【问题标题】:AsyncTask with intent service (w AlarmManager)带有意图服务的 AsyncTask (w AlarmManager)
【发布时间】: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


    【解决方案1】:

    由于没有 UI,请将您的 Asynctask 放在 Service 中,然后将您的数据存储在 SQLite 中,以便在您打开应用程序的那一刻>>您只需要从数据库中获取它。

    这是一个示例流程

    • 警报管理器将告诉服务执行异步任务
    • Asynctask 将从服务器或您的 API 收集信息
    • 收集的信息/数据应存储在 SQL 中
    • 打开应用程序时,首先向数据库询问数据并更新 UI。
    • 做你平常的应用程序

    【讨论】:

    • intent 服务可以访问共享首选项吗?我想我将不得不做出很多改变。我正在考虑或切换到内容提供商。那会是更好的方法吗?因为在上面的流程中,如果数据库有一些数据,即使手动(非意图服务,asynctask)刷新后,应用也会显示过期数据
    • 我不确定您是否真的可以在 IS 中访问首选项,但我认为可以,如果您要使用 SQL,请确保在打开应用程序后清除它们,以便旧数据将被删除,此外您可以在 SQL 中添加 Date 以比较数据是否旧。我希望这清楚:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    相关资源
    最近更新 更多