I've searched for about hour to find some solution how to send extras to activity when user clicks in notification box but everything I've found didn't work for me.
I need to pass event ID to activity where I show user info about this event.
I've used setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), setAction("Action"), PendingIntent.FLAG_UPDATE_CURRENT and combination of all of these solution but neither didn't work.
That's my code:
Notification.Builder notiBuilder = new Notification.Builder(context);
notiBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo));
notiBuilder.setSmallIcon(R.drawable.logo);
notiBuilder.setContentTitle(context.getString(R.string.eventNitificationTitle));
notiBuilder.setContentText(obj.getString("nazwa") + " " + obj.getString("data"));
Intent eventIntenet = new Intent(context, EventActivity.class);
eventIntenet.setAction("Action_"+id);
eventIntenet.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
eventIntenet.putExtra("eventID", id);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, eventIntenet, PendingIntent.FLAG_UPDATE_CURRENT);
eventIntenet = null;
notiBuilder.setContentIntent(pIntent);
pIntent = null;
NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notiManager.notify(Integer.parseInt(id), notiBuilder.build());
} else {
notiManager.notify(Integer.parseInt(id), notiBuilder.getNotification());
}
And way to get my Int:
this.eventID = getIntent().getIntExtra("eventID", -1);
Everytime when I click in notification, I'm moving to activity but getExtra returns -1.
You can try something along these lines:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ChatService.this).setSmallIcon(R.drawable.app_icon)
.setContentTitle(senderName)
.setContentText("Notification Text Here");
mBuilder.setAutoCancel(true);
Intent resultIntent = new Intent(MyService.this, TargetActivity.class);
resultIntent.putExtra("eventID", id);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(MyService.this);
stackBuilder.addParentStack(TargetActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, mBuilder.build());
If your app is already running and your EventActivity is already on the top of the stack, this code:
this.eventID = getIntent().getIntExtra("eventID", -1);
will always use the Intent that EventActivity was started with the first time.
You should override onNewIntent() and get the "extra" from the Intent that is passed as an argument to that method.
Related
So I would like to create a notification that, when clicked, will open my MainActivity and do something according to the extras I've put in the intent.
Right now, the notification works perfectly, but once I click it, nothing happens. I've search a little bit and have done some modification to my code :
I have added android:launchMode="singleTop" to my activity in the manifest.
I have put the code to execute in my MainActivity in the onNewIntent method :
#Override
protected void onNewIntent(Intent intent){
System.out.println("Entering onNewIntent!!!!!!!");
if(getIntent().getExtras() != null) {
url = getIntent().getExtras().getString("url");
System.out.println("URL in Main Activity : " + url);
if (url != null && url != "") {
saveFile(url);
dezipFile();
}
}
}
But nothing changed, I've put some System.out to see if it even reach the beginning of the onNewIntent... But nothing is shown on the console.
Here is the code where I create the notification :
private void createNotification () {
Intent downloadIntent = new Intent(getApplicationContext(), MainActivity.class);
downloadIntent.putExtra("url", url);
downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent downloadPendingIntent = PendingIntent.getService(getApplicationContext(), 0, downloadIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "Notif")
.setSmallIcon(R.drawable.icon_notif)
.setContentTitle(getApplicationContext().getString(R.string.notif_title))
.setContentText(getApplicationContext().getString(R.string.notif_content))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(downloadPendingIntent)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notification_download", "Dowload BD infos", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
builder.setChannelId("notification_download");
}
NotificationManagerCompat notification = NotificationManagerCompat.from(getApplicationContext());
notification.notify(1, builder.build());
}
If anybody knows what I did wrong, it will be really appreciated!
Add this:
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "Notif")
.setSmallIcon(R.drawable.icon_notif)
.setContentTitle(getApplicationContext().getString(R.string.notif_title))
.setContentText(getApplicationContext().getString(R.string.notif_content))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(downloadPendingIntent)
.setAutoCancel(true);
Intent mIntent = new Intent(context, YourActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(mIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
You can set the activity launched when user clicks on a notification as follows:
Intent resultIntent = new Intent(this, targetActivityClass);
Intent backIntent = new Intent(this, backActivityClass);
Intent[] intentArray = new Intent[]{backIntent, resultIntent};
PendingIntent resultPendingIntent = PendingIntent.getActivities(this, 0, intentArray,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
builder.setContentIntent(resultPendingIntent);
This code also sets the activity launched when user clicks the back button after clicking the notification.
Nothing happens on clicking Accept or Reject button of the head-ups notification.
But when the head-up notification disappear and from clicking Accept and Reject from the notification panel is working.
Testing on Android 5.1.0.
Intent acceptIntent = new Intent(this, NotificationReceiver.class);
acceptIntent.setAction("com.android.test.Accept");
PendingIntent acceptPendingIntent = PendingIntent.getBroadcast(TestApplication.getAppContext(), 12345, acceptIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Intent rejectIntent = new Intent(this, NotificationReceiver.class);
rejectIntent.setAction("com.android.test.Reject");
PendingIntent rejectPendingIntent = PendingIntent.getBroadcast(TestApplication.getAppContext(), 12345, rejectIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.fundu);
builder.setContentTitle("Test Notification");
builder.setContentText("Hello");
builder.setAutoCancel(true);
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
builder.setCategory(NotificationCompat.CATEGORY_SERVICE);
builder.setDefaults(NotificationCompat.DEFAULT_ALL);
builder.setPriority(NotificationCompat.PRIORITY_MAX);
builder.addAction(R.drawable.ic_check_icon, "Accept", acceptPendingIntent);
builder.addAction(R.drawable.ic_action_close, "Reject", rejectPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
Just setting the vibration, makes it working fine.
builder.setVibrate(new long[0]);
The key is to call setContentIntent on the Notification Builder and passing it a PendingIntent. The Full code with comments explaining each step is included below. See the part named "THIS IS THE PERTINENT PART" (The Full code is included for completeness sake.)
// Use Notification Builder to start things off
// There are other ways of acquiring a Notification Builder; this is just an example
String channelId = "channelId";
String title = "title";
String body = "body";
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channelId);
notificationBuilder
.setSmallIcon(R.drawable.ic_alarm)
.setContentTitle(title)
.setContentText(body);
//--------------- THIS IS THE PERTINENT PART ---------------
// Prepare Intent for creating PendingIntent
Intent intent = new Intent(context, ActivityToStart.class);
// Create Pending Intent
int requestCode= 1234; // requestCode has to be a unique ID for EACH PendingIntent
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(
requestCode,
PendingIntent.FLAG_UPDATE_CURRENT // use to prevent re-using current Activity Intent
);
notificationBuilder.setContentIntent(pendingIntent);
// Finally, create the Notification
Notification notification = notificationBuilder.build();
I create notification with action button. When clicking on action button, broadcast receiver is called. I am passing the notification ID in the intent
In the broadcast receiver I do the following
int notifId = intent.getIntExtra(Constants.NOTIF_ID, 0);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(notifId);
This is how I generate the notification
int notifId = Util.random.nextInt(9000);
Intent mIntent = new Intent(con, NotificationBroadcastReceiver.class);
mIntent.putExtra(Constants.NOTIF_CODE, codeReason);
mIntent.putExtra(Constants.NOTIF_ID, notifId);
PendingIntent mPendingIntent = PendingIntent.getBroadcast(con, 0, mIntent , 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(con)
.setSmallIcon(R.drawable.icon)
.setContentTitle("test")
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true)
.addAction(R.drawable.ic_launcher, "action", mPendingIntent);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(con, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
con, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) con.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.setDefaults(
Notification.DEFAULT_SOUND |
Notification.DEFAULT_VIBRATE |
Notification.DEFAULT_LIGHTS
);
// mId allows you to update the notification later on.
mNotificationManager.notify(notifId, mBuilder.build());
However the notification does not get hidden/dismissed although I know I am hitting the code ( using log statements).
Why is that?
I found the answer. I "think" that due to the 2 pending intents having the same con and req code, they are ending up modifying their intent values. I fixed it by using 2 different request codes to ensure unique Pending Intents . Therefore , I got the same notifId
Check your id if it's zero.
Check the notification is not binded with other Service by startForeground().
I'm trying to putExtra to Activity which will be launched after clicking on notification, but instead of value that I set I'm getting default value. This is my code in AlarmReceiver:
Intent notifActiv = new Intent(context, NotificationActivity.class);
notifActiv.putExtra("ID", id);
PendingIntent pI = PendingIntent.getActivity(context, 0, notifActiv, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(string).setTicker("You got meeting today!")
.setContentText("Click here for more details");
mBuilder.setContentIntent(pI);
mBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE);
mBuilder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, mBuilder.build());
And this is my NotificationActivity where I'm trying to get Extras:
Intent intent = getIntent();
int id = intent.getIntExtra("ID", 0);
Could you please tell my where I'm doing something wrong?
Currrently I am working on Notification in andorid.
Here code is notification arrive....
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setTicker("New Task Here!!!");
if(taskdata.get(0).getDescription().equals(""))
{
int stringId = context.getApplicationInfo().labelRes;
String appname = context.getString(stringId);
mBuilder.setContentTitle(appname);
}
else
{
mBuilder.setContentTitle(taskdata.get(0).getDescription());
}
long l = Long.parseLong(taskdata.get(0).getDateTime());
Date date =new Date(l);
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a ");
String alarmtime = formatter.format(date);
String dateString= DateFormat.format("dd/MM/yyyy",date).toString();
mBuilder.setContentText(alarmtime+","+dateString);
Intent resultIntent = new Intent(context, TaskDetail.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
Bundle bundledata = new Bundle();
bundledata.putString("ImagePath", taskdata.get(0).getImagePath());
bundledata.putString("Des", taskdata.get(0).getDescription());
bundledata.putString("DateTime", FlagValue);
resultIntent.putExtras(bundledata);
stackBuilder.addParentStack(TaskDetail.class);
//ringtone on
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(context, notification);
r.play();
/* Increase notification number every time a new notification arrives */
mBuilder.setNumber(++numMessages);
mBuilder.setAutoCancel(true);
// Adds the Intent that starts the Ac tivity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
// here this activity will refresh when fire the receive
Intent activityintent = new Intent(context,MainActivity.class);
PendingIntent contentintent = PendingIntent.getActivity(context, 0, activityintent, PendingIntent.FLAG_UPDATE_CURRENT);
activityintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activityintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());
}
My issue is :
When Nofification come that time MyActivity.class Activity will be refresh.
I am also refer this link Android Refresh Activity from Notification but in my application not wok.
If you have Any Idea Please Help me.
Thank you in Advance.
Add the following function in the end of the notification function .
onCreate(null)