Android - start alarm service immediately?

I created an On Boot Receiver to call the wake service again every 5 minutes, but I canโ€™t figure out how to start the service right after installing the application.? I do not want to rely on the user rebooting their device before it starts working!

Here is my code:

public class OnBootReceiver extends BroadcastReceiver { private static final int PERIOD = 300000; // check every 5 minutes @Override public void onReceive(Context context, Intent intent) { AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, OnAlarmReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60000, PERIOD, pi); }} 

Can anyone help me? :)

0
source share
2 answers

If you want to set up an accountant to start the service when the application is installed, then this is not possible. This is an OS limitation, security, if you like. But if you want to start the service at the moment when the application starts, just call it, it will continue to work.

+1
source

Essentially, since the application object is created when the application starts and when it receives the BOOT_COMPLETED intent, you can register with AlarmManager in the onCreate method in your custom Application class. Just keep in mind that the application object is created every time a process starts, which includes cases where the process is temporarily killed to save resources. But if you do not change the PendingIntent in any way, it should not be a problem to register again and again.

However, when starting the application, it is impossible to start the application, first there must be some interaction with the user.

0
source

Source: https://habr.com/ru/post/920225/


All Articles