【问题标题】:How can I wake my android application at certain regular time intervals?如何以特定的时间间隔唤醒我的 android 应用程序?
【发布时间】:2012-02-11 23:46:11
【问题描述】:

我的目的是制作一个应用程序,每隔几分钟跟踪我的安卓手机的移动并将其发送到我的服务器。我在网上阅读了很多关于如何使用服务、AlarmManager 和 Partial_WakeLock 来做到这一点的内容。我也浏览了 github.com 中的 commonsware 示例,但我有点困惑,因为我仍然没有使用 android 的经验。

我已成功让我的应用程序 [获取位置并将其发送到我的服务器]。我如何让我的服务每隔几分钟唤醒一次并做[提到的工作]?在 commonsware 中的 Wakeful 示例中,我在哪个方法中提及我的 [work] 以及我在哪个方法中继续调用它?

【问题讨论】:

    标签: android service commonsware


    【解决方案1】:

    您需要ServiceAlarmManager。您的服务将处理获取位置并将其发布到服务器,AlarmManager 将根据您决定的时间间隔调用您的服务。您应该在 onCreate 或您想要的其他地方使用您的 Service 大致像这样初始化您的 AlarmManager:

    AlarmManager alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, YourAlarmReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
    
    // Use inexact repeating which is easier on battery (system can phase events and not wake at exact times)
    alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, YOUR_ALARM_TRIGGER_AT_TIME,YOUR_ALARM_INTERVAL, pendingIntent);
    

    YourAlarmReceiver 将启动您的服务

    public class YourAlarmReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
              context.startService(new Intent(context, YourService.class));
        }
    }
    

    关于如何使用服务请参考android网站http://developer.android.com/guide/topics/fundamentals/services.html

    【讨论】:

    • 我会试试这个,如果顺利的话,我会在这里发布。谢谢。
    • 我试过了,目的很好。我现在遇到的问题是我得到了太多的数据点。我要求 LocationManager 仅在看到至少 10 米的位移时才进行 [工作]。尽管如此,我每隔一秒(几乎)在同一位置获取数据点,直到看到位移。这可能是因为 AlarmManager 吗?
    • 您是否使用 AlarmManager 调用 LocationManager?您给 AlarmManager 的时间间隔将用于在这些时间间隔调用您喜欢的服务......我无法完全理解问题?你是说你有太多更新,如果是这样你可以增加间隔..用alarmmanager得到结果后如果没有10米的位移你可以处理结果我不知道但10米的位移似乎gps 精度不够。
    • 好的,我应该更清楚。如上所述,我已经包含了 AlarmManager 和 Receiver,提供的参数使警报在我启动服务后 1 分钟首先响起,并且每隔 1 分钟调用一次。每次我创建一个新意图并使用 alarmMgr.cancel(pendingIntent); 取消它时;
    • 现在,我假设当警报响起时,它会检查服务是否开启,如果开启则什么也不做。但是,在服务开启一个小时或更长时间后,我将获得 20 个相同位置的副本(具有不同的时间戳)。我的问题是,AlarmManager 是否每次都会创建新的服务副本,因此会产生大量数据点?
    【解决方案2】:

    您可以使用带有 sleep(X) 的部分唤醒锁,当 sleep(x) 解决时,系统将调用下一行代码,但问题是我看到可能需要一个任务的无限循环杀死动作,或者干脆让系统崩溃。

    【讨论】:

    • 我也要试试这个。问题是我不在乎它是否进入无限循环,因为我需要数据,比如说,在一起的日子。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多