Mi código está trabajando en lollipop
y a continuación, pero no parece funcionar marshmallow
y arriba. Estoy tratando de conectar a la específica SSID
todo el tiempo, es necesario volver a conectar a la SSID
incluso si pierdo conexión.
Aquí está mi código.
//Connect to SSID if WiFi is Enabled
public class ConnectToSSID extends AsyncTask<String, String, Boolean>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(MainActivity.this, "Connecting...",
"Connecting to \""+SSID+"\" Please Wait...", true);
}
@Override
protected Boolean doInBackground(String... params) {
final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", SSID);
wifiConfig.preSharedKey = String.format("\"%s\"", NetworkPass);
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
SystemClock.sleep(10000);
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return wifi.isConnected();
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progress.dismiss();
Log.e("result","r:"+result);
if(result){
Toast.makeText(MainActivity.this,"Successfully Connected to "+SSID,Toast.LENGTH_LONG).show();
conctTaskMain = new connectTaskMain();
conctTaskMain.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//startService();
}else{
timer.schedule(new TimerTask(){
@Override
public void run(){
conctTaskMain = new connectTaskMain();
conctTaskMain.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);}
}, 1000);
Toast.makeText(MainActivity.this,"Error Connecting to "+SSID,Toast.LENGTH_LONG).show();
}
}
}