Eli Revah
Eli Revah

Reputation: 3676

Notification tap event without showing an activity?

I want to assign an event that will fire when a notification is being tapped on, without showing an activity (like explained here).

How can I do that?

Upvotes: 0

Views: 76

Answers (1)

Raghav Sood
Raghav Sood

Reputation: 82553

You can do this by registering a Broadcast Receiver. This way, you can run code in the receiver when your notification is clicked, without showing any UI whatsoever if you want.

Basic receiver code:

public class Provider extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        //Your code here

    }
}

In the manifest:

<receiver android:name="Provider" />

Sample code for the notification:

public static void showNotification(Context context) {
    CharSequence title = "title";
    CharSequence message = "text";

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(<image>, title, System.currentTimeMillis());
    notification.flags = Notification.FLAG_ONGOING_EVENT;

    Intent notificationIntent = new Intent(context, Provider.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, 0);

    notification.setLatestEventInfo(context, title, message, pendingIntent);
    notificationManager.notify(<notification id>, notification);
}

Upvotes: 1

Related Questions