我编写了启动 wifi 的代码,然后(每秒)检查 wifi 是否已连接。问题是它持有主线程,直到连接可用。我需要帮助处理此代码。
// Sevice
// wifi checking part
ConnectivityManager Cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo Ni = Cm.getActiveNetworkInfo();
WifiManager wiM = (WifiManager) getSystemService(WIFI_SERVICE);
wiM.setWifiEnabled(true);
int i=0;
while (Ni == null) {
Ni = Cm.getActiveNetworkInfo();
i++;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i > 29) {
break;
}
}
if(Ni.isConnected()) {
Intent intent1 = new Intent(this, MainActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent1, 0);
noti = new NotificationCompat.Builder(this)
.setContentTitle("app")
.setContentText("running")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pendIntent)
.setPriority(Notification.PRIORITY_MIN)
.build();
startForeground(12345, noti);
new myTask().execute(httpAddress);
DelayedShutdown(millis);
} else {
}