2015-05-24 131 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()停止服务,或者等到它完成它自己。如果需要示例我可以显示。所以请问。