服务或IntentService或AlarmManager方法 [英] Service or IntentService or AlarmManager approach

查看:157
本文介绍了服务或IntentService或AlarmManager方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个类似游戏的应用程序,我一直在阅读有关与服务在背景,前景,警报运行的东西等等所有不同的方法,我有点糊涂了。

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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆