Paras Sidhu
Paras Sidhu

Reputation: 670

Implementing Action In Notification In Android

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.

I need to implement Cancel All button under first notification

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>

Upvotes: 0

Views: 87

Answers (1)

Shaishav
Shaishav

Reputation: 5312

Within your Service class, instantiate a BroadcastReceiver and make sure you register it with a custom Intent-Filter. Now, add the action for firing that intent via a PendingIntent in your notification. Within the onReceive() of your BroadcastReceiver, do your stuff with the cancelling of downloads, etc.

EDIT: Adding code example:

Define your Service class as:

public class YourService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        ...
        registerReceiver(stopReceiver, new IntentFilter("just.some.random.fixed.string"));
        ...
    }

    // Defining the receiver
    private final BroadcastReceiver stopReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Methods to stop downloads
            stopSelf();
        }
    };

}

Now, remember to launch the Intent in for the Receiver in your notification as:

Intent stop_intent = new Intent("just.some.random.fixed.string");
PendingIntent stop_pi = PendingIntent.getBroadcast(context, NUM, stop_intent, PendingIntent.FLAG_CANCEL_CURRENT);

NotificationCompat.Builder notif = new NotificationCompat.Builder(this)
    ...
    .addAction(0, "CANCEL", stop_pi);

Upvotes: 1

Related Questions