unable to open second notification - android

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

Related

Android notification may open twice (or even more) the app

My app sets a notification with the following code:
private void defineAndLaunchNotification(String apppack,String title, String ContentText)
{
Context context = getApplicationContext();
PackageManager pm = context.getPackageManager();
Intent LaunchIntent = null;
String name=null;
try {
if (pm != null)
{
ApplicationInfo app = context.getPackageManager().getApplicationInfo(apppack, 0);
name = (String) pm.getApplicationLabel(app);
LaunchIntent = pm.getLaunchIntentForPackage(apppack);
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Intent intent = LaunchIntent;
if (ContentText.equals("filesystemfullnotification"))
{
intent.putExtra("start", "fullsystem");
}
else
{
intent.putExtra("start","incorrecttime");
}
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
NotificationCompat.Builder builder=null;
NotificationChannel notificationChannel=null;
int NOTIFICATION_ID = 12345;
if (Build.VERSION.SDK_INT<26) {
builder =
new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.drawable.notification_icon)
.setAutoCancel(true)
.setContentTitle("title
)
.setContentText("Content Text");
}
else
{
int importance=NotificationManager.IMPORTANCE_HIGH;
notificationChannel=new NotificationChannel("mychannel", "channel", importance);
builder =
new NotificationCompat.Builder(getBaseContext(),"mychannel")
.setSmallIcon(R.drawable.notification_icon)
.setAutoCancel(true)
//.setStyle(new NotificationCompat.BigTextStyle().bigText(StaticMethods.giveStringAccordingtoLanguage(title,language)))
.setContentTitle(StaticMethods.giveStringAccordingtoLanguage(title, language))
.setContentText(StaticMethods.giveStringAccordingtoLanguage(ContentText, language));
}
builder.addAction(R.drawable.notification_icon, "OK", pIntent);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
builder.setVibrate(new long[]{0, 1000, 1000, 1000, 1000});
builder.setContentIntent(pIntent);
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT>=26) {
nManager.createNotificationChannel(notificationChannel);
}
nManager.notify( (int) ((new Date().getTime() +Math.round(Math.random()*5000) / 1000L) % Integer.MAX_VALUE), builder.build());
}
That code sucessfully shows a notification whenever is called, but problem is that if the notification is tapped twice (or more) times it will open as many instances of my application as that number of times.
This happens even though I have defined in my AndroidManifest.xml my application tag with android:launchMode="singleInstance".
What could I do so the notificacion just reacts to the first tap or only one instance of the app appears?
The way you have build the intent you passed into your pending intent could be the problem. Consider building your intent this way:
Intent intent = new Intent(context.getApplicationContext(), <Activity to launch>.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("start", "fullsystem");
By your code you're actually calling to launch the whole application that is why its creating several instances of the application.
You are supposed to launch a particular part of your application, an entry activity to your application.

android firebase notification not navigate to the exact page

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.

GCM start background operations (make post to server) on notification click

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

Android Notifications, loads only the latest intent when there are more than one notifications

I have an app which has 4 layers/stack, something like,
HomePage >> DetailPage >> MapPage >> ChatPage
I managed to create notifications whenever I received different chat messages (note that each conversation has its unique id, say ChatId)
for different conversation, I will create a notification using ChatId as the requestCode in the pendingIntent
The problem I am facing is that, whenever I received more than 1 notification, say ChatId1 comes first, followed by ChatId2. Then when I clicked on the ChatId1's notification, it will launch the latest intent which is ChatId2, making the conversations loaded in ChatPage are conversations of ChatId2.
Question is, how can I make it so that, when I clicked on ChatId1's notification, it loads messages of ChatId1, and when click on ChatId2, it loads messages of ChatId2.
Below is the snippet of the code where I create my notifications
public void createLocalNotification(String meetingIdLong, String countryCode, String phoneNumber, String contactName, String chatMessage) {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, ChatLog.class);
long L = Long.parseLong(meetingIdLong);
int a = Integer.parseInt(meetingIdLong);
intent.putExtra("meetingId", L);
Intent intent1 = new Intent(this, HomePage.class);
Intent intent2= new Intent(this, MeetingDetailPage.class);
intent2.putExtra("meetingId", L);
Intent intent3 = new Intent(this, MapPage.class);
intent3.putExtra("meetingId", L);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ChatLog.class);
stackBuilder.addNextIntent(intent1);
stackBuilder.addNextIntent(intent2);
stackBuilder.addNextIntent(intent3);
stackBuilder.addNextIntent(intent);
PendingIntent pIntent = stackBuilder.getPendingIntent(a, PendingIntent.FLAG_UPDATE_CURRENT);
String notificationSound = _defPrefs.getString("pref_notification_tone", "");
NotificationCompat.Builder noti = new NotificationCompat.Builder(this)
.setContentTitle(contactName)
.setContentText(chatMessage)
.setSmallIcon(R.drawable.noti_smallicon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.noti_smallicon))
.setSound(Uri.parse(notificationSound))
.setDefaults(Notification.DEFAULT_VIBRATE)
.setNumber(++numberMsg)
.setAutoCancel(true)
.setContentIntent(pIntent);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
String[] events = new String[6];
events [numberMsg - 1] = new String(chatMessage);
// Sets a title for the Inbox style big view
inboxStyle.setBigContentTitle(contactName);
inboxStyle.setSummaryText(numberMsg + " new message(s)");
for (int i=0; i < events.length; i++) {
inboxStyle.addLine(events[i]);
}
noti.setStyle(inboxStyle);
String isChatOpen, isChatOpenId;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
isChatOpen = preferences.getString("isChatOpen","");
isChatOpenId = preferences.getString("isChatOpenId","0");
if (!isChatOpenId.equals(meetingIdLong))
{
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(a, noti.build());
}
}
Use
intent.setAction(Long.toString(System.currentTimeMillis()));
for each your Intent you want to be unique. Its just a dummy action, but it helps.

Opening Browser on push notification

I am trying to open the browser with a url when the user click on the push notification, i search in stackoverflow and i find this
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
but it doesnt work for me, when i put that the notification doesnt appear, i debugged it and it only throw the class file editor no error or anything.
this is the code
public void mostrarNotificacion(Context context, String body,String title, String icon, String url,String superior)
{
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notManager = (NotificationManager) context.getSystemService(ns);
int icono = R.drawable.mydrawable;
CharSequence textoEstado = superior;
long hora = System.currentTimeMillis();
Notification notif = new Notification(icono, textoEstado, hora);
Context contexto = context.getApplicationContext();
CharSequence titulo = title;
CharSequence descripcion = body;
PendingIntent contIntent;
if(url.equalsIgnoreCase("NULL"))
{
Intent notIntent = new Intent(contexto,MainActivity.class);
contIntent = PendingIntent.getActivity(
contexto, 0, notIntent, 0);
}
else
{
// Intent i = new Intent(Intent.ACTION_VIEW);
//i.setData(Uri.parse(url));
// contIntent = PendingIntent.getActivity(contexto, 0, i, 0);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
// notif.setLatestEventInfo(contexto, titulo, descripcion, contIntent);
//AutoCancel:
notif.flags |= Notification.FLAG_AUTO_CANCEL;
//send notif
notManager.notify(1, notif);
}
What you need to do is set a pending intent -
which will be invoked when the user clicks the notification.
(Above you just started an activity...)
Here's a sample code :
private void createNotification(String text, String link){
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle(text);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// pending implicit intent to view url
Intent resultIntent = new Intent(Intent.ACTION_VIEW);
resultIntent.setData(Uri.parse(link));
PendingIntent pending = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pending);
// using the same tag and Id causes the new notification to replace an existing one
mNotificationManager.notify(String.valueOf(System.currentTimeMillis()), PUSH, notificationBuilder.build());
}
Edit 1 :
I changed the answer to use PendingIntent.FLAG_UPDATE_CURRENT for the sample purpose. Thanks Aviv Ben Shabat for the comment.
Edit 2 :
Following Alex Zezekalo's comment, note that opening the notification from the lock screen, assuming chrome is used, will fail as explained in the open issue : https://code.google.com/p/chromium/issues/detail?id=455126 -
Chrome will ignore the intent, and you should be able to find in your logcat -
E/cr_document.CLActivity﹕ Ignoring intent: Intent { act=android.intent.action.VIEW dat=http://google.com/... flg=0x1000c000 cmp=com.android.chrome/com.google.android.apps.chrome.Main (has extras) }

Categories

Resources