Hendra Anggrian
Hendra Anggrian

Reputation: 5858

Android - where to add onClickListener on custom notification?

I have my custom notification:

Intent myIntent = new Intent(this, MainActivity.class);
PendingIntent myPendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0);

// build notification
// the addAction re-use the same myIntent to keep the example short
Notification myNotification  = new Notification.Builder(this)
    .setContentTitle("My App")
    .setContentText("Service is not running")
    .setSmallIcon(R.drawable.ic_launcher)
    .setContentIntent(myPendingIntent)
    .setAutoCancel(true)
    .addAction(R.drawable.ic_action_mic, "Start Service", myPendingIntent).build();

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(0, myNotification); 

I'm simply asking where should I put onClickListener to my button generated by .addAction()?

Upvotes: 1

Views: 3127

Answers (2)

Eldhose M Babu
Eldhose M Babu

Reputation: 14510

While clicking on the notification, your MainActivity will get opened.

So in onCreate of your activity, you can put your onClick Code.

To be specific, add a line above your pending intent creation:

myIntent.putExtra("FromNotification", true);

Then in the onCreate of your MainActivity check like :

if (getIntent() != null && getIntent().getBooleanExtra("FromNotification", false)) {
    // Do your onclick code.
}

Upvotes: 1

ianhanniballake
ianhanniballake

Reputation: 199805

The third parameter to addAction is a PendingIntent that should correspond to what action you want to take when that action is clicked. This can either call a BroadcastReceiver or a Service that then handles the action and does whatever is required.

Upvotes: 1

Related Questions