Ongoing Notification Disappears When Clearing Memory - android

My problem is I want to cancel an ongoing notification only if cancel
option is selected in the app, but whenever I clear memory on "Task
Manager/RAM" tab of my android device my notification disappears.
What can I do to make my ongoing notification stay even if I clear memory?
I created an ongoing notification in a class that extends BroadcastReciever class.In my OnGoingNotificationReciever(extends BroadcastReciever):
Intent mainAct = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 555, mainAct, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(resID).setContentTitle(city).setContentText(temperature);
mBuilder.setContentIntent(contentIntent);
mBuilder.setOngoing(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
Then I set an AlarmManager to start this BroadcastReciever and repeat every 5 minutes:
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Intent i7 = new Intent(getApplicationContext(), OnGoingNotificationReciever.class);
PendingIntent ServiceManagementIntent = PendingIntent.getBroadcast(getApplicationContext(), 1111111, i7, 0);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,SystemClock.elapsedRealtime(), 5 * 60 * 1000, ServiceManagementIntent);
This works perfectly and does what I want to do(e.g when I close the app, notification stays on the status bar) except it disappears when clearing memory.
Note: In Yahoo Weather application it does what I want to do, but I couldn't find how on the Internet.

After a lot of search I finally found a solution to this problem.
In my Manifest.xml I wrote the following:
<receiver android:name=".OnGoingNotificationReciever" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_RESTARTED" />
<data android:scheme="package" android:path="com.example.havadurumumenu" />
</intent-filter>
</receiver>
PACKAGE_RESTARTED is called when you clear memory, and setting this restarts your receiver after clearing memory.

Related

Notification wtih AlarmManager in fragment

Have a trouble trying to get an alarm manager to work with a notification inside. This is to give the user of the app, a notification on a certain point.
My alarm is setup inside a fragment, with the code as following.
Intent notificationIntent = new Intent(getContext(), DeviceBootReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
int hour = Integer.parseInt(vars.getShowRapport().getFinishTime().split(":")[0]);
int min = Integer.parseInt(vars.getShowRapport().getFinishTime().split(":")[1]);
vars.getShowRapport().getFinishDate().setHours(hour);
vars.getShowRapport().getFinishDate().setMinutes(min);
long futureInMillis = System.currentTimeMillis()+1000*60;
//long futureInMillis = vars.getShowRapport().getFinishDate().getTime();
AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
getFragmentManager().beginTransaction().replace(R.id.makeRapportFragment,fragment).addToBackStack(null).commit();
In my manifest i have
<receiver android:process=":remote" android:name=".DeviceBootReceiver">/receiver>
And finally in my receiver called DeviceBootReceiver i have.
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ejservicebookincon)
.setContentTitle("Rapport finishing")
.setContentText("Rapport on item should be done.");
Intent notificationIntent = new Intent(context, ServiceRapportMain.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
Don't know where my problem is, and my receiver never seems to be activated, so can't check if that part work as of yet. Would like help if someone could point out, where my problem is. And just as a heads up i'm working in Android Studio.
As i wrote in the comment above, the error i had was that i used AlarmManager.ELAPSED_REALTIME_WAKEUP where then one i should have used here was AlarmManager.RTC_WAKEUP

android - Why this code does not make a notification in BroadcastReceiver

I want to make a notification from BroadcastReceiver. I'm using this code in my activity and it works fine but I can't make a notification from BroadcastReceiver . Could you help me to solve this problem :
Random rd;rd= new Random ();
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(link));
PendingIntent pending=null;
pending = PendingIntent.getActivity(ctx, 0, notificationIntent, pending.FLAG_UPDATE_CURRENT);
Notification myNotification = new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(false).setLargeIcon(remote_picture)
.setContentTitle(onvan).setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg).setContentIntent(pending).build();
notificationManager.notify(rd.nextInt(75), myNotification);
The problem is , this code does not make a notification and no notification is showing in the tray .as I say , I run this code in Activity and it works find but in BroadcastReceiver it does not make any notifications
To execute the code inside BroadcastReceiver you have to call sendBroadcast() method or set some action in your Manifest file like
<receiver android:name="Your package name.ReceiverName">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
//set your action here
</intent-filter>
</receiver>

How can I cancel unshown notifications in android

Hi I am new to notifications,
I wrote this code for notifications.
PendingIntent pendingIntent = PendingIntent.getActivity(context, leadidforstatus,
myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.noti)
.setContentTitle("LMS notification")
.setContentIntent(pendingIntent)
.setContentText(intent.getStringExtra("messagenotify"))
.setAutoCancel(true);
i = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(i, mBuilder.build());
In that I set one list of notifications. In that some displayed and some not displayed. But I want to cancel all un shown notifications.
I used mNotificationManager.cancleAll() but that is cancel only shown notifications.
thanks in advance.
I think the problem here is that The Notification is launched immediately after creating it and your not using the AlarmManager to schedule this Notification.
Solution Should be to schedule Alarms via an AlarmManager which will trigger the Notification Code above.
This requires 3 parts:
Register a BroadCastReceiver & Build a Notification when its triggered:
public class UtilityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// .. Here is where you really want to build the notification and notify
// This will be triggered by the AlarmManager from the Code below
PendingIntent pendingIntent = PendingIntent.getActivity(context, leadidforstatus, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.noti)
.setContentTitle("LMS notification")
.setContentIntent(pendingIntent)
.setContentText(intent.getStringExtra("messagenotify"))
.setAutoCancel(true);
i = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(i, mBuilder.build());
}
Schedule an Alarm with the AlarmManager to send a BroadCast which the Receiver above is listening for:
// Create an Intent to Launch
Intent notificationIntent = new Intent(context, UtilityReceiver.class);
// Use a Pending Intent to Launch the Alarm
PendingIntent notificationPendingIntent = PendingIntent.getBroadcast(context,
PendingIntent.FLAG_ONE_SHOT, notificationIntent, Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, timeForAlarmInMillis, notificationPendingIntent);
Then when you encounter the situation when you no longer want notifications to show for your app, you tell the AlarmManager to remove them from its queue of Alarms by Rebuilding the pending Intent and using AlarmManager to Cancel it.
// Create an Intent to Launch
Intent notificationIntent = new Intent(context, UtilityReceiver.class);
// Use a Pending Intent to Launch the Alarm
PendingIntent notificationPendingIntent = PendingIntent.getBroadcast(context,
PendingIntent.FLAG_ONE_SHOT, notificationIntent, Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// *********Important this will cancel all the Matching PendingIntents
alarmManager.cancel(notificationPendingIntent);
Good Luck, and be sure to register your Receiver in your Activity or Manifest.
NotificationManager maintains list of all notification mNotificationList and performs cancel or cancelAll operations on this list
I tried searching in Google source code of NotificationManager.java and NotificationManagerService.java in notify(),enqueueNotificationWithTag() and cancelAllNotification() But there is no implementation to cancel previously unshown notification
As per your comment, if your user is deleted and his notification arrives then user is already deleted so notification has no meaning
i = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(i, mBuilder.build());
// i should be Id for this notification, i think you want to pass
// time in mili second here
I think you are searching similar to this,
How to dismiss notification after action has been clicked
Just check the answer on that post. Use the id to cancel that particular Notification
I think the id part in your code is this,
i = (int) System.currentTimeMillis();

android notification only sound plays notification is not shown in notification drawer

i am trying to fire notification in at a particular time using AlarmManager and Notification manager. i am facing a strange problem. when notification is fired only sound plays but notification is not shown in the notification drawer.
i got an error in the log
04-26 11:32:09.217 1222-1222/? E/NotificationService﹕ WARNING: In a future release this will crash the app: com.example.shiv.selftweak
my code is .
The class which calls the AlarmManager
Intent intent1 = new Intent(this, FireNotification.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 1000, intent1, 0);
AlarmManager am = (AlarmManager)this.getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), pendingIntent);
FireNotification class
public class FireNotification extends Service {
#Override
public void onCreate() {
Intent intent = new Intent(this, MainActivity.class);
long[] pattern = {0, 300, 0};
PendingIntent pi = PendingIntent.getActivity(this, 1234, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Self tweak")
.setContentText("Habbits are waiting for last dones")
.setVibrate(pattern)
.setAutoCancel(false);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(false);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.notify(1234, mBuilder.build());
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Android Menifest
<service android:name=".FireNotification"></service>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
when notification fires only sound plays. but it is not getting shown in the notification drawer which shows no notification.
The problem is that you haven't specified mBuilder.setSmallIcon(R.drawable.ic_launcher).
Basically you have to set smallIcon, contentTitle and contentText. If you miss any of those the Notification will not be displayed at all! That's clearly specified HERE (also you can read more about notifications there as well).

How to dismiss notification after action has been clicked

Since API level 16 (Jelly Bean), there is the possibility to add actions to a notification with
builder.addAction(iconId, title, intent);
But when I add an action to a notification and the action is pressed, the notification is not going to be dismissed.
When the notification itself is being clicked, it can be dismissed with
notification.flags = Notification.FLAG_AUTO_CANCEL;
or
builder.setAutoCancel(true);
But obviously, this has nothing to with the actions associated to the notification.
Any hints? Or is this not part of the API yet? I did not find anything.
When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:
notify(int id, Notification notification)
To cancel, you would call:
cancel(int id)
with the same id. So, basically, you need to keep track of the id or possibly put the id into a Bundle you add to the Intent inside the PendingIntent?
Found this to be an issue when using Lollipop's Heads Up Display notification. See design guidelines. Here's the complete(ish) code to implement.
Until now, having a 'Dismiss' button was less important, but now it's more in your face.
Building the Notification
int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setPriority(NotificationCompat.PRIORITY_MAX) //HIGH, MAX, FULL_SCREEN and setDefaults(Notification.DEFAULT_ALL) will make it a Heads Up Display Style
.setDefaults(Notification.DEFAULT_ALL) // also requires VIBRATE permission
.setSmallIcon(R.drawable.ic_action_refresh) // Required!
.setContentTitle("Message from test")
.setContentText("message")
.setAutoCancel(true)
.addAction(R.drawable.ic_action_cancel, "Dismiss", dismissIntent)
.addAction(R.drawable.ic_action_boom, "Action!", someOtherPendingIntent);
// Gets an instance of the NotificationManager service
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
notifyMgr.notify(notificationId, builder.build());
NotificationActivity
public class NotificationActivity extends Activity {
public static final String NOTIFICATION_ID = "NOTIFICATION_ID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(getIntent().getIntExtra(NOTIFICATION_ID, -1));
finish(); // since finish() is called in onCreate(), onDestroy() will be called immediately
}
public static PendingIntent getDismissIntent(int notificationId, Context context) {
Intent intent = new Intent(context, NotificationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra(NOTIFICATION_ID, notificationId);
PendingIntent dismissIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
return dismissIntent;
}
}
AndroidManifest.xml (attributes required to prevent SystemUI from focusing to a back stack)
<activity
android:name=".NotificationActivity"
android:taskAffinity=""
android:excludeFromRecents="true">
</activity>
I found that when you use the action buttons in expanded notifications, you have to write extra code and you are more constrained.
You have to manually cancel your notification when the user clicks an action button. The notification is only cancelled automatically for the default action.
Also if you start a broadcast receiver from the button, the notification drawer doesn't close.
I ended up creating a new NotificationActivity to address these issues. This intermediary activity without any UI cancels the notification and then starts the activity I really wanted to start from the notification.
I've posted sample code in a related post Clicking Android Notification Actions does not close Notification drawer.
In new APIs don't forget about TAG:
notify(String tag, int id, Notification notification)
and correspondingly
cancel(String tag, int id)
instead of:
cancel(int id)
https://developer.android.com/reference/android/app/NotificationManager
In my opinion using a BroadcastReceiver is a cleaner way to cancel a Notification:
In AndroidManifest.xml:
<receiver
android:name=.NotificationCancelReceiver" >
<intent-filter android:priority="999" >
<action android:name="com.example.cancel" />
</intent-filter>
</receiver>
In java File:
Intent cancel = new Intent("com.example.cancel");
PendingIntent cancelP = PendingIntent.getBroadcast(context, 0, cancel, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Action actions[] = new NotificationCompat.Action[1];
NotificationCancelReceiver
public class NotificationCancelReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Cancel your ongoing Notification
};
}
You will need to run the following code after your intent is fired to remove the notification.
NotificationManagerCompat.from(this).cancel(null, notificationId);
NB: notificationId is the same id passed to run your notification
You can always cancel() the Notification from whatever is being invoked by the action (e.g., in onCreate() of the activity tied to the PendingIntent you supply to addAction()).
Just put this line :
builder.setAutoCancel(true);
And the full code is :
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.misti_ic));
builder.setContentTitle("Notifications Title");
builder.setContentText("Your notification content here.");
builder.setSubText("Tap to view the website.");
Toast.makeText(getApplicationContext(), "The notification has been created!!", Toast.LENGTH_LONG).show();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder.setAutoCancel(true);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
Just for conclusion:
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
Intent intent = new Intent(context, MyNotificationReceiver.class);
intent.putExtra("Notification_ID", 2022);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0,
intent,
...);
Notification notification = new NotificationCompat.Builder(...)
...
.addAction(0, "Button", pendingIntent)
.build();
notificationManager.notify(2022, notification);
and for dismiss the notification, you have two options:
approach 1: (in MyNotificationReceiver)
NotificationManager manager = (NotificationManager)
context.getSystemService(NOTIFICATION_SERVICE);
manager.cancel(intent.getIntExtra("Notification_ID", -1));
approach 2: (in MyNotificationReceiver)
NotificationManagerCompat manager = NotificationManagerCompat.from(context);
manager.cancel(intent.getIntExtra("Notification_ID", -1));
and finally in manifest:
<receiver android:name=".MyNotificationReceiver" />
builder.setAutoCancel(true);
Tested on Android 9 also.

Categories

Resources