我已经编写了启动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 {
}
答案 0 :(得分:1)
这个助手类可能能够帮助你
https://gist.github.com/bclymer/6708605
主要是runInBackgroundThenUi()
方法,将等待WiFi的代码放在后台参数中的runnable中,然后在ui param中连接wifi后运行的代码。
喜欢这个
ThreadManager.runInBackgroundThenUi(new Runnable() {
@Override
public void run() {
// wait for that tasty WiFi
}
}, new Runnable() {
@Override
public void run() {
// GUYS I HAVE THE WIFI!!
}
});
免责声明,我写了这堂课。我在很多(所有)应用程序中使用它。