2013-01-09 54 views
0

我試圖通過意圖傳遞我的價值,如果它是從Activity到另一個Activity,那麼它的工作良好。但是這次是從活動到服務。我認爲這是正確的方法?但我得到一個錯誤服務類如何將價值從活動傳遞到服務

我的動態

@Override 
    protected void onPause() { 
     // TODO Auto-generated method stub 
     myLocation.disableCompass(); 
     super.onPause(); 
     locationManager.removeUpdates(this); 


    Intent intent = new Intent(this, LocationLoggerService.class); 
    intent.putExtra("midllat", midllat); 
    intent.putExtra("midlongi", midlongi); 
    startActivity(intent); 

} 

我的服務類

@Override 
public void onCreate() { 
    // Find my current location 
    locationManager = (LocationManager) this 
      .getSystemService(Context.LOCATION_SERVICE); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
      2000, 0, this); 
    Criteria crit = new Criteria(); 
    towers = locationManager.getBestProvider(crit, false); 
    Location location = locationManager.getLastKnownLocation(towers); 
    Toast.makeText(this, "The app is know running in the background", 
      Toast.LENGTH_LONG).show(); 
    gm = new GoogleMaps(); 

我得到一個錯誤的getIntent()它無法找到該方法,它是因爲在服務類中嗎?該怎麼辦?

Intent intent = getIntent(); 
    String test1 = intent.getStringExtra("midllat"); 
    String test2 = intent.getStringExtra("midlongi"); 

    midllat = Double.parseDouble(test1); 
    midlongi = Double.parseDouble(test2); 

} 
+0

檢查此問題:http://stackoverflow.com/questions/5229370/how-to-pass-a-value-in-services?rq=1 – JafarKhQ

+0

你會得到什麼錯誤? – alex

+0

我剛纔說過嗎? @alex ..它站在那裏 我在getIntent()中遇到錯誤它找不到方法,是因爲它在服務類中嗎?該怎麼辦? – Zaz

回答

0

一個問題肯定是這樣的:

startActivity(intent); 

如果你想開始一個Service,你不應該叫startActivity。改爲嘗試startService

假設你只是忘了在你的問題中改變它,你指出的另一個問題是getIntent。 A Service沒有該方法。這是一種Activity方法。服務通常與許多意圖有關,通常是同時發生的,所以getIntent方法不會有意義。仔細閱讀Service的文檔,尤其是lifecycle section

您可能想要將您的Intent相關代碼放在onStartCommand中。

+0

@Zaz如果這個答案充分解決了你原來的問題,那麼繼續並接受它。就你的崩潰而言,我建議你通讀堆棧跟蹤並嘗試理解這條消息並嘗試自己修復。如果你無法弄清楚,那麼隨意創建一個包含該堆棧跟蹤的詳細信息的新問題。 – kabuko

相關問題