2016-12-28 131 views
2

我有兩個通知操作,一個停止服務,一個重新啓動它。 我成功啓動該服務,但我不能使用此代碼停止:Android - 通知pendingIntent停止服務

PendingIntent show = PendingIntent.getService(this, 1, svc, PendingIntent.FLAG_UPDATE_CURRENT); 
PendingIntent hide = PendingIntent.getService(this, 1, svc, PendingIntent.FLAG_CANCEL_CURRENT); 

任何想法?

不是重複的,因爲我的問題具體是關於通知操作,而不是按鈕(我沒有問題讓我的按鈕停止並啓動服務)。

+5

可能重複的[PendingIntent啓動和停止服務](http://stackoverflow.com/questions/20572216/pendingintent-to-launch-and-stop-a-service) –

+1

爲什麼你使用相同的請求兩種不同行爲的代碼?我認爲你與PendingIntent標誌混淆。這些標誌用於控制通知。 – Ayaanp

回答

2

僅此標誌不會停止服務。我建議你制定停止行動,而不是發射一個自定義BroadcastReceiver類,該類在其onReceive()內運行stopService()方法。讓我知道你是否需要幫助設置更詳細的內容。

編輯答案:

更改IntentPendingIntent的隱藏行動,這一點:

Intent intentHide = new Intent(this, StopServiceReceiver.class); 

PendingIntent hide = PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(), intentHide, PendingIntent.FLAG_CANCEL_CURRENT); 

然後使StopServiceReceiver這個樣子,哪裏ServiceYouWantStopped.class是要停止的服務:

public class StopServiceReceiver extends BroadcastReceiver { 
    public static final int REQUEST_CODE = 333; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Intent service = new Intent(context, ServiceYouWantStopped.class); 
     context.stopService(service); 
    } 
} 

確保您剛剛製作的BroadcastReceiver已在您的清單文件中聲明e:

<receiver 
    android:name=".StopServiceReceiver" 
    android:enabled="true" 
    android:process=":remote" /> 

希望這有助於!