2015-05-24 127 views
4

我有Service正在運行。並在其onStartCommand我做startforeground,以避免系統查殺。如何從自己的前臺通知中停止服務

public int onStartCommand(Intent intent, int flags, int startId) { 
    if (ACTION_STOP_SERVICE.equals(intent.getAction())) { 
     Log.d(TAG,"called to cancel service"); 
     manager.cancel(NOTIFCATION_ID); 
     stopSelf(); 
    } 
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
    builder.setContentTitle("abc"); 
    builder.setContentText("Press below button to stoP."); 
    builder.setPriority(NotificationCompat.PRIORITY_HIGH); 
    builder.setSmallIcon(R.drawable.ic_launcher); 

    Intent stopSelf = new Intent(this, SameService.class); 
    stopSelf.setAction(this.ACTION_STOP_SERVICE); 
    PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf,0); 
    builder.addAction(R.drawable.ic_launcher, "Stop", pStopSelf); 
    manager.notify(NOTIFCATION_ID, builder.build()); 
} 

但按下按鈕後,PendingIntent不工作,我的activity是沒有得到通過它停止。

有人可以告訴我,我在這裏做什麼或任何其他解決方案停止從自己做的前景notification服務。

謝謝

+0

你是一個傳奇! – Maysara

回答

9

回答我自己的問題,爲了像我這樣的其他發現者。

問題已在該線下方

PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf,0); 

這0到底是問題的原因。 我用PendingIntent.FLAG_CANCEL_CURRENT代替了它,它現在可以工作。

改正的代碼是:

PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf,PendingIntent.FLAG_CANCEL_CURRENT); 

請檢查FLAG_CANCEL_CURRENT or FLAG_UPDATE_CURRENT更多的解釋。

1

上述想法將無法正常工作。服務應該先阻止它的線程,所以有時你會看到奇怪的行爲。你應該在你的循環/計算方法中加入一些標誌並且調用「return;」,並且你可以通過stopself()停止服務,或者等到它完成它自己。如果需要示例我可以顯示。所以請問。