Search code examples
androidnotificationspush-notificationheads-up-notifications

Notification Action without starting new Activity?


I plan to have a heads up notification that has two Actions: one to Approve a login request and one to Decline a login request. By clicking on either of these actions I wish to fire off a HTTP request to my server and most importantly do not want to start a new Activity or have the user redirected to my app at all.

        Context context = getBaseContext();
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.notificationicon)
            .setContentTitle(notificationTitle)
            .setContentText("Access Request for " + appName + " : " + otp)
            .setDefaults(Notification.DEFAULT_ALL)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .addAction(R.drawable.ic_tick, "Approve", someApproveIntent?  );

Here is my notification builder and after looking around it seems that the addAction method is looking for a new/pendingIntent, which is confusing me as I cannot find any examples online where Intents do not lead to new Activities being fired off.

How would I implement some code (a method maybe) rather then starting a new Activity on each of my Actions?


Solution

  • If you don't want to start an activity you can also wrap a BroadcastReceiver or a Service directly in a PendingIntent.

    Wherever you build your notification...

    Your notification actions will start a service directly.

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)...
    
    Intent iAction1 = new Intent(context, MyService.class);
    iAction1.setAction(MyService.ACTION1);
    PendingIntent piAction1 = PendingIntent.getService(context, 0, iAction1, PendingIntent.FLAG_UPDATE_CURRENT);
    
    builder.addAction(iconAction1, titleAction1, piAction1);
    
    // Similar for action 2.
    

    MyService.java

    IntentServices run in a row one after another. They do the work on a worker thread.

    public class MyService extends IntentService {
      public static final String ACTION1 = "ACTION1";
      public static final String ACTION2 = "ACTION2";
    
      @Override
      public void onHandleIntent(Intent intent) {
        final String action = intent.getAction();
        if (ACTION1.equals(action)) {
          // do stuff...
        } else if (ACTION2.equals(action)) {
          // do some other stuff...
        } else {
          throw new IllegalArgumentException("Unsupported action: " + action);
        }
      }
    }
    

    AndroidManifest.xml

    Don't forget to register the service in manifest.

    <manifest>
      <application>
        <service
            android:name="path.to.MyService"
            android:exported="false"/>
      </application>
    </manifest>