2011-09-02 63 views
0

我有一個由如何從活動調用服務?

   Intent dialogIntent = new Intent(getBaseContext(), dialog.class); 
       dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       getApplication().startActivity(dialogIntent); 

開始的活動相關的服務,但我不知道如何在這個新的活動結束到服務通過一個電話?

請注意,「startActivityForResult」不適用於服務。 ;)

另一方面,也許有一些「當焦點回來」監聽服務?

謝謝!

編輯:

活動結束由

Intent dialogIntent = new Intent(getBaseContext(), TotalKeyboard.class); 
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
getApplication().startActivity(dialogIntent); 

finish(); 

然而這一點,在服務,沒有獲得通話

 @Override public void onStart(Intent intent, int startid) 
    { 
     Toast.makeText(getApplicationContext(), "aaa!", Toast.LENGTH_SHORT).show(); 
    } 
+0

我認爲最好告訴我們爲什麼你想這樣做。也許有更好的解決方案。 –

+0

基本上我想要一個帶有選項的對話框出現並讓服務知道,用戶選擇了什麼。由於該服務無法顯示對話框,因此我爲其創建了一個活動。即啓動服務和活動,啓動對話。當用戶做出選擇時,活動結束。現在只需要讓服務知道,活動已完成。 – Roger

回答

2

當您嘗試start service這是already running那麼它的onCreate方法不會接到呼叫,但它的onStart()方法接到呼叫......您可以使用此屬性來滿足您的需要...

+0

嗯......在我的服務中找不到onStart()方法,無法添加它。 – Roger

+0

覆蓋此方法:public void onStart(Intent intent,int startid){\t} –

+0

不會引發任何錯誤,但似乎也不會執行任何操作。我應該放什麼(意圖意圖,int startid)? – Roger

2

你永遠不會得到foucsService。我不確定你想達到什麼目的,也許這不是最好的解決方案,但是你可以從Activity到到Service並在你的Service類中聲明一個方法,然後你可以從你的Activity之後調用該方法,之後你是bound爲您服務。

編輯:您可以通過創建一個看起來像對話框的Activity來模擬Service中的對話框顯示。您可以通過設置theme屬性來實現您的AndroidManifest.xml

<activity 
     android:name="myPackages.ui.DialogActivity" 
     android:theme="@android:style/Theme.Dialog" 
     android:launchMode="singleInstance" 
     android:excludeFromRecents="true" 
     android:finishOnTaskLaunch="true" /> 

你可以聲明在一個methodService讓我們說:

public void performAction(boolean userChoice){ 
     //implementation 
    } 

,並在您DialogActivity類,你可以boundService類並按下按鈕,您可以撥打:

mBoundService.performAction(true); 

mBoundService.performAction(false); 

根據用戶的選擇。

1

總之,活動本身必須處理這一點。

+0

怎麼樣?即活動如何告訴服務「我已完成,現在就由您決定」。 :) – Roger

+0

你需要在這種情況下使用回調.... – Richa

+0

Dialog Activity有不同的監聽器,例如:OK,Cancel。你可以調用finish();並告訴你的服務現在你的電話 –