I want to create Notification in Android.
But, If I kill the application via TaskManager, it terminate the Notification too..
It is the code-snipet.
it is the caller.
Intent intent = new Intent(myActivity, NotificationReciever.class);
String appName = myActivity.getTitle().toString();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, time);
AlarmManager alarmManager = (AlarmManager)
myActivity.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
it is the Reciever.
public class NotificationReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
I added the code, but it can't
intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
I' like to make alive the Notification.
Would you tell me how to avoid the TaskManager's killing?
Would you tell me how to avoid the TaskManager's killing?
That is not possible, except perhaps via a custom build of the Android OS, put into your own ROM mod to deploy on your own devices.
Related
So far I've been using AlarmManager and BroadcastReceiver like this:
private void setUpStreakResetAlarm() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.add(Calendar.DAY_OF_MONTH, 1);
Intent intent = new Intent(getApplicationContext(), DailyCounterCheckReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
And in my DailyCounterCheckReceiver class:
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
int counterOld = sharedPreferences.getInt(GlobalUtilities.SHARED_PFC_STREAK_COUNTER_OLD_KEY, 0);
int counterToday = sharedPreferences.getInt(GlobalUtilities.SHARED_PFC_STREAK_COUNTER_KEY, 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
// If user has increased counter on this day, increase the old check for tomorrow
if (counterToday > counterOld) {
counterOld = counterToday;
editor.putInt(GlobalUtilities.SHARED_PFC_STREAK_COUNTER_OLD_KEY, counterOld);
editor.putBoolean("increasedOld", true);
editor.putBoolean("reset", false);
}
// etc.....
But with new Android versions, background tasks like that just get killed and it's very unreliable.
So what can I use instead? Work Manager, Foreground Service, something else?
And don't I still need AlarmManager to trigger them?
My use case is extremely simple, so I don't think I need some super complex solution, but there are so many options out there. What is better for my simple case?
Edit:
Angel's comment would solve my reset problem, but I also do the same for triggering notifications at certain times:
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putLong("lastTimeOfNotifTrigger", System.currentTimeMillis());
editor.apply();
repository = new NotificationRepository(context);
repository.startGetNextNotificationAsync(this);
}
How could I solve that in the easiest way?
You could use alarmManager.setExact to schedule the alarms (so that your receiver is called exactly at the time you want even if the phone is sleeping or in Doze mode). Once your receiver is called you can schedule the next. Remember to also add receivers detecting BOOT and PACKAGE_CHANGED so that you can re-schedule the alarms in case the phone is rebooted or the app updated.
You could also use Work Manager as you said to schedule a job, if you don't need it to be run at an exact time.
Your code shouldn't have any other issue running in newer versions of Android if you are not trying to launch an Activity from that receiver (you can't launch an activity anymore from the background).
I want a task to do which require internet connection and it's must scheduled once in a day. I achieve above task partially using alarm manager like below.
Calendar c = Calendar.getInstance(); //gives u calendar with current time
c.add(Calendar.SECOND, 30);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
if (alarmManager != null) {
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
// my broadcast receiver
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//my task will be here
// for now I planned to check internet here and if it has i'll continue the task
}
}
//in manifest
<receiver android:name=".broadcast_receiver.AlarmReceiver" />
Is there any way to postpone above task in same day whenever got internet connection?
Can AlarmManager be used to achieve above requirement?
You can achieve that with WorkManager. Check out the official docs for more info.
I have an app that needs to reset its text fields and other views everyday. Its like a daily tasks that remain constant but the progress has to be reset everyday or at 12am
That a really easy task to implement using AlarmManager.
Following this guide it should be easy for you.
Example:
//define your intent
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PedingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to start at approximately 00:00 h(24h format).
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 00);
//repeteat alarm every 24hours
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
Now create a BroadcastReceiver called "AlarmReceiver" and inside it, do whatever you want to.
public class AlarmReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//do whatever you want.
}
}
Maybe you should use a WakefulBroadcastReceiver depending of your task.
I am making a small android APP and I want to have some code that runs once a day at 6AM. When the app is not running to update some parameters and send a notification to the user telling them to enter the app. Can someone help me by telling me the best way to go about doing this?
You can do it like so with alarm manager, pending intent and a broadcast receiver. This code will wake up the device every two hours:
AlarmManager alarmManager = (AlarmManager)this.getSystemService(ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
//set the alarms to start in the time period
cal.add(Calendar.MILLISECOND,60000);
Intent i = new Intent(this, AlarmBroadcastReceiver.class);
PendingIntent getSqlUpdatesTimer = PendingIntent.getBroadcast(this, 0, i, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 7200000, getSqlUpdatesTimer);
And your broadcast receiver:
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
if (intent != null) {
PowerManager pm = (PowerManager)context.getSystemService(context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wl.acquire();
//Some code to do your task
wl.release();
}
}
}
You also need to have the wakelock permission set in your Manifest.
I have some doubts that I would like to clear regarding the AlarmManager class in Android.
I have an app that needs to:
Allow the user to set a time.
Start an alarm.
Then, even if the app is closed, it should start up on the preset time and do a certain function (like button.performClick()) in the main activity.
So, I have successfully created an activity called alarm.java, created the layout in res\layout and added it to AndroidManifest.xml. Also, I have successfully set the alarm as follows in my alarm.java class:
onCreate(){
alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
intent = new Intent(context, MyActivity.class);
pi = PendingIntent.getBroadcast(this.getApplicationContext(), ALARM_ID, intent, 0);
}
onClick(){
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
Toast.makeText(getApplicationContext(), "Alarm Set For " + hour + ":" + minute + " " + ampm, Toast.LENGTH_LONG).show();
}
Now, in my MyActivity.java class, which is the main activity, I have added the BroadcastReceiver
public BroadcastReceiver AlarmReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
/*This is the part I got from SO for starting an activity from `BroadcastReceiver`
Intent i = new Intent();
i.setClassName("com.kanishka.nightstalker.homeautomation", "com.kanishka.nightstalker.homeautomation.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);*/
Toast.makeText(getApplicationContext(), "APP STARTED", Toast.LENGTH_LONG).show();
button.performClick();
}
};
Obviously, this method isn't working as I see no Toast popping up after elapsed time. I kinda understand what the issue is, and I should be using a Service for this. But from what I know, AlarmManager itself runs in the background and SHOULD trigger the BroadcastReceiver of MyActivity.java on elapsed time. Where am I going wrong?
Where am I going wrong?
You are using setInexactRepeating(). Here, "inexact" means "not exact", and so the alarm will occur sometime within INTERVAL_DAY of your requested time.
You are taking the current time, then setting the hour and minute, which could result in a time in the past.
You are creating an Intent for MyActivity, which is probably not a BroadcastReceiver (or, if it is, MyActivity is a very odd name to choose).
If you want the alarm to go off "even if the app is closed", then you need to use a BroadcastReceiver that is registered in the manifest.
It is not possible to "do a certain function (like button.performClick()) in the main activity", as there will not be an activity "if the app is closed".