Frage

Hello I'm noob in Android. I have already seen this How to loop or to repeat periodically task in Android?

I want to know the different types of ways you can repeat your task in background Android. I know only about AlarmManager where you can execute your code after specific time. Is there any other ways also to do same. Any idea ?

War es hilfreich?

Lösung

AlarmManager will be good choice as its a system service and you don't need to create extra service for that. To start a AlarmManager you need a pending intent and a background task to do the heavy stuff.

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, DownloadService.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
boolean alarmUp = (PendingIntent.getBroadcast(ViewPagerActivity.this,
    0, new Intent(ViewPagerActivity.this, DownloadService.class),
    PendingIntent.FLAG_NO_CREATE) != null);

if (alarmUp)
    am.cancel(sender);

You can use this code at the time of initialization of activity or onCreate(). Where DownloadService is a extend of BroadcastReceiver Class.

public class DownloadService extends BroadcastReceiver 

inside onReceive method of this class you can do your periodic repeat task.

And this is how you can start your alarm and you put this code inside resume of activity or some other callback

am.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis(), globalData.serviceTimeInterval,
                sender);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top