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

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.

Related

Firebase data notification cannot click

Hi I want to send image on notification and use data notification
this is my data and
notification comes with picture. but the notification is not clicked
How can i send clikable ?
""data"" : {""click_action"":"".MainActivity"",
""body"" : ""new Symulti update 22!"",
""title"" : ""new"",
""url"":""https://www.blablaaas.com"",
""img_url"":""https://www.image.com/image1""
""}}
I hope you are implementing code for android, so to make notification clickable you just need to add the pendingIntent with destination Activity name so that you will get the clickable action. Use the below code for reference.
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
Intent mainIntent = new Intent(this, TabHostScreen.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent mainPIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.setSmallIcon(getNotificationIcon(builder));
builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
builder.setAutoCancel(true);
//start intent on notification tap (MainActivity)
builder.setContentIntent(mainPIntent);
//custom style
builder.setStyle(new NotificationCompat.DecoratedCustomViewStyle());
builder.setCustomContentView(remoteCollapsedViews);
//builder.setCustomBigContentView(remoteExpandedViews);
long[] pattern = {500, 500, 500};
builder.setVibrate(pattern);
Random rand = new Random();
NOTIFICATION_ID = rand.nextInt(1000);
//notification manager
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(NOTIFICATION_ID, builder.build());

unable to open second notification

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

How to open Play Store via a FCM notification?

I would like to send a notification to my users to remember them to update the app, but I can't change the app code as obviously the problem is that the app is outdated.
Is there a way to open Play Store via a FCM notification, using clickAction or something like that, without needing to make changes to the app?
you can open play store-specific app using FCM you just need to put following logic in your onMessageReceived of your FCM custom class.
Bellow is the Logic:
public static void openStore(Context context,RemoteMessage remoteMessage) {
Intent intent;
if (remoteMessage.getData().containsKey("appPackageName")) {
final String appPackageName = remoteMessage.getData().get("appPackageName"); // getPackageName()
try {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName));
} catch (android.content.ActivityNotFoundException anfe) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName));
}
int notificaionId = 1;
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.BigTextStyle bigTextNotiStyle = null;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int color = ContextCompat.getColor(this, R.color.profileFontColor);
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle("" + remoteMessage.getData().get("title"))
.setContentText("" + remoteMessage.getData().get("desc"))
.setStyle(bigTextNotiStyle)
.setAutoCancel(true)
.setColor(color)
.setContentIntent(pIntent)
.setLights(Color.RED, 3000, 3000);
notificationManager.notify(notificaionId, mBuilder.build());
}
}

Android ignoring my notification sound when a specific icon is chosen

When the iconIndex of my notification = 0, it looks for the name in the array on position 0, and returns "ic_alert", which is the name of the icon. But only when this icon is chosen, it doesn't want to play the notification sound, even though isPlaySound() returns true, so weird... Other icons work fine
public class AlarmReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("ALARMRECEIVER","ONRECEIVE");
//Create a notification
long notificationId = intent.getLongExtra("id", -1);
if(notificationId == -1)
{
Log.e("AlarmReceiver","id went missing");
}
else
{
NotificationRepository repository = NotificationRepository.getInstance(context);
Notification notification = repository.getNotification(notificationId);
if(notification != null)
{
String[] icons = context.getResources().getStringArray(R.array.icons);
int iconId = context.getResources().getIdentifier(context.getPackageName()
+ ":drawable/" + icons[notification.getIconIndex()], null, null);
String icon = icons[notification.getIconIndex()];
//create the android notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(iconId)
.setContentTitle(notification.getTitle())
.setContentText(notification.getSubtitle())
.setColor(ContextCompat.getColor(context, R.color.colorPrimary));
if(notification.isPlaySound())
{
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Log.e("ALARMRECEIVER", "SOUND");
}
else Log.e("ALARMRECEIVER","NO SOUND");
if (notification.isVibrate())
{
mBuilder.setVibrate(new long[]{1000, 1000});
}
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify((int) notificationId, mBuilder.build());
//Delete the notification from the database
repository.removeNotification(notificationId);
Intent i = new Intent("dvanack.gmail.com.NOTIFY");
context.sendBroadcast(i);
Log.w("ONRECEIVE","ENDED");
}
I don't have this problem with other devices than the One Plus one running Cyanogenmod, this was fixed the day after with an update ...

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