Service or IntentService or AlarmManager approach

2019-05-10 00:27发布

I am building a game-like application and I've been reading about all the different approaches of running things with Services in background, foreground, Alarms and so on, and I am a bit confused.

My app would go like this (example):

  • user presses a button in Main, then he can close the app
  • after 30 minutes Activity1 opens up
  • user finishes whatever he needs to do in that activity, which triggers the next activity to start after 2 hours
  • after 2 hours Activity2 opens up
  • user finishes whatever he needs to do there as well, triggering the next one
  • after a day Activity3 opens up, and so on

What would be the best approach? Have a service running continuously to open those activities, or get a new alarm set up to start every time the user finishes one of the activities?

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-10 00:42

Please do not create a service just to it can stay idle for several hours. It makes no sense.


What you need to do is to create an alarm. something like:

alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);

alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, alarmIntent);

This is just a general example for the Alarm API. You will need to adjust it for your needs.


Finally - please be aware: alarms is not boot resilient! That is: if for any reason the user's device goes down, all of your alarms will be lost.

if you do want your app to be boot resilient you will need to register to an event called RECEIVE_BOOT_COMPLETED (think post-boot) where you will restart your pending alarms:

//manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>



<receiver android:name=".MyBootReceiver"
        android:enabled="false">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"></action>
    </intent-filter>
</receiver>


//java class
public class MyBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            // restart alarms
        }
    }
}


Hope it helps

查看更多
登录 后发表回答