3

i have a notification which i'm calling from a service. I want to call the service again on notification click. But the notification click is not able to get inside the method.

Intent intent = new Intent(this, MyService.class).setAction(ACTION_1);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.food)
                    .setContentTitle("notification")
                    .setContentText("near by you!");
   NotificationManager mNotificationManager =(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);

Method that i want to call is

if (ACTION_1.equals(resultPendingIntent)) {
        getRecommendation();
    } 
        mBuilder.setContentIntent(resultPendingIntent);
    mNotificationManager.notify(id, mBuilder.build());

i have tried following link but not able to resolve my problem. How to execute a method by clicking a notification

Community
  • 1
  • 1
user3804161
  • 45
  • 2
  • 7

2 Answers2

12

You can specify a Broadcast in your Service and launch that via a PendingIntent in your notification.

Intent stopIntent = new Intent("my.awersome.string.name");
PendingIntent stopPi = PendingIntent.getBroadcast(this, 4, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT);

Then, in your notification builder:

NotificationCompat.Builder builder;
builder = new NotificationCompat.Builder(context)
    ...     
    .setContentIntent(stopPi);

In your Service you can setup a BroadcastReceiver as:

private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Code to run
    }
};

You register this receiver in your Service (possibly in onStartCommand()) only using:

registerReceiver(myReceiver, new IntentFilter("my.awersome.string.name"));

Your Service MUST be running for this to work.

Shaishav
  • 5,282
  • 2
  • 22
  • 41
  • 1
    You are a life saver. This is exactly what I was looking for. Works like a charm. Thanks!! – John Spax Jun 05 '18 at 11:58
  • where to setup Broadcast in service –  Feb 08 '19 at 07:39
  • @VipulChauhan You can set it up as soon as you launch the notification but, make sure that you unregister it as soon as you're done with it (and also in onDestroy()) – Shaishav Feb 08 '19 at 07:51
  • thanks for your fast reply but i already done with it now i am stuck with how to set custom layout for notification –  Feb 08 '19 at 08:10
  • @VipulChauhan thats an entirely different problem. You can try finding a solution on SO or create a new issue here. – Shaishav Feb 08 '19 at 08:27
0

Better option is to try How to execute a method by clicking a notification ..but be careful because of the static class

Community
  • 1
  • 1
user3804161
  • 45
  • 2
  • 7