How to schedule notification in android after application exit? - android

I am working on an application in which a notification has to fired after some time. The code for firing a notification is in a method. I want to execute this method after some time the application has been exited. I tried Alarm Manager, it runs fine but it needs an intent. I don't want to show an activity , I just want to show notification in status bar. Is there any other way to do this? The method I want to run is fireNotification. Using Alarm Manager seems logical but It can fire an Intent not a method. I need some way to run this method when application is not running.
private void fireNotification(long Id, String Title)
{
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(Title)
.setContentText("Tap here to view")
.setSound(soundUri)
.setAutoCancel(true);
Intent resultIntent = new Intent(this, ViewActivity.class);
resultIntent.putExtra("noteId", noteId);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(ViewNoteActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = safeLongToInt(safeLongToInt(Id));
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
public static int safeLongToInt(long l) {
if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
throw new IllegalArgumentException
(l + " cannot be cast to int without changing its value : Notification ID.");
}
return (int) l;
}

Related

Android notification in background continue previous intent

sendNotification('Hello', 0, 1);
private void sendNotification(String message, int id, int notification_num) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, Main.class);
intent.setData(new Uri.Builder().scheme("data").build());
intent.putExtra("id", id);
intent.putExtra("noti_number", notification_num);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(Main.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent = PendingIntent.getActivity(this, id, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("App Title")
.setContentText(message)
.setSmallIcon(R.drawable.notif)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setNumber(notification_num);
nm.notify(id, notificationBuilder.build());
}
When application is opened intent.putExtra works fine, but when I close app (kill proccess), notification is coming but not with it extra than with new intent extra.
Problem is also with multiple notification, when app is closed, there are no grouping like I want it to be.
notificationBuilder.setNumber is always 0 in background.
Need help how to run app always in background or how to continue previous intent.
I have done it using GcmIntentService & GcmBroadcastReceiver, for more info click on this link.

Multiple notification in android for same app not working?

I have implemented push notifications for my android app .I am able to show multiple notification in notification bar but only one notification work at a time.If I click on any notification it will start the intended activity and that particular notification will disappear from notification bar but other notification for same app will become dead.Nothing happens when I click on rest of the notification.My code for handling notification is following:
private void sendNotification(String msg, String msgId, int notificationId,
int type) {
// SharedPreferences prefs = getSharedPreferences(
// Utility.PREFS_NAME, MODE_PRIVATE);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = null;
Bundle bundle = new Bundle();
if (type == 1) {
intent = new Intent(this, Activity_Received.class);
// bundle.putString("greeting", msg);
bundle.putString(Utility.KEY_MESSAGE_DELIVERY_ID, msgId);
} else if (type == 2) {
intent = new Intent(this, Activity_Birth.class);
} else {
return;
}
bundle.putBoolean(Utility.KEY_IS_NOTIFICATION, true);
intent.putExtras(bundle);
PendingIntent contentIntent;
// The stack builder object will contain an artificial back stack
// for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out
// of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
if (type == 1) {
stackBuilder.addParentStack(Activity_Received.class);
} else {
stackBuilder.addParentStack(Activity_Birth.class);
}
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("WishnGreet")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(notificationId, mBuilder.build());
}
Please advise what do I need to change in above code so that I can click on every notification that I receive for my application and start the intended activity.
Pass a different notificationId for each different notification you want to have in the method: sendNotification(String msg, String msgId, int notificationId, int type)
I have wrote the following method which is working in case of multiple notifications.
private void pushNotification(String msg, String msgId, int notificationId,
int type) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Bundle bundle = new Bundle();
bundle.putString(Utility.KEY_MESSAGE_DELIVERY_ID, msgId);
bundle.putBoolean(Utility.KEY_IS_NOTIFICATION, true);
Intent intent = new Intent(this, Activity_ReceivedGreeting.class);
intent.putExtras(bundle);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(), notificationId, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("WishnGreet")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(notificationId, mBuilder.build());
}
The key was to remove the FLAGS on pending intent.

android notifications won't run .notify

I'm trying to send an android notification but it keeps failing at the mbuilder.build() part. I do have an alert dialog right after in the same method. I'm posting my code below
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.noteiconcon)
.setContentTitle("Finished search")
.setContentText("We found your account");
System.out.println("failed after setText");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
System.out.println("failed after result intent");
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
System.out.println("taskstackbuilder passed");
stackBuilder.addParentStack(MainActivity.class);
System.out.println("stackbuilder.appParentstack passed");
stackbuilder.addNextIntent(resultIntent);
System.out.println("stackbuilder.addnextintent passed");
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
System.out.println("pending intent passed");
mBuilder.setContentIntent(resultPendingIntent);
System.out.println("mbuilder.setcontentintent passed");
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
System.out.println("notification manager passed");
// mId allows you to update the notification later on.
mNotificationManager.notify(mId,mBuilder.build());
System.out.println("notificationManager.notify passed"+ mId);
I already added the meta data task but the log cat says.
Bogus static initialization, type 4 in field type Landroid/support/v4/app/NotificationCompat$NotificationCompatImpl; for Landroid/support/v4/app/NotificationCompat; at index 1
Like I said I added the meta data tag and this is being called in an asychtask after an alert dialog. Ive commented out the alert dialog but it still works.
If I drop the last line .notify it doesn't crash but obviously doesn't send a notification.
I had to use a different notification method which it accepted the notification then.
// Set the icon, scrolling text and timestamp
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String MyText = "Finished searching";
Notification mNotification = new Notification(R.drawable.passicon, MyText, System.currentTimeMillis() );
//The three parameters are: 1. an icon, 2. a title, 3. time when the notification appears
String MyNotificationTitle = "Finished Searching";
String MyNotificationText = "We can't find your password.";
Intent MyIntent = new Intent(this, MainActivity.class);
PendingIntent StartIntent = PendingIntent.getActivity(getApplicationContext(),0,MyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//A PendingIntent will be fired when the notification is clicked. The FLAG_CANCEL_CURRENT flag cancels the pendingintent
mNotification.setLatestEventInfo(getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent);
int NOTIFICATION_ID = 1;
notificationManager.notify(NOTIFICATION_ID , mNotification);
//We are passing the notification to the NotificationManager with a unique id.

What alternate methods we can use for notification in android?

I have a problem. What I want to do is, I just want to display a message in notification bar at frequent time of interval. For that I used two notification methods they are:
Notification notification = new Notification(icon, message, when);
......
notification.setLatestEventInfo(context, title, subTitle, intent);
Currently I am using API level 19. So I came to know above ones are deprecated. I was suggested to use Notification.builder. But after using that I am not getting proper output. Can anyone show me the code how to use Notification.Builder for above 2 statements...
Any help will be appreciated.
you can use this...
public static void createNotification(Context context, Long data) {
Random rnd = new Random();
int i = rnd.nextInt();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.app_icon)
.setContentTitle("Logo").setContentText("text");
mBuilder.setAutoCancel(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, activity.class);
resultIntent.putExtra(StringUtils.SESSIONID, data);
// The stack builder object will contain an artificial back stack for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(activity.class);
// stackBuilder.editIntentAt(index);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(i, mBuilder.build());
Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setSubText(subTitle)
.setContentIntent(pendingIntent)
.build();
This is example is from here: Notification.Builder
To set the time you could use the method setWhen(long timestamp);

How to make notification uncancellable/unremovable

I want to make my Android notification stay even if user clicks it or clicks clear all...
Right now it stays sometimes, and gets removed sometimes, and I'm not sure what causes it.
Here's my code for the notification:
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void createNotification()
{
NotificationManager notificationManager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle("Wolftech Field Agent")
.setContentText("Getting Status")
.setSmallIcon(R.drawable.ic_launcher)
.setOngoing(true)
.setAutoCancel(false);
Intent intent = new Intent(context, FieldAgent.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(FieldAgent.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
public static void updateNotificationText(String inString)
{
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentText(inString)
.setContentTitle("Wolftech Field Agent")
.setSmallIcon(R.drawable.ic_launcher)
.setOngoing(true)
.setAutoCancel(false);
Intent intent = new Intent(context, FieldAgent.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(FieldAgent.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
public static void cancelNotification()
{
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
I think you are looking for ongoing notifications, in that case if you are using NotificationCompat.Builder , you can use :
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this);
mNotifyBuilder.setOngoing(true);
I believe that you are looking for this flag:
Notification.FLAG_NO_CLEAR
Add that flag to your notification.
you try
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
notificationManager.cancel(pendingIntent);
Okey, I've realized the code I posted is actually good.
What is happening is that when I'm clicking the notification, it's calling onCreate() again, and then after a random interval it's calling onDestroy().
In onDestroy() I had my cancelNotification() method, so if onDestroy() got called after onCreate(), it removed my notification.
Which brings me to a new question: Why is it destroying and recreating my activity after I've followed every answer I could find on here on how to stop that from happening?
You can find that question here How to make notification resume and not recreate activity? if you want to help me solve it...
I had this issue too. My Solution is the add extra on the function that creates the intent
private void addNotification(String headLine, String info, Context context) {
mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon) //R.drawable.icon
.setContentTitle(headLine)
.setContentText(info)
.setOngoing(true)
.setAutoCancel(false);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class);
resultIntent.putExtra("FROM_NOTIF", true);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
// stackBuilder.addParentStack(MainActivity.class);
//Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
// mBuilder.setf |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
mNotificationManager.notify(mNotification_id, mBuilder.build());
}
and In MainActivity:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.getBooleanExtra("FROM_NOTIF", false)) {
addNotification(...)
... call the function that adds the notification again ..}
So thing is that the notification turns off after the user press on it, but than you can be notify on the activity that started using onNewIntent(), check the intent over there and if you find out that it came from the notification, set it again.

Categories

Resources