将 JobIntentService 绑定到活动 [英] Binding a JobIntentService to a Activity

查看:24
本文介绍了将 JobIntentService 绑定到活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Android 中运行长时间运行的操作.假设任务将运行大约 5-10 分钟.为此,我计划使用 JobIntentService 并将其绑定到 Activity.

I want to run an long running operation in Android. Say the task would run for about 5-10 mins. For this reason I am planning to use a JobIntentService and Bind it to an Activity.

现在我正在使用 AsyncTask,尽管我知道 AsyncTask 不能/不应该用于长时间运行的操作,因此我现在计划更改它.很多时候,当任务运行时,用户最小化应用程序,一段时间后 Android 操作系统关闭/清除 Activity 以释放一些内存.

Right now I am using a AsyncTask, even though I know AsyncTask cannot/should not be used for long running operations hence I am planning to change it now. Many times what happens is while the task is running the user minimizes the app and after sometime the Android OS closes/clears the Activity to free up some memory.

所以我的 AsyncTask 在没有任何目的的情况下一直运行,并在尝试更新该 Activity 中的视图时崩溃.

So my AsyncTask is kept running without any purpose and crashes while trying to update a view in that Activity.

所以我打算使用 JobIntentService .但是,使用 JobIntentService 并将其绑定到 Activity 会减少 Android 操作系统关闭/清除 Activity 的机会吗?还是会遵循同样的流程?

So I am planning to use an JobIntentService . But will using an JobIntentService and Binding it to an Activity will reduce the chances of Android OS closing/clearing the Activity? or still will it follow the same process?

如有任何帮助,我们将不胜感激.

Any Help would be really grateful.

推荐答案

如果你的 Activity 在后台,那么阻止 Android 杀死你的 Activity 听起来不像对我来说是个好主意(甚至是必要的).由于您的 Activity 在后台,它对用户不可见,因此在此期间无需更新 UI.

If your Activity is in the background then blocking Android from killing your Activity doesn't sound like a good idea (and even necessary) to me. Since your Activity is in the background it's not visible to the user and there's no need to update the UI during this time.

相反,您可以执行以下操作:

Instead, you could do the following:

如果 Activity 在前台,那么它可以通过 BroadcastReceiver 从您的 JobIntentService 接收更新,您使用 LocalBroadcastManager 注册/取消注册onResume/onPause 中.

If Activity is in the foreground then it can receive updates from your JobIntentService via BroadcastReceiver that you register/unregister with LocalBroadcastManager in onResume/onPause.

如果 JobIntentService 在您的 Activity 被终止时或在后台您可以将结果保存在某个地方(例如,在 SharedPreferences 中)已完成其工作>) 然后在 ActivityonResume 中,您可以从 SharedPreferences 读取该结果.

IF JobIntentService has completed its work when your Activity was killed or in the background you could persist the result somewhere (for example, in SharedPreferences) and then in onResume of your Activity you could read that result from SharedPreferences.

这篇关于将 JobIntentService 绑定到活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆