Intent does not work in Android notification - android

I try to make notification, but click on notification does not work as expected: in activity I could not retrive additional info send in notification:
int requestID = (int) System.currentTimeMillis();
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, LoadPictureActivity.class);
intent.putExtra("Test", "sometext");
PendingIntent pIntent = PendingIntent.getActivity(this, requestID, intent, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.common_signin_btn_icon_focus_light)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg)
.setContentIntent(pIntent)
.setAutoCancel(true);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
In LoadPictureActivity`s onCreate method I try to catch additional info:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = getIntent();
Log.d("App", "Intent get intent: " + intent);
if (intent != null) {
Log.d("App", "Intent extra sting: " + intent.getStringExtra("Test"));
}
}
But after click on notification I do not see any output with additional string, I also try to put the same check in OnResume, but in this case after click on notification I see that fires the intent that original start main class with nullable extra string. So I'm not sure if notification click works correctly in total. Where is the problem?

Try this way
PendingIntent pIntent = PendingIntent.getActivity(this, requestID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Related

Passing Data from Android Notifications

I have built a notification and am displaying it properly, but I can't figure out how to pass data to the activity. I pulled one string from the intent to display as the title of the notification, but I need to pull a 2nd string, and have the NotificationHandlerActivity process it.
//inside intentservice
private void sendNotification(Bundle extras) {
Intent intent=new Intent(this, NotificationHandlerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("link", extras.getString("link"));
mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
long[] vibrate = {100L, 75L, 50L};
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.abc_ic_menu_copy_mtrl_am_alpha)
.setContentTitle(extras.getString("title"))
.setOngoing(false)
.setAutoCancel(true)
.setVibrate(vibrate);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
//Inside NotificationHandlerActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
}
You should use the extras on your Intent. Because your intent is currently anonymous, you cannot do so. Extras are basic key-value stores. See below:
public static final String KEY_SECOND_STRING = "keySecondString";
...
...
String secondString = "secondString";
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, NotificationHandlerActivity.class);
intent.putExtra(KEY_SECOND_STRING, secondString);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
...
then, from your NotificationHandlerActivity, you can access that secondString from the intent.
#Override
public void onCreate(Bundle sIS){
super.onCreate();
String secondString = getIntent().getStringExtra("keySecondString");
...
}
use it like this :
Intent intent=new Intent(this, NotificationHandlerActivity.class);
intent.putExtra("key", "value");
mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
long[] vibrate = {100L, 75L, 50L};
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.abc_ic_menu_copy_mtrl_am_alpha)
.setContentTitle(extras.getString("title"))
.setOngoing(false)
.setAutoCancel(true)
.setVibrate(vibrate);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Apparently using 0 as the requestCode when calling getActivity() on the PendingIntent isn't the way to go. I updated it to just use System.currentTimeMillis() and that seemed to work. I'm assuming that the first time I built the notification, using 0 as the requestCode, the extra wasn't present.

Notification auto cancel not working for Android lollipop

I want to auto cancel my notification when user clicks on notification. The following code works good in all the devices except Android lollipop device. In Lollipop device, notification goes only when user swipes it off.
#SuppressWarnings("deprecation")
public void sendNotification(int id){
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Test")
.setContentText("Jump to next screen")
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, NextActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
resultIntent, 0);
//PendingIntent.FLAG_UPDATE_CURRENT
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// id, if there is a need to update the notification later on.
mNotificationManager.notify(id, mBuilder.build());
Log.v(TAG, "Notification ID value " + id);
//mNotificationManager.cancel(id);
}
What is missing in this code?
Looks good to me. My auto cancel still works on 5.0.2. Let me give you a portion of my code:
public static void notif(int id, String title, String text, Context context, Class activity) {
// get an instance of the NotificationManager service
if (mNotifyMgr == null)
mNotifyMgr = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context, activity);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent notifIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.launcher)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(notifIntent);
mNotifyMgr.notify(id, mBuilder.build());
}
modify following:
setAutoCancel(true) -> setAutoCancel(false);
then on action activity do the following
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
if you want to set special condition you can set by
intent.putExtra("key", "value")

Multiple notification in android for same app not working?

I have implemented push notifications for my android app .I am able to show multiple notification in notification bar but only one notification work at a time.If I click on any notification it will start the intended activity and that particular notification will disappear from notification bar but other notification for same app will become dead.Nothing happens when I click on rest of the notification.My code for handling notification is following:
private void sendNotification(String msg, String msgId, int notificationId,
int type) {
// SharedPreferences prefs = getSharedPreferences(
// Utility.PREFS_NAME, MODE_PRIVATE);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = null;
Bundle bundle = new Bundle();
if (type == 1) {
intent = new Intent(this, Activity_Received.class);
// bundle.putString("greeting", msg);
bundle.putString(Utility.KEY_MESSAGE_DELIVERY_ID, msgId);
} else if (type == 2) {
intent = new Intent(this, Activity_Birth.class);
} else {
return;
}
bundle.putBoolean(Utility.KEY_IS_NOTIFICATION, true);
intent.putExtras(bundle);
PendingIntent contentIntent;
// The stack builder object will contain an artificial back stack
// for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out
// of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
if (type == 1) {
stackBuilder.addParentStack(Activity_Received.class);
} else {
stackBuilder.addParentStack(Activity_Birth.class);
}
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("WishnGreet")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(notificationId, mBuilder.build());
}
Please advise what do I need to change in above code so that I can click on every notification that I receive for my application and start the intended activity.
Pass a different notificationId for each different notification you want to have in the method: sendNotification(String msg, String msgId, int notificationId, int type)
I have wrote the following method which is working in case of multiple notifications.
private void pushNotification(String msg, String msgId, int notificationId,
int type) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Bundle bundle = new Bundle();
bundle.putString(Utility.KEY_MESSAGE_DELIVERY_ID, msgId);
bundle.putBoolean(Utility.KEY_IS_NOTIFICATION, true);
Intent intent = new Intent(this, Activity_ReceivedGreeting.class);
intent.putExtras(bundle);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(), notificationId, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("WishnGreet")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(notificationId, mBuilder.build());
}
The key was to remove the FLAGS on pending intent.

How to ask Yes/No in notification and then launch the app and run corresponding method? Source code and screenshot attached

I have prepared a simple test app which posts a notification on a button click:
The source code from MainActivity.java creating the notification is displayed below:
Button showButton = (Button) findViewById(R.id.show);
showButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent appIntent = new Intent(mContext, MainActivity.class);
appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
appIntent.putExtra("my_data", 12345);
String question = getString(R.string.the_question);
PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, appIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(mContext)
.setContentTitle(question)
.setContentText(question)
.setTicker(question)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
mManager.notify(NOTIFY_ID, notification);
}
});
My question is: how to modify the notification, so that the user is asked a Yes/No question (in this case: "Do you want to open the car?") and - after she selects Yes or No to launch the same app and run a corresponding method in it (in this case: openCar() or closeCar() method).
I probably should use NotificationCompat.Action.Builder - but how exactly?
Also I am not really sure if this code is the correct code for launching an app from notification and what flags should I use:
Intent appIntent = new Intent(mContext, MainActivity.class);
appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
And finally I wonder if hardcodidng some random number in NOTIFY_ID is the correct way when posting notifications?
Here is a source code I used for notification with Login/Register action.
private void sendNotification(String message, String title) {
try {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Intent secondActivityIntent = new Intent(this, SecondActivity.class);
PendingIntent secondActivityPendingIntent = PendingIntent.getActivity(this, 0 , secondActivityIntent, PendingIntent.FLAG_ONE_SHOT);
Intent thirdActivityIntent = new Intent(this, ThridActivity.class);
PendingIntent thirdActivityPendingIntent = PendingIntent.getActivity(this, 0 , thirdActivityIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_3d_rotation_white_36dp)
.setContentTitle(title)
.setContentText(message)
.addAction(R.drawable.ic_lock_open_cyan_600_24dp,"Login",secondActivityPendingIntent)
.addAction(R.drawable.ic_lock_pink_700_24dp,"Register",thirdActivityPendingIntent)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
To use it: simply call this method sendNotification(String yourMessage, String yourTitle)
e.g. sendNotification("Hello Message", "Hello Title")
Here is a snapshot of the output
Notify user on pending Intent.. an example is here..
public void notifyUser() {
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(HappyActivity.this, NotificationDialog.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
// use the flag FLAG_UPDATE_CURRENT to override any notification already
// there
pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification(R.drawable.ic_launcher,
"Question.....?????", System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
notification.setLatestEventInfo(this, "title",
"Explanation of question..", pendingIntent);
// 10 is a random number I chose to act as the id for this notification
notificationManager.notify(10, notification);
}

Multiple notification from GCM not directing to correct activity

I am using GCM for push notifications. My constraint is that from the received bundle from GCM server I have to redirect user to specific location in my application. Every thing is working fine when I have only one notification. If there are two notification in the notification tray then the user is redirected to the activity based on the latest bundle. All other bundle are ignored. I have followed many SO post like this and this but it didnot solve my problem. Here are excerpts from my code:
private void sendNotification(String msg, String type, String id) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("notification_type", type);
intent.putExtra("notification_id", id);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, 0);//I have tried all flags of pending intent like PendingIntent.FLAG_UPDATE_CURRENT and other 3
// flag_update_current
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("RWD Rugby").setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
Random rnd = new Random();
NOTIFICATION_ID = rnd.nextInt(90000);
Log.d("notification number", NOTIFICATION_ID + "");
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
On the receiving end I use :
Intent intent = getIntent();//this gives me extras from the intent that started the activity not pending intent
String fromNotification = intent.getStringExtra("notification_type");
I might have to compromise on the result that I might get. For me the best case scenario is that user is redirected to the correct page based on the property i set on creating the intent. Any help is much appreciated and if I am not specific enough please ask.
You can try the below code..
(try using FLAG_UPDATE_CURRENT)
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent myintent = new Intent(this, ReceiveActivity.class);
myintent.putExtra("message", msg);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
myintent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
// .setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

Categories

Resources