2013-10-26 52 views
0

我的問題是這一個, Android LocationLister implemented in IntentService never execute the OnLocationChanged() method但不幸的是我無法理解這一點,我從Android設備獲取位置的代碼工作正常活動,但是當涉及到意圖服務時,onLocationChanged()方法永遠不會被調用。從意圖服務的位置更新(onLocationChanged永遠不會被調用)

服務的其他部分運行良好,因爲我也在同一服務中實現了通知管理器示例來跟蹤各種變量的值,但由onLocationChanged()修改的變量永遠不會被修改,描述該方法沒有得到執行。 請幫助

+0

你的代碼在哪裏? – GrIsHu

回答

0

據我所知,位置傳感器需要在UI線程中運行。一個活動在那裏運行,但一個服務在後臺運行。

在您的代碼中添加一些密集的日誌記錄和異常處理以查明。

如果這是原因,那麼有一種方法可以創建並註冊Looper。讓我知道,我可以去我的代碼搜索

+0

我已經閱讀了一些關於stackoverflow的問題,我的代碼可能太快了,可能會發生onLocationChanged()方法從未返回並且服務因此在它之前被銷燬,但是我得到了我所需的,我檢索了最後一次位置更新從getLastKnownLocation(),現在我的應用程序工作正常謝謝你! – nobalG

2

IntentService不會等待您的onLocationChangedListener,如果您的IntentService的最後一部分是註銷您的位置更改偵聽器,那麼存在您的問題。

您可以做的是將您的IntentService轉換爲常規服務。檢查不同的操作,其中之一是您收到新位置時的下一步。

private class MyLocationListener implements LocationListener { 
    public void onLocationChanged(Location location) { 
     Intent intent = new Intent(this,MyService.class); 
     intent.setAction("LOCATION_RECEIVED"); 
     intent.putExtra("locationUpdate",location); 
     locationManager.removeUpdates(this); 
     this.startService(intent); 
    } 
    public void onStatusChanged(String s, int i, Bundle bundle) {} 
    public void onProviderEnabled(String s) {} 
    public void onProviderDisabled(String s) {} 
} 

,並在您服務...

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    if (intent!=null) { 
     String action = intent.getAction(); 
      if (action!= null) { 
       if (action.equals("LOCATION_RECEIVED")) { 
        Location location = null; 
        if (intent.hasExtra("locationUpdate")) { 
         location = intent.getExtras().getParcelable("locationUpdate"); 
         //Process new location updates here 
        } 

另一種方法是使用掛起的意圖您LocationListener的,但它會爲上面的代碼相同的效果。第三種方法是從OnLocationChangedListener發佈一個可運行的IntentService(我個人還沒有試過這個)。

如果你可以在這裏分享一些代碼,將不勝感激。如果您還有其他問題。當我正在從事類似項目,從服務中獲取位置時,我可能會有所幫助。

相關問題