2012-03-31 66 views
1

我試圖通過意圖將數據從活動發送到服務。如何將數據從活動發送到服務

這是在我的活動課

Intent i= new Intent(this,SampService.class); 

    i.putExtra("startTimeHour", timePicker1.getCurrentHour()); 
    i.putExtra("endTimeHour", timePicker2.getCurrentHour()); 
    i.putExtra("startTimeMinute",timePicker1.getCurrentMinute()); 
    i.putExtra("endTimeMinute", timePicker2.getCurrentMinute()); 
    startActivity(i); 

代碼這是我的服務類的代碼

public class SampService extends Service implements Runnable { 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return null; 
} 
public void onCreate() 
{ 
    Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_LONG).show(); 
    String startTimeHour,startTimeMinute,endTimeHour,endTimeMinute; 



} 
public void onStart() 
{ 
    Thread t=new Thread(this); 
    t.start(); 
} 
public void run() { 



} 

回答

4

SampleService是服務,您應該使用startService(i);而不是startActivity(i);然後可以在服務中檢索附加到意圖的數據。

2

你不意圖從活動將數據發送到服務。該活動需要綁定到該服務,然後您在活頁夾上調用方法。請參閱http://developer.android.com/guide/topics/fundamentals/services.htmlhttp://developer.android.com/reference/android/app/Service.html

另一種選擇是讓您的活動向數據發送廣播意圖,您的服務可以設置BroadcastReceiver來偵聽。

你想用什麼服務?也許有一個更容易或更輕的解決方案來解決您的問題。

+0

「您不會將數據從活動發送到具有意向的服務。」 - 是的你是。它是命令模式,使用'startService()'以'Intents'的形式發送命令。引用[文檔](http://developer.android.com/guide/topics/fundamentals/services.html)「啓動服務的多個請求會導致對服務的onStartCommand()的多個相應調用。但是,只有一個請求停止服務(使用stopSelf()或stopService())來停止它。「這與'IntentServices'很好地結合。 – CommonsWare 2012-03-31 14:32:15

+0

@David Wassler我正在使用服務檢查時間值,並在我的開始和結束時間之間啓用無聲模式 – 2012-03-31 14:57:38

+0

好的,那麼即使您的活動不是,也需要服務才能運行。 @Akhil的解決方案應該可以工作。 [這個問題/答案](http://stackoverflow.com/questions/4252371/unable-to-get-data-from-activity-to-service)顯示瞭如何在'startService()'中使用的Intent中傳遞值以及如何在服務中的onStartCommand()中檢索它們。 – 2012-03-31 15:50:12

相關問題