Вопрос

I have this Service that do other stuff in the background and must always be running. On its onCreate i've set an Alarm that sends an email once a day. The server is not running in foreground, so sometimes its get killed by the system, and then created again, and when that happens its creates the alarm again, and sends another email every time it happens. So my question is, is there a way to prevent it from triggering the alarm if its already set for repeating in the system? Or is there another "place" in the Service where i can create the alarm once and prevent it for being recreated with the it?

public class ObserverService extends Service {  


private String BABAS = "babas";

@Override
public void onCreate() {

    setRecurringAlarm(this);

}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {      

    return START_STICKY;
}



@Override
public IBinder onBind(Intent intent) {

    return null;
}





private void setRecurringAlarm(Context context) {
    Log.i(BABAS, "entrou no set alarme");

    Calendar updateTime = Calendar.getInstance();
    updateTime.setTimeZone(TimeZone.getDefault());//getTimeZone("GMT"));
    updateTime.set(Calendar.HOUR_OF_DAY, 00);
    updateTime.set(Calendar.MINUTE, 00);
    Intent downloader = new Intent("ALARME");//context, AlarmReceiver.class);
    PendingIntent recurringDownload = PendingIntent.getBroadcast(context,
            0, downloader, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarms = (AlarmManager)        context.getSystemService(Context.ALARM_SERVICE);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringDownload);
}

}

Это было полезно?

Решение

If that code is everything your Service does you can completely get rid of the Service.

The only thing the service does is schedule a Broadcast once a day on the alarm manager, why not do this schedule directly from the Activity?

edit:

Given your comment, my original answer remains: The Alarm set on the AlarmManager is permanent until the device is turned off or rebooted. So you can set the first alarm via Activity and mark it as active on the SharedPreferences. Create a BroadcastReceiver to receive onBoot events, this receiver will check the SharedPreferences for if the alarm is active and in case it is, re-register it on the AlarmManager.

Your service still does the same ContentObserver stuff, but have no association with the recurring AlarmManager event.

I reckon that would be cleanest solution.

Alternatively (but I don't think it's a good/clean solution), you can use the AlarmManager.cancel() to remove the existing PendinIntent, and then re-trigger it

http://developer.android.com/reference/android/app/AlarmManager.html#cancel(android.app.PendingIntent)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top