Reputation: 587
I am currently building an android app which needs to work through notification bar's action buttons.
I have added the notification bar and the action buttons. I have also added a BroadcastReceiver
to perform some action on button click. My problem is that the actions are performed based on the title of the action button clicked. Please guide me in how to get the title of the clicked button.
This is my notification creation code:
Intent intent = new Intent();
intent.setAction(AppConstants.YES_ACTION);
// Open receiver
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
//Create Notification using NotificationCompat.Builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
// Set Icon
.setSmallIcon(R.mipmap.ic_launcher)
// Set Ticker Message
// .setTicker(getString(R.string.notificationticker))
// Set Title
.setContentTitle(getString(R.string.app_name))
// Set Text
.setContentText(getString(R.string.notificationtext))
// Add an Action Button below Notification
.addAction(R.mipmap.ic_launcher, "Action Button", pIntent)
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Dismiss Notification
.setAutoCancel(true);
for(int l = 0; l<btnNames.length; l++){
if(!btnNames[l].isEmpty()){
builder.addAction(R.mipmap.ic_launcher, btnNames[l],pIntent);
// intent.putExtra("Btn"+(l+1), btnNames[1]);
}
}
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
Below is the broadcast receiver code:
public class notificationReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String notificationAction = intent.getAction();
//the title retrieval code goes here
if(notificationAction.equals(AppConstants.YES_ACTION)){
//some work is done here
}
}
}
Upvotes: 0
Views: 184
Reputation: 1006614
Step #1: Move all of your Intent
/PendingIntent
/Notification
creation logic inside of the loop
Step #2: Put an identifier of the action button in as an extra to the Intent
that you use for the PendingIntent
Step #3: Use a distinct number for each PendingIntent
for the second parameter to the getBroadcast()
method, so you get different PendingIntent
instances for each
Step #4: Have your BroadcastReceiver
read the extra to determine the action that was clicked
Or...
Step #1: Move all of your Intent
/PendingIntent
/Notification
creation logic inside of the loop
Step #2: Use a unique action string in each of the Intent
objects
Step #3: Have your BroadcastReceiver
read the action string to determine the action that was clicked
Or...
Step #1: Use different BroadcastReceivers
for each action button
Upvotes: 2