我有一个在后台运行的服务来获取数据。我想在获得之前检查连接性。
public class DataManager extends Thread {
static final long DELAY = 170000;
Context c;
String stop;
public DataManager(Context argContext) {
c = argContext;
stop = "F";
}
public void StopPlease()
{
stop = "T";
}
@Override
public void run() {
while (true) {
try {
if (stop=="F")
{
if(Functions.isOnline(c))
{
//run the data table loaders for each data type
Log.i("MobileViaNetData", "running aircraft data update");
DataLoader_Aircraft acloader = new DataLoader_Aircraft(c);
acloader.run();
Thread.sleep(DELAY);
}
else
{
Thread.sleep(DELAY);
Toast.makeText(c, "NOT CONNECTED AT THIS TIME", Toast.LENGTH_LONG).show();
}
}
else {
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Functions {
public static boolean isOnline(Context context)
{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
return true;
}
return false;
}
}
这很有效。但是,如果我将其更改为“if(!Functions.isOnline(c))”,则检查(当没有Wi-Fi时)它会抛出错误
10-24 13:59:57.970: ERROR/AndroidRuntime(2972): FATAL EXCEPTION: Thread-12
10-24 13:59:57.970: ERROR/AndroidRuntime(2972): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
这是检查连通性的正确方法吗?
答案 0 :(得分:0)
您正在正确检查连接,但是您的线程正在绊倒。您应该尝试使用AsyncTask或IntentService,而不是访问原始线程。对于您的特定实例,我将DataManager更改为AsyncTask,并基本上从您的run()
函数逐字复制代码并将其放入doInBackground()
方法中。