I have done the firebase notification. I can be able to get the multiple notification in the notification bar. When I pressed one notification icons from the notification bar then it's redirecting to the last received screen. then if I pressed the pending icons from the notification bar then nothing happen. this is my code
private void sendNotification(Map<String, String> data) {
Intent intent = null;
String messageBody = data.get("Message");
String referenceKey = data.get("ReferenceKey");
String referenceValueFromFCM = data.get("ReferenceValue");
if (LocalRepository.getInstance().isAuthenticated()) {
PromotionData promotionData = new PromotionData();
if (!TextUtils.isEmpty(referenceValue) && TextUtils.isDigitsOnly(referenceValue)) {
promotionData.promotionId = Integer.parseInt(referenceValue);
}
intent.putExtra("key", referenceKey);
intent.putExtra("data", promotionData);
intent.putExtra("value", referenceValue);
intent = new Intent(this, DashboardActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
long[] pattern = {250, 250, 250, 250, 250};
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(AppUtil.getNotificationId() /* ID of notification */, notificationBuilder.build());
This is my manifest
<activity
android:name=".views.dashboard.DashboardActivity"
android:screenOrientation="portrait"
android:exported="true"
android:theme="#style/AppTheme.NoActionBar"
android:windowSoftInputMode="stateAlwaysHidden" />
This is the dashboard navigation activity
String key = getIntent().getStringExtra("key");
String promotionID = getIntent().getStringExtra("value");
PromotionData promotionData = getIntent().getParcelableExtra("data");
if (!TextUtils.isEmpty(promotionID) && (!TextUtils.isEmpty(key))) {
Intent intent = null;
switch (key) {
case Repository.ModuleCode.WHATS_NEWS:
if (hasPromotionId) {
whatsNew();
intent = new Intent(this, WhatsNewDetailActivity.class);
intent.putExtra("data", promotionData);
intent.putExtra("pushID", pushID);
startActivity(intent);
}else{
whatsNew(); // this is fragment
}
break;
case Repository.ModuleCode.PROMOTION:
if (hasPromotionId) {
promotion();
intent = new Intent(this, PromotionDetailActivity.class);
intent.putExtra("data", promotionData);
intent.putExtra("pushID", pushID);
startActivity(intent);
}else{
promotion(); // this is fragment
}
break;
can you please advise me
Thanks in advance.
You can use this answer for understanding how to pass value on Activity using Notification. Here's a link which might be helpful
Only you have to pass values with the Intent like this,
Intent intent = new Intent(this, yourActivityClass.class);
intent.putExtra("msg",messageBody);
I have find out the answer for my question.
When I am passing the values with Intent, should use the
intent.setData
then its working for multiple notification.
This is my updated code for navigate the exact screen.
Intent intent = null;
String messageBody = data.get("Message");
String referenceKey = data.get("ReferenceKey");
String referenceValue = data.get("ReferenceValue");
String pushID = data.get("PushId");
PromotionData promotionData = new PromotionData();//item id
if (!TextUtils.isEmpty(referenceKey)) {
if (!TextUtils.isEmpty(referenceValue) && TextUtils.isDigitsOnly(referenceValue)) {
promotionData.promotionId = Integer.parseInt(referenceValue);
}
}
if (LocalRepository.getInstance().isAuthenticated()) {
intent = new Intent(this, DashboardActivity.class);
intent.setData(new Uri.Builder().scheme(referenceKey).build());
intent.putExtra("pushID", pushID);
intent.putExtra("data", promotionData);
intent.putExtra("key", referenceKey);
intent.putExtra("value", referenceValue);
} else {
intent = new Intent(this, LoginActivity.class);
intent.setData(new Uri.Builder().scheme(referenceKey).build());
intent.putExtra("pushID", pushID);
intent.putExtra("data", promotionData);
intent.putExtra("key", referenceKey);
intent.putExtra("value", referenceValue);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
long[] pattern = {250, 250, 250, 250, 250};
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(AppUtil.getNotificationId() /* ID of notification */, notificationBuilder.build());
}
Here should use this line for the exact page navigation. this is firebase bug.
intent.setData(new Uri.Builder().scheme(referenceKey).build());
We can pass whatever the String instead of referenceKey.
Related
I am trying to start an activity from a notification. Upon starting that activity, I add data via intent.putextra to the intent so the activity shows the right content for the situation.
The activity that is being started is supposed to be open only once in the stack. I did achieve this via
android:launchMode="singleTop"
in my manifest.
However - and now I come to my question - if this activity is already running, I want it to close and replace it with the instance I am creating with the specific additional data (put extra). How can I achieve this?
Heres the code of my notification:
public void newMessageNotification(String title, String message, String otherusernumber, String requestStatus, String sendername) {
notificationManager = NotificationManagerCompat.from(this);
Intent chatIntent = new Intent(this,ChatActivity.class);
//these three strings define the behaviour of the chat activtity
chatIntent.putExtra("otherUsername", sendername);
chatIntent.putExtra("otherUsernumber", otherusernumber);
chatIntent.putExtra("requestStatus", requestStatus);
chatIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), chatIntent,
PendingIntent.FLAG_UPDATE_CURRENT);;
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_new_message)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(1, notification);
}
Try below code
Add PendingIntent in notification
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Full create notification code
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager =
(NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);
Uri defaultSoundUri = RingtoneManager . getDefaultUri (RingtoneManager.TYPE_NOTIFICATION);
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The id of the channel.
String Ch_id = "yourappname_01";
// The user-visible name of the channel.
CharSequence name = "Notification";
// The user-visible description of the channel.
//String description = getString(R.string.channel_description);
int importance = NotificationManager . IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(Ch_id, name, importance);
mChannel.setSound(defaultSoundUri, new AudioAttributes . Builder ().build());
notificationManager.createNotificationChannel(mChannel);
// Create a notification and set the notification channel.
notification = new Notification . Builder (this, Ch_id)
.setSmallIcon(R.drawable.notify)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(remoteMessage.getData().get("title"))
.setAutoCancel(true)
.setContentIntent(pendingIntent) //Add PendingIntent
.setChannelId(Ch_id)
.build();
} else {
// Create a notification
notification = new Notification . Builder (this)
.setSmallIcon(R.drawable.notify)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(remoteMessage.getData().get("title"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent) //Add PendingIntent
.build();
}
//Generate Diff Notification
int m =(int)((new Date ().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(m, notification);
Update
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_ONE_SHOT);
I hope this can help you!
Thank You.
Try to add flag: Intent.FLAG_ACTIVITY_NEW_TASK to your Intent
Try Below
Intent intent = new Intent(this, ActivityDestination.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
//pendingIntent = PendingIntent.getActivity(this, 0,intent,PendingIntent.FLAG_ACTIVITY_NEW_TASK);
The following is the code that I use to handle notifications on my app. As you can see using the flag variable I receive different notifications which I handle differently. My problem is that I want to bundle my notifications but every time I receive a new notification the older notification is overridden i.e., I only get displayed with one notification at a time despite using setGroup() and setGroupSummary(). What could be the problem and how can I resolve it?
private int notificationId = 1;
private String GROUP_KEY_CHAT = "com.example.CHAT";
private static final String CHANNEL_ID = "com.example.gummy.pushnotification";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String title = data.get("title");
String body = data.get("body");
String flag = data.get("flag"); // notification flag to categorize type of notification
String receiverId = data.get("receiverId");
String receiverName = data.get("receiverName");
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = null;
assert flag != null;
switch (flag) {
case "2":
intent = new Intent(getApplicationContext(), ViewVisitors.class);
break;
case "4": // reliever 1 notification
intent = new Intent(getApplicationContext(), PendingRelieverRequests.class);
break;
case "5": // reliever 2 notification
intent = new Intent(getApplicationContext(), Reliever2PendingRequests.class);
break;
case "6": // reliever 3 notification
intent = new Intent(getApplicationContext(), Reliever3PendingRequests.class);
break;
case "7": // approval notification
intent = new Intent(getApplicationContext(), EmployeeMainActivity.class);
intent.setAction("LeaveHistory");
case "8":
intent = new Intent(getApplicationContext(), Chat.class);
intent.putExtra(Constants.DISPLAY_NAME, receiverName);
intent.putExtra(Constants.UID, receiverId);
default:
intent = new Intent(getApplicationContext(), LoginActivity.class);
break;
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification) // small icon
.setContentTitle(title) // title
.setStyle(new NotificationCompat.BigTextStyle().bigText(body)) // set body to be expandable
.setAutoCancel(true) // remove notification on tap
.setGroup(GROUP_KEY_CHAT)
.setGroupSummary(true)
.setPriority(NotificationCompat.PRIORITY_MAX) // priority
.setCategory(NotificationCompat.CATEGORY_MESSAGE) // system wide category
.setContentIntent(pendingIntent); // set tap action
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationBuilder.setSound(uri); // set to default notification sound
notificationManager.notify(notificationId++, notificationBuilder.build());
}
Thank you.
I wanted to open different articles in one activity using different post id's which i am sending via notification. and i am able to open one post on clicking on notification but with same activity open i m unable to open or process second notification.
public void onMessageReceived(RemoteMessage remoteMessage) {
sharedPref = new SharedPref(this);
if (sharedPref.getNotification()) {
// play vibration
if (sharedPref.getVibration()) {
((Vibrator) getSystemService( Context.VIBRATOR_SERVICE)).vibrate(VIBRATION_TIME);
}
RingtoneManager.getRingtone(this, Uri.parse(sharedPref.getRingtone())).play();
JSONObject json = null;
if (remoteMessage.getData().size() > 0) {
Map<String, String> data = remoteMessage.getData();
FcmNotif fcmNotif = new FcmNotif();
fcmNotif.setTitle(data.get("title"));
fcmNotif.setPosttitle( data.get("posttitle"));
fcmNotif.setPost_id(data.get("post_id"));
fcmNotif.setPost_slug( data.get( "post_slug" ) );
fcmNotif.setCat_name(data.get("cat_name"));
fcmNotif.setType(data.get("type"));
if(!data.get("cat_name").equals("No Notification"))
{
displayNotificationIntent(fcmNotif);
}
}
}
}
private void displayNotificationIntent(FcmNotif fcmNotif) {
Intent intent = new Intent(this, MainActivity.class);
if (fcmNotif.getPost_id() != "tnd") {
intent = new Intent(this, PostDetails.class);
intent.putExtra( "PostId",fcmNotif.getPost_id());
intent.putExtra( "type",fcmNotif.getType() );
intent.putExtra( "PostSlug",fcmNotif.getPost_slug() );
intent.putExtra("CategoryName",fcmNotif.getCat_name());
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(fcmNotif.getTitle());
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(fcmNotif.getPosttitle()));
builder.setContentText(Html.fromHtml(fcmNotif.getPosttitle()));
builder.setSmallIcon( R.mipmap.custom_icon);
builder.setDefaults( Notification.DEFAULT_LIGHTS);
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
builder.setPriority(Notification.PRIORITY_HIGH);
}
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int unique_id = (int) System.currentTimeMillis();
notificationManager.notify(unique_id, builder.build());
}
Note:
I have tried using intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK); and it opens all notifications easily but when pressing HOME button and reopening app from drawer its opens first notification post not last opened one.
and XML is simple `
android:name=".PostDetails"
android:label="#string/back"
android:parentActivityName=".AllCategoryList"
android:screenOrientation="portrait"/>
<activity`
Finally Got solution:
Intent backIntent = new Intent(this, HomeActivity.class);
backIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent notificationIntent = new Intent(this, NextActivity.class);
final PendingIntent pendingIntent = PendingIntent.getActivities(this, 1,
new Intent[] {backIntent, notificationIntent}, PendingIntent.FLAG_ONE_SHOT);
from ans from diffrent question of #Jitendra ramoliya
I have receive three different screens in my app:
Reading,
Walking, and
Sleeping
How do I identify the specific notification to redirect to in each screen?
To do so, you must specify a content intent defined with a PendingIntent object and pass it to setContentIntent().
The following snippet shows how to create a basic intent to open an activity when the user taps the notification:
// Create an explicit intent for an Activity in your app
Intent intent = new Intent(this, Reading.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
This is clearly mentioned in Android developer site
private final String CHANNEL_ID = "channel1";
private final String CHANNEL_NAME = "channel_one";
private NotificationManager notificationManager;
private NotificationManager getNotificationManager() {
if (notificationManager == null) {
notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
return notificationManager;
} else {
return notificationManager;
}
}
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra("type", "type");
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.enableVibration(true);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setShowBadge(true);
getNotificationManager().createNotificationChannel(channel);
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
builder.setColorized(true);
builder.setChannelId(CHANNEL_ID);
builder.setColor(ContextCompat.getColor(this,R.color.colorPrimaryDark));
builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
} else {
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
}
builder.setContentTitle("Title");
builder.setContentText("Message");
Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(notificationSound);
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_bottom_logo);
builder.setLargeIcon(/*BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)*/getBitmapFromDrawable(ContextCompat.getDrawable(getApplicationContext(), R.mipmap.ic_launcher)));
builder.setContentIntent(pendingIntent);
getNotificationManager().notify((int) SystemClock.uptimeMillis(), builder.build());
I'm using Google Play Services lib for GCM and all works great.
Now I implement 2 buttons (actions) in my notificationCompat.Builder:
- One open app.
- Other one delete some unread messages: for this operation I post some dato to server.
How can I launch a post to my server on notification action click without open any activity in front of user?
Thank you very much!!!!!
Here my code:`Intent openIntent = new Intent();
Intent cancelIntent = new Intent();
if (has1Id) {
//go details!
openIntent = new Intent(this, NotificationActivity.class);
openIntent.putExtra("id", ids.get(0));
//cancell intent: start async operation in background
cancelIntent = new Intent(this, HomeActivity.class);
cancelIntent.putExtra("id", ids.get(0));
}else{
//go home!
openIntent = new Intent(this, HomeActivity.class);
//cancell intent: start async operation in background
cancelIntent = new Intent(this, HomeActivity.class);
cancelIntent.putExtra("id", ids);
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
openIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent cancelNotificationIntent = PendingIntent.getActivity(this, 0,
cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long[] vibrationPattern = {0, 200, 800, 200, 100, 500};
Uri soundUri = Uri.parse("android.resource://"+ getPackageName() + "/" + R.raw.jingle1);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_notification)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setContentTitle(title) //set title
.setContentInfo(numNotRead) //number of unread content
.setAutoCancel(true)
.setContentText(msgs.get(0)+"...")
.setVibrate(vibrationPattern)
.setSound(soundUri)
.setLights(Color.rgb(255, 165, 00), 800, 800)
.setContentIntent(contentIntent).addAction(R.drawable.ic_notification, getString(R.string.open_app), contentIntent)
.setContentIntent(cancelNotificationIntent).addAction(android.R.drawable.ic_delete, getString(R.string.mark_read), cancelNotificationIntent);
if (has1Id) {
NotificationCompat.BigTextStyle bigTextStyle =new NotificationCompat.BigTextStyle().bigText(msgs.get(0));
mBuilder.setContentTitle(getString(R.string.notification_new_content));
//get only 1 long text: the description of content
mBuilder.setStyle(bigTextStyle);
}else{
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(getString(R.string.notification_new_contents));
for (int i=0; i < msgs.size(); i++) {
inboxStyle.addLine(msgs.get(i));
}
mBuilder.setStyle(inboxStyle);
}
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());`
You should use another class as the intent receiver for cancelIntent, like a BroadcastReceiver and handle the intent there with no UI.
public class MyIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context _context, Intent _intent) {
if (_intent.getAction().equals(MY_INTENT)) {
// TODO Handle a notification
}
}
}
You also can use a Activity with no UI as the intent, but I think previous option is better.
More info:
Android Activity with no GUI