我有一個小應用程序,它使用服務從服務器下載問題論文。我需要直接在通知中執行「全部取消」操作。通常情況下,這很簡單。我只需要停止一項我可以做的服務。但我不知道如何實現代碼來停止通知服務。我想我必須對PendingIntent做些什麼。在Android中的通知中實施操作
編輯1: @ Shaishav的回答後,我嘗試這樣做:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
MyApp x = (MyApp)getApplicationContext();
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
registerReceiver(stopReceiver, new IntentFilter("Paras"));
// If we get killed, after returning from here, restart
// I tried changing it to START_NOT_STICKY but still service restarted.
return START_STICKY;
}
private final BroadcastReceiver stopReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Methods to stop downloads
Intent i = new Intent(getApplicationContext(),DownloadService.class);
stopService(i);
notificationManager.cancelAll();
stopSelf();
}
};
和
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
try {
MyApp x = (MyApp) getApplicationContext();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent stop_intent = new Intent("Paras");
PendingIntent stop_pi = PendingIntent.getBroadcast(getApplicationContext(), 0, stop_intent, PendingIntent.FLAG_CANCEL_CURRENT);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_file_download_deep_orange_a400_18dp)
.setContentTitle("Downloading")
.setContentText("Hold on...")
.setAutoCancel(true)
.addAction(0, "Cancel All Downloads", stop_pi);
notificationManager.notify(x.ID, notificationBuilder.build());
Log.i("Paras", "onHandleIntent: " + x.filename + x.url + " " + x.ID);
initDownload(x.filename, x.url, x.ID);
}catch (Exception ex){
}
}
}
服務的艙單申報:
<service android:name=".DownloadService" android:enabled="true">
</service>
這裏是你的問題的解決方案[http://stackoverflow.com/questions/12526228/how-to-put-media-controller-button-on-notification-bar](http://stackoverflow.com/questions/ 12526228 /如何把媒體控制器按鈕通知欄) –