2

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

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

4

2 回答 2

7

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

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));
    }
}

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

于 2012-02-12T00:11:58.903 回答
0

您可以使用带有 sleep(X) 的部分 wakeLock,当 sleep(x) 解决时,系统将调用下一行代码,但问题是我看到可能需要执行任务终止操作的无限循环,或者只是使系统崩溃。

于 2012-02-12T00:00:15.543 回答