【发布时间】:2015-06-27 22:14:12
【问题描述】:
我已经完成了一个安卓天气应用程序的构建。它使用 AsyncTask 从 api 获取天气,并通过在适配器上调用 notifyDataSetChanged() 来更新 onPostExecute() 中的 UI。
现在我还想创建一个后台服务/任务等。我知道 AlarmManager。我想知道,什么应该与AlarmManager一起使用来触发AsyncTask。我对这个问题的关注和原因是我的 AsyncTask 也在更新 UI。但是,如果任何后台服务调用 AsyncTask,由于应用程序当前未运行,因此前台没有 UI。会不会导致崩溃?
更新 在我的主要活动中,我调用此方法来启动我的警报管理器
public void scheduleAlarm() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, AlarmReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
long firstMillis = System.currentTimeMillis(); // first run of alarm is immediate
int intervalMillis = 10000; // 5 seconds
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, intervalMillis, pIntent);
}
报警管理器实现:
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, WeatherIntentService.class);
i.putExtra("foo", "bar");
context.startService(i);
}
意图服务实现
@Override
protected void onHandleIntent(Intent intent) {
// Do the task here
Log.i("MyTestService", "Service running");
}
我对如何启动异步任务感到困惑。由于我的异步任务依赖于共享首选项以及从 gms 收到的位置等。请引导我走向正确的道路。
【问题讨论】:
标签: android android-asynctask android-service alarmmanager