1

I am currently starting a service using a Broadcast Receiver which fires 60 seconds after the device boots up. This broadcast receiver triggers an alarm so that my service runs every 60 seconds. Code for this is as follows:

public class ScheduleReceiver extends BroadcastReceiver {
    // Restart service every 60 seconds
    private static final long REPEAT_TIME = 1000 * 60;

    @Override
    public void onReceive(Context context, Intent intent) {
        AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, StartServiceReceiver.class);
        PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);

        Calendar cal = Calendar.getInstance();
        // Start 60 seconds after boot completed
        cal.add(Calendar.SECOND, 60);
        // Fetch every 60 seconds
        // InexactRepeating allows Android to optimize the energy consumption
        service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pending);
    }
}

The above starts the service as follows:

public class StartServiceReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, PhotoService.class);
        context.startService(service);
    }
} 

I would like to somehow modify this so that my service runs every 60 seconds when the phone screen is on and every 20 minutes when off.

What is the best way to do this ? Can I modify the alarm dynamically when the screen is switched off/on ?

Thanks for any help,

Regards,

Fido

4

1 に答える 1