Service or IntentService or AlarmManager approach

天大地大妈咪最大 提交于 2019-12-22 09:58:38

问题


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:


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



来源:https://stackoverflow.com/questions/24586199/service-or-intentservice-or-alarmmanager-approach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!