0

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

这是我的代码的简化版本:

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

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

提前致谢

4

1 回答 1

2

是的,您需要使用 aWakeLock来确保您的服务可以完成其工作。

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

如果你走这条路,你将不想使用 AsyncTask - 你需要保持服务活跃(在它的doWakefulWork()方法中)以保持WakeLock.

于 2012-10-10T16:29:27.637 回答