Android:在alarmmanager触发的服务中使用wakelock

时间:2012-10-10 16:19:33

标签: java android service alarmmanager wakelock

在我的应用程序中,我发出警报,触发从互联网下载信息并显示通知的服务。

以下是我的代码的简化版本:

MyActivity包含以下内容:

            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, 20);
            Intent intent = new Intent(this, AlarmService.class);
            PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 20000, pendingIntent);

AlarmService看起来像这样:

public class AlarmService extends Service {

    @Override
    public void onCreate() {

        new myAsyncTask().execute();

    }

    private class myAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... args) {

            //Download stuff

            return null;
        }

        @Override
        protected void onPostExecute(Void arg) {
            //Show notification
        }
    }
}

我真的不明白何时使用唤醒锁定,所以我的问题是:在这种情况下,我应该使用唤醒锁定,如果是这样,我应该在哪里开始和停止它?

提前致谢

1 个答案:

答案 0 :(得分:2)

是的,您需要使用WakeLock来确保您的服务能够完成其工作。

如果使用IntentService符合您的设计要求,我会看一下WakefulIntentService。它代表您管理警报和WakeLock,并且易于设置。警报触发时获取WakeLockWakefulIntentService库在服务完成时负责释放它。

如果你走这条路,你不会想要使用AsyncTask - 你需要让服务保持忙碌(在doWakefulWork()方法中)以保持WakeLock