在Android中,我使用Timer类每秒检查手机中的wifi连接,因为我想打开GPS,当设备不使用wifi时。但它显示我致命的Timer-0 RunTimeException。
这是我的计时器功能
public void checkWifi()
{
Timer timer = new Timer();
TimerTask hourlyTask = new TimerTask() {
@Override
public void run()
{
boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting();
if (!isWifi) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
}
};
timer.schedule(hourlyTask, 0l, 1000);
}
这是我的LogCat
02-14 02:52:53.126: E/AndroidRuntime(1539): FATAL EXCEPTION: Timer-0
02-14 02:52:53.126: E/AndroidRuntime(1539): Process: com.example.gpsco11wifialert, PID: 1539
02-14 02:52:53.126: E/AndroidRuntime(1539): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
02-14 02:52:53.126: E/AndroidRuntime(1539): at android.os.Handler.<init>(Handler.java:200)
02-14 02:52:53.126: E/AndroidRuntime(1539): at android.os.Handler.<init>(Handler.java:114)
02-14 02:52:53.126: E/AndroidRuntime(1539): at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:221)
02-14 02:52:53.126: E/AndroidRuntime(1539): at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:221)
02-14 02:52:53.126: E/AndroidRuntime(1539): at android.location.LocationManager.wrapListener(LocationManager.java:844)
02-14 02:52:53.126: E/AndroidRuntime(1539): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:857)
02-14 02:52:53.126: E/AndroidRuntime(1539): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:454)
02-14 02:52:53.126: E/AndroidRuntime(1539): at com.example.gpsco11wifialert.GpsC011Wifi$MyLocationListener$4.run(GpsC011Wifi.java:213)
02-14 02:52:53.126: E/AndroidRuntime(1539): at java.util.Timer$TimerImpl.run(Timer.java:284)
答案 0 :(得分:1)
正如logcat中的错误所示,您是从工作线程调用它,使用Handler's
或AsyncTask
来执行此操作。
但是通过查看您的要求,我建议您使用BradcastReceiver
来监听无线状态。
对于Broadcastreceiver:BroadcastReceiver when wifi or 3g network state changed
对于处理程序:Android + FATAL EXCEPTION: Timer-0 (Removing ImageView using timer)
答案 1 :(得分:0)
我知道这根本不可行但你仍然可以试试这个以避免这个错误。或者如果您不想使用它,那么您可以尝试Asynctask类来解决您的问题。
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
这将删除您的错误。