2014-04-05 34 views
1

在我的應用我有一個後臺服務器和服務器類裏面我有定時器,內部定時器我有一個的LocationManager找到的位置:如何在Timer中使用LocationManager?

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

        LocationListener locationListener = new MyLocationListener(); 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 5000, 10, 
          locationListener); 

但在這裏我得到這個錯誤:

java.lang.runtimeexception can't create handler inside thread that has not called looper.prepare(); 

我這裏的問題如何使用定時器內的locationManager?

回答

2

看後臺服務與活動不同,當您使用runOnUiThread這僅僅是可能的活動要小心,或者如果您使用線程內服務類,你可以做到這一點是這樣的: 服務類寫這裏面:

static Activity ac; 

    public static void setActivity(Activity a) { 
     ac = a; 

    } 

,並在您的活動來實現這個目的:

MyService.setActivity(this); 

現在這個線程就像這樣:

(ac).runOnUiThread(new Runnable() { 

    @Override 
public void run() {}); 

我強烈推薦給你,就像我做的一樣。

+0

最好的答案感謝這就是我想:) –

+0

請不要這樣做。在這裏看到第一個答案:http://stackoverflow.com/questions/7298375/get-activitys-reference-from-a-service 正確的解決方案要簡單得多。只需在服務中創建一個處理程序並使用其後處理方法即可。 –

1

如果您不知道Looper線程是什麼,那麼異常消息可能看起來很神祕,但它基本上意味着它的含義:您不能在線程中創建Handler(或任何包含Handler的對象)不是一個Looper。定時器線程不是循環。 Android中的很多東西都只是在UI線程(這是一個Looper)上創建的。

無論如何,試圖在定時器中使用LocationListener「內部」並沒有什麼意義。 LocationListener的方法由系統調用,而不是由您的代碼調用。我建議搜索並閱讀事件驅動編程

0
((Activity) getBaseContext()).runOnUiThread(new Runnable() { 

      @Override 
      public void run() { 
       // TODO Auto-generated method stub 
       LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

        LocationListener locationListener = new MyLocationListener(); 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 5000, 10, 
          locationListener); 

      } 
     }); 
+0

我得到這個錯誤: 未定義MyService類型的runOnUiThread(new Runnable(){})方法。 –

+0

((活動)getBaseContext())。runOnUiThread(新的Runnable(){ \t \t \t \t \t \t @Override \t \t \t公共無效的run(){ \t \t \t \t // TODO自動生成方法存根 \t \t \t \t \t \t \t} \t \t}); –

+0

定時器0,還沒有工作:( –

相關問題