Pending Intent Not Working, Notification Does Not Open Activity - android

Hello I have the following function that displays notifications in my app, however I suddenly started having an issue where when I click a notification it does not take me to the activity I specified in .setContentIntent(), this is my code:
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void getNotifications() {
ArrayList<com.xxxxxx.app234929.models.Notification> notifications = mNotificationsTable.get();
int requestId = (int) System.currentTimeMillis();
Intent notificationsIntent = new Intent(getApplicationContext(), NotificationsActivity.class);
notificationsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), requestId,
notificationsIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle(new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_stat_mtgh_notification)
.setColor(getResources().getColor(R.color.colorPrimary))
.setContentTitle("xxxxxx")
.setContentText("You have "+(notifications.size() > 1 ? "new updates" :"a new update"))
.setNumber(notifications.size())
.setContentIntent(intent)
.setDefaults(Notification.DEFAULT_VIBRATE |
Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS))
.setBigContentTitle("xxxxxx");
for (int i=0; i < notifications.size(); i++) {
inbox.addLine(notifications.get(i).getMessage());
};
Notification notification = inbox.build();
NotificationManager notificationManager = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);
}
I've googled a lot of solutions and tried them but none of them worked for me so now I do not know what I am doing wrong here.

This is the code i use and works perfectly, i have it on a service but you can use in any activity:
Intent myIntent = new Intent(MyActivity.this, ActivityIWantToOpenOnClick.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MyActivity.this, 0, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncomp = new NotificationCompat.Builder(MyActivity.this);
ncomp.setContentTitle("Message Tittle");
ncomp.setContentText("Message Text");
ncomp.setTicker("Message Ticker");
ncomp.setSmallIcon(R.drawable.your_icon);
ncomp.setAutoCancel(true);
ncomp.setContentIntent(pendingIntent);
nManager.notify((int) System.currentTimeMillis(), ncomp.build());

Related

Handle successive fcm push notification

i have set up my own push notification server to send notification to android devices.
I have handled the notification so on click it always open my custom activity whatever the app was in background or foreground.
The working part : When sending two separated notifications that means when the first notification is received i click on it so the activity is launched that's ok.
I re-send another notification so also when i click on it all goes well and the activity is relauched.Perfect!
The NOT working part : When sending two successive notifications the problem occurs.
When two notifications are received ..i open the first one the activity is launched but when i click on the second one nothing happens !!.
So i think it might be a solution in changing the Intent FLAG or Pending Intent.
I have searched for solutions but all were about handling the notification when app is in foreground or background which is not in my case.
This is my working code:
Intent i = new Intent(this, News_description.class);
i.putExtra("title", title);
i.putExtra("message", message);
i.putExtra("image", image);
i.putExtra("time", time);
i.putExtra("date", date);
i.putExtra("click_action", click_action);
i.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i,PendingIntent.FLAG_ONE_SHOT
);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setVibrate(new long[]{status, status})
.setContentTitle(getString(R.string.app_name))
.setContentText(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(title))
.setSmallIcon(R.mipmap.ahed_me)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int id = (int) System.currentTimeMillis();
manager.notify(id, builder.build());
} catch (Exception e) {
e.printStackTrace();
}
I can provide any further information.
I have the Flag FLAG_ACTIVITY_CLEAR_TASK and it works on my app.
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Here my full code, it works perfect for me:
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent =
PendingIntent.getActivity(getApplicationContext(), 0,
i, 0);
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.alarm)
.setAutoCancel(true)
.setContentTitle(title)
.setPriority(Notification.PRIORITY_MAX)
.setVibrate(vibrate)
.setLights(Color.BLUE, 3000, 1500)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(body))
.setContentIntent(contentIntent)
.setContentText(body);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int Unique_Integer_Numbe = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
mNotificationManager.notify(Unique_Integer_Numbe, mBuilder.build());
UPDATED:
public SomePushNotificationClass {
private static int NOTIFICATION_ID = 1;
String previousMessageID = "null";
#Override
public void onReceive(Bundle data) {
String messageID = data.getString("message_id");
if (!messageID.equals(previousMessageID) && !messageID.isEmpty()) {
previousMessageID = messageID;
NotificationManager notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent it = new Intent(this, SomeActivity.class);
it.putExtra("key_example_1", someValue);
it.putExtra("key_example_2", someValue2);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.some_drawable);
notificationBuilder.setLargeIcon(someIcon);
notificationBuilder.setContentTitle(someTitle);
notificationBuilder.setStyle(new
// Optional
NotificationCompat.BigTextStyle().bigText(someText));
notificationBuilder.setContentText(someText);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
notificationManager.notify(NOTIFICATION_ID,
notificationBuilder.build());
NOTIFICATION_ID++;
}
}
}
This is what you need:
Intent it = new Intent(this, SomeActivity.class);
it.putExtra("key_example_1", someValue);
it.putExtra("key_example_2", someValue2);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP);

Status bar notification auto starts activity

I am trying to do scheduled notification. All works except: When application is active and minimized. Notification auto starts activity without waiting for user to click on it.
On reveive:
public void onReceive(Context context, Intent paramIntent) {
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
Notification notification = new Notification(R.drawable.logo_f, context.getResources().getString(R.string.notification_text), System.currentTimeMillis());
Intent notificationIntent = new Intent(context, TimeLeftActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, context.getResources().getString(R.string.notification_text), "", intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound=alarmSound;
// Fire the notification
notificationManager.notify(1, notification);
}
My notification start method:
private void createScheduledNotification(int sec)
{
// Get new calendar object and set the date to now
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// Add defined amount of days to the date
calendar.add(Calendar.SECOND, sec);
// Retrieve alarm manager from the system
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getBaseContext().ALARM_SERVICE);
// Every scheduled intent needs a different ID, else it is just executed once
int id = 1;
// Prepare the intent which should be launched at the date
Intent intent = new Intent(this, TimeAlarm.class);
// Prepare the pending intent
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
// Register the alert in the system. You have the option to define if the device has to wake up on the alert or not
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
EDIT after Kirill answer. Error still persist. Notification auto starts pending intent and does not wait for click.
#Override
public void onReceive(Context context, Intent paramIntent) {
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
Intent notificationIntent = new Intent(context, TimeLeftActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle(context.getResources().getString(R.string.notification_text))
.setContentIntent(intent)
.setSound(alarmSound)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Fire the notification
notificationManager.notify(1, notification);
}
It is hard to find error, because you use deprecated API in your code, you should to use Notication.Builder
Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build();
If you need to support old versions you can use NotificationCompat
UPDATE
This is sample from my app, it throws a notification, which open activity by click, I marked method to add intent.
String message = context.getString(R.string.notif_message);
Intent notificationIntent = new Intent(AddBpRecordActivity.ADD_ACTION);
NotificationCompat.Builder nb = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notif_logo)
.setContentTitle(message)
.setContentText(billet.comment)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
>>> .setContentIntent(PendingIntent.getActivity(context, (int) billet.id, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT))
.setWhen(System.currentTimeMillis());
Notification notification = nb.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) billet.id, notification);

Notification auto cancel not working for Android lollipop

I want to auto cancel my notification when user clicks on notification. The following code works good in all the devices except Android lollipop device. In Lollipop device, notification goes only when user swipes it off.
#SuppressWarnings("deprecation")
public void sendNotification(int id){
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Test")
.setContentText("Jump to next screen")
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, NextActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
resultIntent, 0);
//PendingIntent.FLAG_UPDATE_CURRENT
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// id, if there is a need to update the notification later on.
mNotificationManager.notify(id, mBuilder.build());
Log.v(TAG, "Notification ID value " + id);
//mNotificationManager.cancel(id);
}
What is missing in this code?
Looks good to me. My auto cancel still works on 5.0.2. Let me give you a portion of my code:
public static void notif(int id, String title, String text, Context context, Class activity) {
// get an instance of the NotificationManager service
if (mNotifyMgr == null)
mNotifyMgr = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context, activity);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent notifIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.launcher)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(notifIntent);
mNotifyMgr.notify(id, mBuilder.build());
}
modify following:
setAutoCancel(true) -> setAutoCancel(false);
then on action activity do the following
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
if you want to set special condition you can set by
intent.putExtra("key", "value")

android status bar notyfication icon

I'm trying to set an icon to the status bar, I can not view it as soon as you click on the button.
The problem there is the option to delete. I want to set up so you will not be deleted as long as those entering the application and delete
public void setNotificationToStatusBar(){
Intent intent= new Intent(this, PrefActivitySmsForwarder.class);
PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0,intent, 0);
String forwarder_start_str= getResources().getString(R.string.sms_forwarding_activated);
String app_name=getResources().getString(R.string.app_name);
Notification n= new Notification(R.drawable.ic_launcher,forwarder_start_str, System.currentTimeMillis());
n.setLatestEventInfo(getApplicationContext(), app_name, forwarder_start_str, pi);
n.defaults= Notification.DEFAULT_ALL;
nm.notify(uniqueId, n);
finish();
}
String forwarder_start_str= getResources().getString(R.string.sms_forwarding_activated);
String app_name=getResources().getString(R.string.app_name);
Intent intent= new Intent(this, PrefActivitySmsForwarder.class);
Notification n= new Notification(R.drawable.ic_launcher,forwarder_start_str, System.currentTimeMillis());
/** I ADD THIS **/ n.flags=Notification.FLAG_ONGOING_EVENT;
PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0,intent,0);
n.setLatestEventInfo(getApplicationContext(), app_name, forwarder_start_str, pi);
n.defaults= Notification.DEFAULT_ALL;
nm.notify(uniqueId, n);
finish();
This is how I create a notification. Using setOngoing(true) I make it persistent
http://developer.android.com/reference/android/app/Notification.Builder.html#setOngoing(boolean)
Intent intent = new Intent("MY_INTENT");
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),0,intent,PendingIntent.FLAG_ONE_SHOT);
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("Title")
.setContentText("Click here")
.setSmallIcon(R.drawable.img2)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.img1))
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
If you want to keep your own way of creating the notification and not use the Notification.Builder, you could add this line of code to edit the flag field of the notification
notification.flags |= Notification.FLAG_ONGOING_EVENT;
you can do like this too
int icon = R.drawable.icon_notification;
String msg= "hey";
Intent notificationIntent = new Intent(context,Activity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(icon)
.setContentTitle(context.getString(R.string.app_name))
.setContentIntent(intent)
.setPriority(PRIORITY_LOW)
.setContentText(msg)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_SOUND |
Notification.DEFAULT_VIBRATE |
Notification.DEFAULT_LIGHTS);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notificationId, mBuilder.build());

Android Notification Remote View Error

I have a notification that is shown. It works perfectly on my GS3 running Vanilla JB. When I try to run it on a Android 3.1 Emulator it crashes with the following exception. It is not a Custom Notification
12-28 00:26:05.239: E/AndroidRuntime(417): android.app.RemoteServiceException: Bad notification posted from package XX: Couldn't expand RemoteViews for: StatusBarNotification(package=XX id=0 tag=null notification=Notification(contentView=XX/0x1090087 vibrate=[500,500],sound=content://settings/system/notification_sound,defaults=0x0,flags=0x11) priority=0)
Here is my code:
public static void generateNotification(Context context, String message) {
// Show the notification
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Drawable largeIcon = context.getResources().getDrawable(R.drawable.ic_launcher);
Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle("XX");
builder.setContentText(message);
builder.setSmallIcon(R.drawable.ic_stat_push).setLargeIcon(drawableToBitmap(largeIcon));
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
builder.setLights(Color.RED, 1000, 1000);
builder.setTicker("XX: " + message);
builder.setVibrate(new long[] { 500, 500});
Intent intent = new Intent(context, MainActivity.class);
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("message", message);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(pendingIntent);
Notification notification = builder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
notificationManager.notify(0, notification);
}

Categories

Resources