How to open a specific activity based on Notification - android

I am currently working on a reminders app in which the user gets a notification with the name of the reminder and is then redirected to an activity which contains the text of the reminder in detail.
I am however, only able to redirect to the same activity each time.
I am using this code :
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, title, text, contentIntent);
So this redirects to the MainActivity on clicking the notification. I would like to redirect to a separate screen and then based on a key value display a text on that activity.
How do I achieve this ?
Thanks

Just change the PendingIntent using another Activity and/or append extra information on the Intent you are using to create the PendingIntent:
Intent launchIntent = new Intent(this, AnotherActivity.class)
launchIntent.putExtra("myKey", "myValue");
//....
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, launchIntent , 0);
notification.setLatestEventInfo(this, title, text, contentIntent);
And than, in you Activity's onCreate():
//...
getIntent().getStringExtra("myKey")
//do your stuff..

Just pass the value in the intent . eg.
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
contentIntent.putExtra("phone", value);
contentIntent.putExtra("name", value);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, contentIntent,
PendingIntent.FLAG_CANCEL_CURRENT);

Question has already been anwered and accepted, but here's another method:
int mId = 1;
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, TwoActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this)
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title")
.setContentText("Content")
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setNumber(1);
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(mId, builder.build());

Related

shutting the app by removing notification

#RequiresApi(api = Build.VERSION_CODES.M)
public void showNotification(int playPauseBtn) {
Intent intent = new Intent(this, ExoActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE);
Intent prevIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PREVIOUS);
PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this, 0, prevIntent,
PendingIntent.FLAG_MUTABLE);
Intent playIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PLAY);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(this, 0, playIntent,
PendingIntent.FLAG_MUTABLE);
Intent nextIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_NEXT);
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, nextIntent,
PendingIntent.FLAG_MUTABLE);
Bitmap picture = BitmapFactory.decodeResource(getResources(), HelperClass.getlist().get(position).getImg());
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_2)
.setSmallIcon(HelperClass.getlist().get(position).getImg()) //get thumbnail will have small icon pic
.setLargeIcon(picture)
.setContentTitle(HelperClass.getlist().get(position).getName())
.addAction(R.drawable.ic_baseline_skip_previous_24, "Previous", prevPendingIntent)
.addAction(R.drawable.ic_baseline_play_arrow_24, "Play", playPendingIntent)
.addAction(R.drawable.ic_baseline_skip_next_24, "Next", nextPendingIntent)
//.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
//.setMediaSession(mediaSession.getSessionToken()))
.setPriority(Notification.PRIORITY_HIGH)
.setC`your text`ontentIntent(contentIntent)
.setOnlyAlertOnce(true).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
This code creates Notification wherever this 'showNotification()' function is called but what if I want to shut the app by removing the notification?
use setDeleteIntent method - when notification is removed you can send some broadcast to all your "contextual" ojects (e.g. Activity, Service)
note that there is also setOngoing method, which will stick your notification and user won't be able to remove it "manually". then you can provide "kill" action button for this notification, which may behave exacly same as one created for setDeleteIntent. in that case don't forget to remove notification when user just leave/exit your app, when "kill" action pressed or in any other "usual" way

Send data to activity when clicked on notification?

i am opening a activity when notification is clicked . notification is activated from a service class .i want to send data to new activity opened from notification i am using intent1.putExtra("lable",lable); but in new activity it is giving me nullpointer exeption.
intent1 = new Intent(this.getApplicationContext(), simplestop.class);
intent1.putExtra("lable",lable);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification mNotify = new Notification.Builder(this)
.setContentTitle("title" + "!")
.setContentText("Click me!")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
I use this code for send data to activity.
Intent intent = new Intent(this, MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("from", "notification");
pIntent = PendingIntent.getActivity(this, 3, intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
May be you have problem in setting flag=0 or try to change request code=0 to any other integer.
Sending data.
Intent intent = new Intent(getApplicationContext(), simplestop.class);
intent.putExtra("lable", lable);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
final RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.yourLayoutOfNotification);
contentView.setOnClickPendingIntent(R.id.IdOfTheItemYouClick, contentIntent);
Try to retrieve data something like this in your simplestop.class
if (getIntent().getDataString() == null) {
String lable = Objects.requireNonNull(getIntent().getExtras()).getString("lable");
}
And I think you need to call the onNewIntent at the simplestop.class
And there to retrieve data.
And try to create a Log if the data are retrieved.
Log.d("Data", lable);
And tell what is the Log showing.

Intent returns WRONG data

I have this function to create a notification:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(title)
.setSound(alarmSound)
.setContentText(subtitle);
if(haveIntent) {
Intent intent = new Intent(context, PSBeaconMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("idToPass", beaconSettingID);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
mBuilder.setContentIntent(pIntent);
}
int mNotificationId = 001;
NotificationManager mNotifyMgr =
(NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
I send for now a hardcoded value for the beaconSettingID such as this:
https://scontent-amt2-1.xx.fbcdn.net/v/t35.0-12/28822214_1907084479363661_711965391_o.png?oh=b4c247836bcbd572d27f53738d2bdf6c&oe=5AA0C75E
This is my getIntent.getBundle:
if (bundle != null && bundle.containsKey("idToPass")) {
beaconUUID = bundle.getString("idToPass");
}
But I get back this:
https://scontent-amt2-1.xx.fbcdn.net/v/t35.0-12/28768405_1907084916030284_1955200830_o.png?oh=bcccf27352c90b248e82e08d902b8c15&oe=5AA1BA02
I don't understand? beaconID was the name of the "extra" key before. Since then I deleted the app, and changed it to idToPass. But I still get the old key, and more than that, a wrong value for it. Why is this happening?
Deleting an app doesn't mean that you deleted the previous notification.
Try to change
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
to:
PendingIntent pIntent = PendingIntent.getActivity(context, SOME_UNIQUE_ID, intent, 0);
In order to create new
Or to:
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
To update previous notification
Hope it helps

android - How to show a dialog when click on notification

I get notification in my application through BroadcastReceiver, The question is , How can I parse data to an activity and make a dialog with the received data ?
this is my code but when I click on the notification , nothing happens :
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(link));
PendingIntent pending = PendingIntent.getActivity(ctx, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification myNotification = new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(false).setLargeIcon(remote_picture)
.setContentTitle(onvan).setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg).setContentIntent(pending).build();
notificationManager.notify(1, myNotification);
I've some variablese like link , msg, onvan that contains my data and I need to send these variables to an activity and make a dialog .
How can I do so ?
Try this:
Intent notifyIntent = new Intent(context,YourActivityClassHere.class);
notifyIntent.setFlag(Intent.FLAG_ACTIVITY_NEW_TASK);
//UNIQUE_ID if you expect more than one notification to appear
PendingIntent intent = PendingIntent.getActivity(SimpleNotification.this, UNIQUE_ID,
notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
just make the PendingIntent open up one of your Activities and have your Activity be complete transparent and just open a Dialog.
EDIT: IF you want to open an Activity from notification click event:
Assuming that notif is your Notification object:
Intent notificationIntent = new Intent(this.getApplicationContext(), ActivityToStart.class);
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, notificationIntent, 0);
notif.contentIntent = contentIntent;
For more detail visit here. Android - Prompt Dialog window when touch on Notification
You can send data from your notification to another Activity using method putExtra and put this
PendingIntent pending = PendingIntent.getActivity(ctx, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT));
inplace of this
PendingIntent pending = PendingIntent.getActivity(ctx, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);`

Notification passes old Intent Extras

i am creating a notification inside a BroadcastReceiver via this code:
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
int icon = R.drawable.ic_stat_notification;
CharSequence tickerText = "New Notification";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_VIBRATE;
long[] vibrate = {0,100,200,200,200,200};
notification.vibrate = vibrate;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
CharSequence contentTitle = "Title";
CharSequence contentText = "Text";
Intent notificationIntent = new Intent(context, NotificationActivity.class);
notificationIntent.putExtra(Global.INTENT_EXTRA_FOO_ID, foo_id);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
int mynotification_id = 1;
mNotificationManager.notify(mynotification_id, notification);
When I click on the notification, it opens the NotificationActivity and inside the Activity i can retrieve the foo_id from the Intent-Bundle (e.g. 1)
However if another notification is triggered and i click on it again, the activity still receives the "old" value (1) from the Intent-Bundle. I've tried to clear the bundle with clear(), but am receiving the same effect. I think sth is wrong with my code..
You are sending the same request code for your pending intens.
Change this:
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
To:
PendingIntent contentIntent = PendingIntent.getActivity(context, UNIQUE_INT_PER_CALL, notificationIntent, 0);
intents are not created if you send the same params. They are reused.
Alternatively, you can use the following code to generate your PendingIntent:
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
From the doc for PendingIntent.FLAG_UPDATE_CURRENT:
If the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent. This can be used if you are creating intents where only the extras change, and don't care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it.
You are passing the same ID. In this kind of situation, make a unique id from time like this:
int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
And put it as this:
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),iUniqueId, intentForNotification, 0);
For anyone looking for the best approach after a long time all, you need to pass the PendingIntent.FLAG_UPDATE_CURRENT as the last argument as shown below
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
you don't even need to provide a new unique id.
You need to do this for next time onwards not for the first time
Your request code is 0 for all the notification. Change following line:
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
With:
PendingIntent contentIntent = PendingIntent.getActivity(context, new Random().nextInt(), notificationIntent, 0);
Just wanted to add another option
PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);

Categories

Resources