0
我使用Timer和TimerTask在我的服務,我調度GPS定期檢查使用此方法@服務在單獨的線程來處理 - 的onCreate()requestLocationUpdates()和removeUpdates(),無法使用的TimerTask
scheduleAllGPST.scheduleAtFixedRate(new AllGPSTimer(), 0,
everyInterval);
代碼段從我的服務類:
//class inside service class
class AllGPSTimer extends TimerTask {
public void run() {
if (!canGetLocation) stopLocationRequest();
else requestLocation();
}
}
// Service class method
public void requestLocation() {
try {
locListener = new mylocationlistener();
locationManager.requestLocationUpdates(provider, 0, 0, locListener);// Error happens at this line
}
catch (Exception e) {
e.printStackTrace();
}
}
public void stopLocationRequest() {
try {
locationManager.removeUpdates(locListener);// And also it happens at this line
}
catch (Exception e) {
e.printStackTrace();
}
}
我收到此錯誤:
Error :
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:139)
at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:137)
at android.location.LocationManager._requestLocationUpdates(LocationManager.java:708)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:630)
at com.mobile.sales.GPSService.requestLocation(GPSService.java:146)
at com.mobile.sales.GPSService$AllGPSTimer.run(GPSService.java:140)
at java.util.Timer$TimerImpl.run(Timer.java:289)
從Error,我猜這個requestLocationUpdates()和 removeUpdates()只能從Service類的主線程中使用,而不能從主線程的派生線程中使用。我猜對了嗎?
那麼有沒有像Activity類的runOnUiThread(runnable)Service類的方法?
請幫忙,我應該處理位置API方法和計時器任務的衍生線程?也讓我知道如果我猜測它是錯誤的。
謝謝!
看這個問題http://stackoverflow.com/questions/3589963/locationmanager-requestlocationupdates-and-timertask-in-android – southerton
@southerton :我看到了整個事情和源代碼也 那麼,這意味着我們不能使用定時器,而使用locationApis? 如果有什麼方法,你可以簡要介紹嗎? – Pradeepraj
你好@ Pradeepraj你注意不到,我們不應該調用線程內的任何硬件檢查控件。我們應該使用Handler。以下鏈接將幫助你。 http://developer.android.com/reference/android/os/Handler.html – itsrajesh4uguys