安卓定时任务

标签 android service scheduled-tasks locationmanager

我有一个任务。

6:00 register locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                0, 0, locationListener);<br>
19:00 unregister locationManager.removeUpdates(locationListener);

首先,我想通过 AlarmManager 使用服务。但我无法将 locationManagerlocationListener 从 Activity 发送到服务。

最后,我使用 AsyncTaskdoInbackground 中创建一个循环以一直运行。如果时间是6:00或19:00,注册或注销locationManager。

 protected Object doInBackground(Object... params) {
    Calendar calendar = Calendar.getInstance();
    while(flag) {
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 19);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        long now = System.currentTimeMillis();
        if(calendar.getTime().getTime() - now < 1000) {
            publishProgress(new Message(Message.REMOVE_LOCATION_MANAGER));
        }

        calendar.set(Calendar.HOUR_OF_DAY, 6);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        now = System.currentTimeMillis();
        if(calendar.getTime().getTime() - now < 1000) {
            publishProgress(new Message(Message.REGISTER_LOCATION_MANAGER));
        }
    }
    return null;
}
 protected void onProgressUpdate(Object... values) {
    super.onProgressUpdate(values);

    Message msg = (Message)values[0];
    if(msg.type == Message.REMOVE_LOCATION_MANAGER) {
        lm.removeUpdates(ll);
        Toast.makeText(context, "remove locationManager", Toast.LENGTH_SHORT).show();
    }

    if(msg.type == Message.REGISTER_LOCATION_MANAGER) {
        lm.removeUpdates(ll);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                0, 0, ll);
        Toast.makeText(context, "register locationManager", Toast.LENGTH_SHORT).show();
    }
}

谁有更好的调度方法,提前谢谢。

最佳答案

直接回答您的问题没有意义,您肯定需要重新考虑您的应用程序,因为没有任何 Android 设备可以在早上 6 点到晚上 19​​ 点运行 GPS 的情况下单次充电就可以使用。

基本上,您只有在真正需要时才需要请求 GPS 位置更新。这是 Android Guru Reto Meyer 撰写的一篇关于获取位置更新的好文章:http://android-developers.blogspot.jp/2011/06/deep-dive-into-location.html

关于安卓定时任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10308465/

相关文章:

Android 应用程序 CPU 使用率高

c# - 从服务向 WPF 应用程序发送通知的好方法

android - 仅使用一行 listview 中的 imageview 来启动一个新的 intent

java - 如何正确获取电影文件夹?

java - Android 10 java 中销毁应用程序后后台服务在 20 秒后停止

scala - Play 2.4.x 中的 Crontab 风格调度?

php - 将所有日期信息放在一个单元格中,位于员工日程表的动态表中

Android 服务和线程中运行的重复性任务

Android gradle ndk jni build with external library & native debugging (ARToolkit)

android - 能不能放一个DrawableShape或者Shape, "directly in"一个布局?