Android: App not started by AlarmManager after app exit - android

I'm trying to make an app to restart from a command sent by my server, searching on the internet i find that the best way to do this is by using AlarmManager so it starts the app at some moment.
So the code i've made this far looks like this:
val intent = Intent(this, StartActivity::class.java)
val wait = TimeUnit.SECONDS.toMillis(3)
val intentId = 123
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra(EXTRA_RESTART_ID, this.restartId)
intent.putExtra(EXTRA_COMMAND_NAME, this.restartCommandName)
val pendingIntent = PendingIntent.getActivity(this.applicationContext, intentId, intent, PendingIntent.FLAG_ONE_SHOT)
val manager: AlarmManager = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// Set alarm manager to start after 3s
manager.set(AlarmManager.RTC, System.currentTimeMillis() + wait, pendingIntent)
// Kill application
this.finish()
exitProcess(2)
Doing this i've noticed that the app doesn't start again consistently.. sometimes it doesn't work and i have no idea why it doesn't, i have tried changing the wait time, as well as the intent id and exit code, but it just continues to be inconsistent.
Also.. checking the alarm system in shell using adb shell dumpsys alarm doesn't show the alarm added by the application.
What could be the cause of the app not starting again sometimes?
Note: Phone is running on Android 9

Related

AlarmManager.setAlarmClock not triggering

I have been coding an app on my phone, a xiaomi with MIUI 12.0.3 and android 10, and the alarm triggered normally, but recently I changed to another phone, a realme with android 12, and the alarm doesn't trigger anymore.
Instead of the application opening itself when the alarm triggers and the new activity starting, I need to open the app and then the activity starts, the alarm never opens the app by its own, which is what I am looking for since this is essentialy an alarm app.
I tried changing all the battery settings and background restrictions on the phone but still it doesn't work. Is there something that have changed on the android version that has made this stop working? Here's the code of the alarm.
#RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun prepareNextAlarm() {
alarm = getSystemService(ALARM_SERVICE) as AlarmManager
val intent = Intent(applicationContext, Pedometer::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pi = PendingIntent.getActivity(applicationContext, 0, intent, 0)
val nextAlarmTime = getNextAlarmTimestamp();
val alarmInfo = AlarmManager.AlarmClockInfo(nextAlarmTime, pi);
saveNextAlarmTime(nextAlarmTime)
alarm!!.setAlarmClock(alarmInfo, pi);
}
Thank you so much for everyone in advance for the help!

How to restart android app programmatically

I want to re-start my app through Pending intent. Below code is not working.
val intent = Intent(this, Activity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
}
val pendingIntentId = 1
val pendingIntent = PendingIntent.getActivity(this, pendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT)
val mgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val timeToStart = System.currentTimeMillis() + 1000L
mgr.set(AlarmManager.RTC, timeToStart, pendingIntent)
exitProcess(0)
Target version is 31, so updated pending intent with PendingIntent.FLAG_MUTABLE still not working. I searched in many links related to this but no luck.
Restarting Android app programmatically
Force application to restart on first activity
https://www.folkstalk.com/tech/restart-application-programmatically-android-with-code-examples/#:~:text=How%20do%20I%20programmatically%20restart,finishes%20and%20automatically%20relaunches%20us.%20%7D
In Nov 2022, When target version is 31 & min sdk version is 29, above pending intent code is not restarting the App.
Any clue why above pending intent is not working or any other suggestion apart from re-launching the activity ?? I don't want to re-launch using startActivity(intent)
When you want to resteart the entire app you could use the very easy libary: ProcessPhoenix
You can just simply insert the Library and execute:
ProcessPhoenix.triggerRebirth(context);
or with a specific intent:
Intent nextIntent = //...
ProcessPhoenix.triggerRebirth(context, nextIntent);
This is the easiest way to restart an android app programatically.

AlarmManager SetExact() Is Not Triggering While App Is Not Running - Android

I'm creating an activity logging app, Where it's user can explicitly set a series of time first. On those set times I want to launch one of the activity which need to popup & collect data from user and go away.
(Data like how much you drink today, How many km jogged, What foods you ate, Did you exercise today etc...).
These are the constrains
The app is very much dependent on precise user defined dates and times. So I think I
had to use setExactAndAllowWhileIdle() with AlarmManager
User can be fully aware that the app need to run always. I've no issues running my tracker as a HIGH_PRIORITY Foreground service if that can offer reliable explicit data collection from user. In that case how to change this code?
For this purpose, I tried using AlarmManager. But it is triggering only when the app is in forground. How can I call the activity even if the app is not running on precise timings?
fun setAlarm()
{
val myIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0)
val alarmManager: AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val calendar: Calendar = Calendar.getInstance()
calendar.timeInMillis = System.currentTimeMillis()
calendar.add(Calendar.SECOND, 5)
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)
Toast.makeText(baseContext, "Alarm Set", Toast.LENGTH_LONG).show()
}
Or should I use start an always running foreground service and later on set times throwing an Intent to OS for starting an activity? Is it a good approach?

android force kill schedule service every minute

I want to schedule a service to run every minute and check if my app is still running. (I want to reopen the application if it is closed).
Also, I still want this service to run every minute if my application was force killed by task manager.
Thanks!
Also, I still want this service to run every minute if my application was force killed by task manager
This is not possible as of Android 3.1. If the user goes into Settings and force=stops your app, nothing of your app will run again, until the user manually launches one of your components.
If your process is terminated for other reasons (e.g., ordinary task-killer app from the Play Store, swiping your task away from the Recent Tasks list), your alarms scheduled with AlarmManager should remain intact, per Lucifer's suggestion.
im writing a "Parent Control" app which is installed on the child's phone.
Any child sufficiently intelligent to use a phone will be sufficiently intelligent to reboot their device in safe mode and get rid of your app.
Use AlarmManager class, it works even if your device is in sleep mode.
private static Intent alarmIntent = null;
private static PendingIntent pendingIntent = null;
private static AlarmManager alarmManager = null;
// First Creating an Intent
alarmIntent = new Intent ( context, yourClass.class );
// Create an Pending Intent which will Broadcast the Intent
pendingIntent = PendingIntent.getBroadcast(context, 234324243, alarmIntent, 0 );
// Set the AlarmManager class
alarmManager = ( AlarmManager ) context.getSystemService( ConstantCodes.ALARM_SERVICE );
// Set Repeating time interval
alarmManager.setRepeating( AlarmManager.RTC_WAKEUP, Interval * 1000, Interval * 1000, pendingIntent );
AlarmManager consumes lesser battery power than TimerTask or Thread. It works like painless AsyncTask.

How to set a timed event which will keep running even if the application is stopped

I need to have a process run whenever the end-user clicks on a Submit button. The application needs to try to process the data on the screen every X minutes, Y times, even if the the application is down. So, it will need to attempt to do some processing until one of the following occurs:
1) The processing is successful for the data that was submitted
2) The processing has been retried Y times and still never succeeded
3) The application is terminated by the OS or the phone is turned off.
If the end-user's phone is still on but the application has stopped,
what's the correct interface to use to accomplish this?
If I use Handler/Runnable, that only works as long as the application stays active.
AlarmManager looks like it's used when you want processing to run at a specific time.
Any suggestions will be greatly appreciated!
I use this method to set an alarm.
private void setAlarm(){
Context context = getApplicationContext();
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
myCal = Calendar.getInstance();
myCal.setTimeInMillis(myPrefs.getLong("time", 0));
mgr.set(AlarmManager.RTC_WAKEUP, myCal.getTimeInMillis(), pi);
Log.i(myTag, "alarm set for " + myCal.getTime().toLocaleString());
Toast.makeText(getApplicationContext(),"Alarm set for " + myCal.getTime().toLocaleString(), Toast.LENGTH_LONG).show();
}
inside my onAlarmReciever onRecieve method is this:
Intent i = new Intent(context, AlarmActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
So basically when the intent fires it starts the AlarmActivity. Inside that activity you could have it try what ever you are doing and if it fails call the setAlarm() again
You have two options: a Service, or set up an alarm with AlarmManager. Which one you pick will depend mostly how often do you want to retry. A minute? Use a service. An hour? A day? set up an alarm so you don't waste the phone resources keeping the service alive.
http://developer.android.com/reference/android/app/Service.html
http://developer.android.com/reference/android/app/AlarmManager.html
Write an Android Service

Categories

Resources