我建立一个类似游戏的应用程序,我一直在阅读有关与服务在背景,前景,警报运行的东西等等所有不同的方法,我有点糊涂了。
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):
- 用户presses主按钮,那么他就可以关闭应用程序
- 30分钟后活动1打开
- 什么,他需要在这一活动做用户完成,这触发后2小时,开始下一个活动 活性2打开后2小时
- 高达
- 无论他需要做的有作为用户完成,触发下一个
- 一天后Activity3打开了,等等
什么是最好的方法?有一个服务持续运行打开这些活动,或者得到一个新的警报设置为每次启动用户完成的活动之一的时间?
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?
推荐答案请不要创建只是为了能赋闲了好几个小时的服务。这是没有意义的。
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);这是只为报警API 一般的例子。您需要调整您的需求。
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
更多推荐
服务或IntentService或AlarmManager方法
发布评论