Pending Intent not receiving the putExtraBudle for different notificationId - android

I am using the code of PingService.java https://github.com/android/platform_development/blob/master/samples/training/notify-user/src/com/example/android/pingme/PingService.java
PingService.Java
/**
* PingService creates a notification that includes 2 buttons: one to snooze the
* notification, and one to dismiss it.
*/
public class PingService extends IntentService {
private NotificationManager mNotificationManager;
private String mMessage;
private int mMillis;
NotificationCompat.Builder builder;
public PingService() {
// The super call is required. The background thread that IntentService
// starts is labeled with the string argument you pass.
super("com.example.android.pingme");
}
#Override
protected void onHandleIntent(Intent intent) {
// The reminder message the user set.
mMessage = intent.getStringExtra(CommonConstants.EXTRA_MESSAGE);
// The timer duration the user set. The default is 10 seconds.
mMillis = intent.getIntExtra(CommonConstants.EXTRA_TIMER,
CommonConstants.DEFAULT_TIMER_DURATION);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
String action = intent.getAction();
// This section handles the 3 possible actions:
// ping, snooze, and dismiss.
if(action.equals(CommonConstants.ACTION_PING)) {
issueNotification(intent, mMessage);
} else if (action.equals(CommonConstants.ACTION_SNOOZE)) {
nm.cancel(CommonConstants.NOTIFICATION_ID);
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.snoozing));
// Sets a snooze-specific "done snoozing" message.
issueNotification(intent, getString(R.string.done_snoozing));
} else if (action.equals(CommonConstants.ACTION_DISMISS)) {
nm.cancel(CommonConstants.NOTIFICATION_ID);
}
}
private void issueNotification(Intent intent, String msg) {
mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// Sets up the Snooze and Dismiss action buttons that will appear in the
// expanded view of the notification.
Intent dismissIntent = new Intent(this, PingService.class);
dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);
Intent snoozeIntent = new Intent(this, PingService.class);
snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
// Constructs the Builder object.
builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle(getString(R.string.notification))
.setContentText(getString(R.string.ping))
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
/*
* Sets the big view "big text" style and supplies the
* text (the user's reminder message) that will be displayed
* in the detail area of the expanded notification.
* These calls are ignored by the support library for
* pre-4.1 devices.
*/
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.addAction (R.drawable.ic_stat_dismiss,
getString(R.string.dismiss), piDismiss)
.addAction (R.drawable.ic_stat_snooze,
getString(R.string.snooze), piSnooze);
/*
* Clicking the notification itself displays ResultActivity, which provides
* UI for snoozing or dismissing the notification.
* This is available through either the normal view or big view.
*/
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putExtra(CommonConstants.EXTRA_MESSAGE, msg);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
startTimer(mMillis);
}
private void issueNotification(NotificationCompat.Builder builder) {
mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// Including the notification ID allows you to update the notification later on.
mNotificationManager.notify(CommonConstants.NOTIFICATION_ID, builder.build());
}
private void startTimer(int millis) {
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_start));
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.sleep_error));
}
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_finished));
issueNotification(builder);
}
}
Intent mServiceIntent = new Intent(context.getApplicationContext(), PingService.class);
mServiceIntent.putExtra(Const.EXTRA_MESSAGE, "" + msg);
mServiceIntent.putExtra(Const.ID, reminder_id);
startService(mServiceIntent);
And passing the data to issueNotification method for Action Button intent like
Intent dismissIntent = new Intent(this, PingService.class);
dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
dismissIntent.putExtra(CommonConstants.ID, reminder_id);
PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);
Intent snoozeIntent = new Intent(this, PingService.class);
snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
snoozeIntent.putExtra(CommonConstants.ID, reminder_id);
PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
But i am not getting the ID at the time of Click event of the Action button from issueNotification and passing the intent in onHandleIntent method
It is automatically set to 1 after Notification generation and i am not able to cancel that notification due to wrong notification id set into putExtra of PendingIntent
I am trying with passing different flag like
PendingIntent piDismiss = PendingIntent.getService(this, 0, taken_intent, PendingIntent.FLAG_UPDATE_CURRENT);
Please help me out i am trying it since long time but not getting the correct id.
My putExtra is override with 1 somehow....
Thank you in advnace

After so much reasearching finally got a solution that i need to pass different code in pending intent like
PendingIntent piDismiss = PendingIntent.getBroadcast(this, CommonConstants.NOTIFICATION_ID, dismissIntent, 0);
which is dynamic one and unique one in each Action Button case.
Use Broadcast receiver to achieve this instead of Service ( getBroadcast ).
Thank you.

Related

notification buttons (.addaction) not launching activity

I'm attempting to make a notification that has two buttons which do two different things by running two different activities. The notification and its buttons appear on the notification bar fine, however pressing on either of the buttons fails to launch the designated activity.
Here is the code:
private void addNotification() {
int requestID = (int) System.currentTimeMillis();
NotificationCompat.Builder builder = (android.support.v7.app.NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ibutton)
.setContentTitle("Timer running..")
.setContentText(timerString);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
//Add buttons to notification
//First make the intent
Intent pauseIntent = new Intent(this, pauseActivity.class);
//Wrap it in pending intent to trigger later
PendingIntent pausePendingIntent = PendingIntent.getActivity(this, requestID, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Then add the action to your notification
builder.addAction(R.drawable.pause, "Pause", pausePendingIntent);
//Same again for stop button
Intent stopIntent = new Intent(this, stopActivity.class);
PendingIntent stopPendingIntent = PendingIntent.getActivity(this, requestID, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.stop, "Stop", stopPendingIntent);
// Add as notification
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int mNotificationId = 001;
notificationManager.notify(mNotificationId, builder.build());
}
EDIT: An example of one of the activities I am trying to launch:
public class stopActivity {
public stopActivity() {
MainActivity.stopped = true;
}
}
If there is any easier way of simply changing the value of a variable in MainActivity from the button in the notification bar then I am also keen to hear that but as far as I can tell the only option is to launch a new activity
EDIT: An example of one of the activities I am trying to launch:
public class stopActivity { public stopActivity() {
MainActivity.stopped = true; } }
This is not an Activity. An Activity extends Activity!
This is just a POJO class and you cannot start it by putting it in a PendingIntent the way you are doing.
You would be better off by just using an Intent for MainActivity with an "extra" to change a value in it. Here's an example:
Intent pauseIntent = new Intent(this, MainActivity.class);
pauseIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
pauseIntent.putExtra("pause", true);
PendingIntent pausePendingIntent = PendingIntent.getActivity(this, requestID, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Then add the action to your notification
builder.addAction(R.drawable.pause, "Pause", pausePendingIntent);
Then, in MainActivity.onNewIntent():
if (intent.hasExtra("pause")) {
this.paused = true; // whatever you want to do when "pause" is pressed
}

Heads-up Notification Buttons Not Executing

I have been searching for a few hours, but could not find any solution to my problem. Does anyone know how to make heads-up notification buttons call a broadcast? My code:
Alarm Receiver Notification Builder:
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.alarmicon)
.setContentTitle("Alarm for " + timeString)
.setContentText(MainActivity.alarmLabel.getText().toString())
.setDefaults(Notification.DEFAULT_ALL) // must requires VIBRATE permission
.setPriority(NotificationCompat.PRIORITY_HIGH); //must give priority to High, Max which will considered as heads-up notification
//set intents and pending intents to call service on click of "dismiss" action button of notification
Intent dismissIntent = new Intent(context, notificationButtonAction.class);
dismissIntent.setAction(DISMISS_ACTION);
PendingIntent piDismiss = PendingIntent.getBroadcast(context, 0, dismissIntent, 0);
builder.addAction(R.drawable.alarmoff, "Dismiss", piDismiss);
//set intents and pending intents to call service on click of "snooze" action button of notification
Intent snoozeIntent = new Intent(context, notificationButtonAction.class);
snoozeIntent.setAction(SNOOZE_ACTION);
PendingIntent piSnooze = PendingIntent.getBroadcast(context, 0, snoozeIntent, 0);
builder.addAction(R.drawable.snooze, "Snooze", piSnooze);
// Gets an instance of the NotificationManager service
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//to post your notification to the notification bar with a id. If a notification with same id already exists, it will get replaced with updated information.
notificationManager.notify(0, builder.build());
notificationButtonAction:
public static class notificationButtonAction extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("notificationButtonAction Started");
String action = intent.getAction();
if (SNOOZE_ACTION.equals(action)) {
stopAlarm();
System.out.println("Alarm Snoozed");
MainActivity ma = new MainActivity();
ma.setAlarm(true);
}
else if (DISMISS_ACTION.equals(action)) {
stopAlarm();
System.out.println("Alarm Dismissed");
}
}
}
My print lines in notificationButtonAction do not print, not even the "notificationButtonAction Started."
I followed the tutorial from Brevity Software (http://www.brevitysoftware.com/blog/how-to-get-heads-up-notifications-in-android/), but their code didn't seem to work.
Any help is appreciated! Thanks!
Turns out, I didn't add the class to the manifest. My code was fine.

Android - create notifications

I have question about notifications. I want to build an app with one buttons called (add notification) when I press add notification a notification is created Then, if I press the notification it takes me back to the activity.
I managed to create a notification but when i press on it, it makes nothing. What do I have to add so the notification sends me back to the activity?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
NotificationManager nmanger;
static int id=1;
public void buclick(View view) {
NotificationCompat.Builder nbuild= (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setContentTitle("Danger")
.setContentText("the raining is comming soon")
.setSmallIcon(R.drawable.amule);
nmanger =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
nmanger.notify(id,nbuild.build());
id++;
}
Create PendingIntent, then set it to builder:
Intent intent = new Intent(this, YourActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder nbuild = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setContentTitle("Danger")
.setContentText("the raining is comming soon")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.amule);
Try this code
Intent intent = new Intent(this, NameOfClassYouWantToOpen.class);
// Create pending intent and wrap our intent
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
try {
// Perform the operation associated with our pendingIntent
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
http://codetheory.in/android-pending-intents/
What is an Android PendingIntent?

strange notifications behaviour

I have a simple application (custom calendar). Every time a user creates event a new AlarmManager with custom broadcast receiver is created to call a notification 5 minuts before the event start. When that time come and user click on the notification a simple activity just shows the events info.
What is the problem: When i run app and create the event for the first time, everything works fine. When user click notification the correct one is displayed. But, when I create the second event, the problem occurs. When the notification for second notification is displayed, it looks fine (the correct information is shown in notification bar), but when i click it the first created event is shown. The same with third, fourth ...
how alarm manager is created, this is located in the activity that create event...
if (hasAlarm) {
Bundle bundle = new Bundle();
bundle.putString("name", eventName);
bundle.putLong("time", dateStart);
bundle.putString("desc", eventDescription);
bundle.putString("location", eventLocation);
bundle.putLong("end", dateEnd);
bundle.putString("username", username);
bundle.putString("password", password);
bundle.putString("mailServer", mailServer);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
alarmIntent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, dateStart
- (1000 * 60 * 5), pendingIntent);
}
and custom broadcast receiver ...
public class AlarmReceiver extends BroadcastReceiver {
private static int id = 0;
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String desc = bundle.getString("desc");
long time = bundle.getLong("time");
String name = bundle.getString("name");
for (String key : bundle.keySet()) {
Log.d("Bundle ALARM REVEIVER", key + " = \"" + bundle.get(key)
+ "\"");
}
long[] vibrate = { 0, 100, 200, 300 };
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.stat_notify_chat)
.setContentTitle("Upcoming event: " + name)
.setContentText(desc).setWhen(time).setVibrate(vibrate)
.setSound(alarmSound);
Intent viewEvent = new Intent(context, ViewEvent.class);
viewEvent.putExtras(intent.getExtras());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
viewEvent, 0);
builder.setContentIntent(contentIntent);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id++, builder.build());
}
}
I found where the problem was ...as we can see in the documentation, we need to add PendingIntent.FLAG_UPDATE_CURRENT for broadcast receiver as well, so the full implementation looks like
Intent viewEvent = new Intent(context, ViewEvent.class);
viewEvent.putExtras(intent.getExtras());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
viewEvent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);

How to check if Activity start from notification

I have problem my MainActivity can be created by 3 ways:
1) standart launch App
2) from Service
3) from notification click.
How I can check when it starts from notification click?
Notification code:
private void createNotification()
{
Log.d("service createNotification",MainActivity.TAG);
Context context = getApplicationContext();
Intent notificationIntent = new Intent(this,MainActivity.class);
intent.putExtra(AppNames.IS_NOTIFICATION_INTENT,true);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(this.getString(R.string.notification_title))
.setContentText(this.getString(R.string.notification_text))
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher);
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(AppNames.APP_NOTIFICATION, builder.getNotification());
}
add
intent.putExtra("started_from","notification");
to the code that starts the intent from the notifications, and the same thing to the other startActivity calls just change the value, then inside your activity
String startedFrom = getIntent().getStringExtra("started_from");
for more refer to this question: How do I get extra data from intent on Android?

Categories

Resources