I have small app which downloads question papers from a server using Service. I need to implement a "Cancel All" action directly in notification there. Usually, it's pretty simple. I just need to stop a service which I can do. But I don't know how to implement code to stop service in notification. I guess I have to do something with PendingIntent.
Edit 1: After @Shaishav's answer, I tried this:
@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();
}
};
and
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's manifest declaration:
<service android:name=".DownloadService" android:enabled="true">
</service>