我已经完成了一个安卓天气应用程序的构建。它使用 AsyncTask 从 API 获取天气信息,并通过调用适配器上的 notifyDataSetChanged() 在 onPostExecute() 中更新 UI。
现在我还想创建一个后台服务/任务等。我知道 AlarmManager。我想知道什么应该与 AlarmManager 结合使用来触发 AsyncTask。我担心这个问题的原因是我的 AsyncTask 也在更新 UI。但是,如果任何后台服务调用 AsyncTask,则前台没有 UI,因为应用程序当前未运行。会导致崩溃吗?
更新 在我的主要 Activity 中,我调用此方法来启动我的警报管理器
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);
}
Intent 服务实现
@Override
protected void onHandleIntent(Intent intent) {
// Do the task here
Log.i("MyTestService", "Service running");
}
我对如何启动异步任务感到困惑。由于我的异步任务依赖于共享首选项以及从 gms 等接收到的位置。请指导我走正确的道路。
最佳答案
因为没有 UI,将你的 Asynctask
放在 Service
中,然后将你的数据存储在 SQLite
中,这样当你打开app >> 你只需要从数据库中获取它。
这是一个示例流程
- 警报管理器将通知服务执行异步任务
- Asynctask 将从服务器或您的 API 收集信息
- 收集的信息/数据应存储在 SQL 中
- 打开 App 时,首先向数据库查询数据并更新 UI。
- 执行常规应用程序
关于android - 具有 Intent 服务的 AsyncTask(带 AlarmManager),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31094058/