I have multiple notifications, each notification has two buttons (Start and Pause) like the below picture and each notification belongs to a unique user.
Each notification has a unique notification ID based on each user name.
I use pending intent and putExtra to deal with action buttons but it does not work.
putExtra will send, useName is unique for each user:
intentPause.putExtra(userName,"pause");
intentResume.putExtra(userName,"start");
I think that the problem is I don't know which notification I am dealing with each time I click an action button so that BroadcastReceiver onReceive method which receives String from putExtra. How can I get String userName in intentPause.putExtra(userName,"pause"); in order to put it in String action = intent.getStringExtra(userName);
Sorry for my bad English.
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra(userName);//Dont know how to get UserName from PutExtra
if (action.equals("resume")) {
timerResume();
Log.d("Action:", action);
} else if (action.equals("pause")) {
timerCancel();
Log.d("Action:", action);
}
}
public void timerResume(){
MainActivity.timerMap.get(userName).countDownTimer.start();
Log.d("Test resume:",userName);
}
public void timerCancel(){
MainActivity.timerMap.get(userName).countDownTimer.cancel();
Log.d("Test cancel:",userName);
}
Based on the answer of @alexal1. I have tried but getStringExtra in BroadCast Receiver always return NULL
Manifest.xml
<receiver android:name=".NotificationReceiver2">
<intent-filter>
<action android:name="com.tuan.timer.ACTION_PAUSE" />
<action android:name="com.tuan.timer.ACTION_RESUME" />
</intent-filter>
</receiver>
NotificationReceiver2
public class NotificationReceiver2 extends BroadcastReceiver {
public static final String ACTION_PAUSE= "com.tuan.timer.ACTION_PAUSE";
public static final String ACTION_RESUME= "com.tuan.timer.ACTION_RESUME";
public static final String EXTRA_USER_NAME = "user_name";
String userName;
String action;
@Override
public void onReceive(Context context, Intent intent) {
action = intent.getAction();
Bundle bundle=intent.getExtras();
//getStringExtra return NULL
Log.d ("myApplication", bundle2string(bundle) + " is a key in the bundle");
Log.d ("get extra user name", intent.getStringExtra(EXTRA_USER_NAME) );
if(action != null){
Log.d("Action: ",action );
}
else{
Log.d("Action: ","is null" );
}
}
MainActivity
intentPause=new Intent(this, notificationReceiver2.class);
intentPause.setAction(NotificationReceiver2.ACTION_PAUSE);
intentPause.putExtra(EXTRA_USER_NAME,userName);
Log.d("Put Extra:",NotificationReceiver2.ACTION_PAUSE);
pendingIntentPause=PendingIntent.getBroadcast(this,notificationId,this.intentPause,PendingIntent.FLAG_UPDATE_CURRENT);
intentResume=new Intent(this, notificationReceiver2);
intentResume.setAction(NotificationReceiver2.ACTION_RESUME);
intentResume.putExtra(EXTRA_USER_NAME,userName);
Log.d("Put Extra:",NotificationReceiver2.ACTION_RESUME);
