AlarmManager.setRepeating - 服务似乎不重复

时间:2013-10-29 12:52:55

标签: android android-service alarmmanager android-alarms

我正在开发一个Android应用程序,该应用程序起诉后台任务每隔x秒从用户端定义一次获取XML(用户定义的间隔,默认为60)。我的结构如此:

MainActivity

通过AlarmManager计划报警:

public static void scheduleAlarm(Context voContext, int viCheckInterval)
{
    try {
        moAlarmManager = (AlarmManager) voContext.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(voContext, AlarmReceiver.class);
        moAlarmIntent = PendingIntent.getBroadcast(voContext, 0, intent,
                                                    PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(System.currentTimeMillis());
        time.add(Calendar.SECOND, viCheckInterval);
        moAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
                                       time.getTimeInMillis(), moAlarmIntent);
    } catch (Exception e) {
        Log.e("MessageCheckAlarmHandler", e.toString());
    }
}

AlarmReceiver

这是启动服务的BroadcastReceiver:

@Override
public void onReceive(Context context, Intent intent)
{
    Context oAppContext = context.getApplicationContext();

    if (oAppContext == null) {
        oAppContext = context;
    }

    Intent serviceIntent = new Intent(oAppContext, MessagingService.class);
    oAppContext.startService(serviceIntent);
}

的MessagingService

这会创建我们的内部记录器(通过TCP记录)并启动一个名为FetchPageTask的AsyncTask:

public class MessagingService extends Service
{
    @Override
    public void onCreate()
    {
        super.onCreate();

        ...

        this.acquireLocks();

        try {
            String sCheckerUrl = oPreferences.getString("pref_server", "");
            int sCheckerPort = Integer.parseInt(oPreferences.getString("pref_server_port",
                                                                           "8050"));
            sCheckerUrl = String.format(URL, sCheckerUrl, sCheckerPort);

            this.moFetchInboxTask = new FetchPageTask(this.logger, this);
            this.moFetchInboxTask.execute(sCheckerUrl);
        } finally {
            this.releaseLocks();
            this.stopSelf();
        }
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();

        this.logger.close();
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    /**
     * Acquire a WakeLock and a WifiLock.
     */
    private void acquireLocks()
    {
        try {
            // Acquire a wake lock to prevent the device from entering "deep sleep"
            PowerManager oPowerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            this.moWakeLock = oPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
            this.moWakeLock.acquire();
            // Acquire a WiFi lock to ensure WiFi is enabled
            WifiManager wm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
            this.moWifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, TAG);
            this.moWifiLock.acquire();
        } catch (Exception e) {
            this.logger.error(TAG + "->onCreate()", "Error acquiring locks: " + e.toString());
        }
    }

    /**
     * Release our WakeLock and WifiLock.
     */
    private void releaseLocks()
    {
        try {
            this.moWakeLock.release();
            this.moWifiLock.release();
        } catch (Exception e) {
            this.logger.error(TAG + "->releaseLocks()", e.toString());
        }
    }
}

FetchPageTask

这扩展了AsyncTask并完成了获取页面和解析XML的所有工作。然后,如果需要,它还会添加通知并对检索到的数据执行操作。


这一切都运行良好,但不会随后运行。我知道AsyncTask的工作原理与之前通过ScheduledExecutorService和ScheduledFuture使用纯Java一样,并且有效。我决定更改为使用AlarmManager的唯一原因是出于可维护性目的。

2 个答案:

答案 0 :(得分:2)

首先,您要立即设置警报,然后每隔约43年设置一次警报。这不太可能是你想要的。将您对setRepeating()的调用的第三个参数修改为所需的时间段(以毫秒为单位),现在将其设置为自1970年1月1日午夜以来的毫秒数。

其次,您收到WakeLock为时已晚。无法保证您的acquireLocks()在设备入睡前有机会运行。 My WakefulIntentServicethe new WakefulBroadcastReceiver提供了更好的模式,可将控件传递给IntentService

答案 1 :(得分:0)

我认为你不需要这里的日历。你只想每隔x秒运行一次动作,所以它会是这样的:

 moAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                                   viCheckInterval, moAlarmIntent); 

//  viCheckInterval should be long miliseconds