How to keep the scheduled handler post delayed timer task is available once the app quits inside of Alarm Receiver on-receive Method?

928 views Asked by At

I have used 20 seconds Handler Post Delayed Timer task inside Alarm Receiver on-receive Method. The app is working fine if i quit the app before the alarm receiver on-receive method gets called. If I quit the app once the Handler Post delayed Timer task scheduled. Then the Handler Post delayed Timer task automatically cancelled after quitting the application. So post delayed Timer task never called in my application.

Code snippet:

Handler handler= new Handler();
handler.postDelayed(networkRunnable,
                10000);

/**
 * A runnable will be called after the 10 second interval
 */
Runnable networkRunnable= new Runnable() {
    @Override
    public void run() {
        // Called after 10 seconds
        cancelNetworkTask();
        // My Job to do after 10 seconds
    }
};

After quitting the app then from when next alarm receiver on-receive method called will schedule the timer task and is working fine.

I tried goAsync() inside of Alarm Receiver on-receive method. So this also not helps me to solve this issue. Once i quit the application my scheduled timer task is cancelled.

How to keep the scheduled handler post delayed timer task is available once the app quits inside of Alarm Receiver on-receive Method.

Please help me on this.

1

There are 1 answers

5
Psypher On

If you schedule an Intent with AlarmManager the application will be started when the intent is fired even if app has been closed.

Add the below in your activity:

AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, alarmIntent, 0);
        manager.set(AlarmManager.RTC_WAKEUP, 10000, pendingIntent); //set 10 sec

Create a class AlarmReceiver

    public class AlarmReceiver extends BroadcastReceiver {
        PowerManager.WakeLock wl;

  @Override
        public void onReceive(Context context, Intent intent) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backgroundwakelock");
            wl.acquire();

    //put your ui update code here
            wl.release();
        }
    }

Add below in Manifest file

<receiver android:name=".AlarmReceiver"/>