SQLiteNoob
SQLiteNoob

Reputation: 3022

Service stops after restarting phone

I have a service running from an AlarmManager set to record sensor data at regular intervals.

I had a problem where opening the app would execute the service in it's onCreate every time the app was started/run. So I implemented the following to ensure it only runs at it's intervals:

        Intent intent = new Intent(getApplicationContext(), Service.class );
        AlarmManager scheduler = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        //Boolean to see if alarm is already set:
        alarmUp = (PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE) != null);
        //make pending intent to schedule
        PendingIntent scheduledIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (runOnce == false){

            if (!alarmUp){
                Log.d("alarmUp", "= false");
                scheduler.setInexactRepeating(AlarmManager.RTC_WAKEUP, 900000, 900000, scheduledIntent);
            }
                runOnce = true;
                    SharedPreferences.Editor editor = prefs.edit();                         
                    editor.putBoolean(RUN_ONCE, runOnce);
                    editor.commit();            
        }               
        //Alarm Manager schedule Start Service:
        if (alarmUp){
            Log.d("alarmUp", "= true");
            // 15 min intervals = 900000
            //scheduler.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 900000, scheduledIntent);
            scheduler.setInexactRepeating(AlarmManager.RTC_WAKEUP, 900000, 900000, scheduledIntent);
        }

I introduced the runOnce boolean because the getBroadcast was either always running the service, or not starting it at all on a fresh install of the application. This was the solution, but causes a new problem - after turning the device on and off, the service won't start again.

How can I address this problem? I can either find another way to start the service without having it running too frequently, or implement a check for when the device was last turned off to reset the runOnce boolean?

Thanks for any advice.

Upvotes: 1

Views: 877

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007474

How can I address this problem?

Reschedule your alarms after a reboot, using an ACTION_BOOT_COMPLETED BroadcastReceiver, as is illustrated in this sample project. AlarmManager scheduled events do not survive a reboot, so you have to re-establish them yourself.

BTW, I would recommend replacing getApplicationContext() with this in your code shown above. Only use getApplicationContext() when you know why you should be using getApplicationContext() in the specific situation.

Upvotes: 2

Related Questions