How to add tap action on notification?

android, android-notifications

Solution

You should be using a notification builder:

mMN = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);        

Intent nid = new Intent(MainActivity.this, stopservice.class);
// If you were starting a service, you wouldn't using getActivity() here
PendingIntent ci = PendingIntent.getActivity(MainActivity.this, NOTIFICATION_ID, nid, PendingIntent.FLAG_UPDATE_CURRENT);

Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setContentTitle("TAP")
        .setContentText("Tap here to exit")
        .setTicker("Tap this notification to exit")
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentIntent(ci)
        .setAutoCancel(true); // auto cancel means the notification will remove itself when pressed

mMN.notify(NOTIFICATION_ID, builder.getNotification());

Your code is set to launch the Activity "stopservice" (which technically should be "StopService" with naming conventions), are you sure that class is an Activity?

Also, make sure your Activity is registered in your app's manifest:

<activity android:name="[package-name].stopservice" android:label="@string/app_name"/>

Problem

I want to add a tap action (exit (finish)) to a notification. I'm making a simple app with several classes, and I want them all finished when I tap the notification. Here is my notification code: ``` mMN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification n = new Notification(); n.icon = R.drawable.ic_launcher; n.tickerText = "Tap this notification to exit"; n.when = System.currentTimeMillis(); Intent nid = new Intent(MainActivity.this, stopservice.class); PendingIntent ci = PendingIntent.getActivity(this, 0, nid,PendingIntent.FLAG_UPDATE_CURRENT); CharSequence ct = "TAP"; CharSequence tt = "Tap here to exit"; n.setLatestEventInfo(this,ct,tt,ci); mMN.notify(NOTIFICATION_ID, n); ``` I'm making a reference to `stopservice class` (where it is my stop service code) on `Intent nid`, but I'm not quite sure if it's a correct reference. hope that my question is clear.

Original source