[英]How to Keep AsyncTask when user closes app
This is in my main activity: 这是我的主要活动:
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
moveTaskToBack(true);
System.exit(0);
}
I want the AsyncTask
to continue put data in my server in the background after the user closes the app. 我希望
AsyncTask
在用户关闭应用程序后继续在后台将数据放入服务器中。
I want the AsyncTask to continue put data in my server in the background after the user closes the app.
我希望AsyncTask在用户关闭应用程序后继续在后台将数据放入服务器中。
The purpose of AsyncTask
is NOT to perform background tasks that's beyond the scope of an Activity
's lifecycle. AsyncTask
的目的不是执行超出Activity
生命周期范围的后台任务。 When a background thread is assigned from a thread pool, it expects to return it once the task is over. 从线程池中分配后台线程后,它希望在任务结束后将其返回。 ie you cannot use an
AsyncTask
for which the required time is indefinite. 即,您不能使用所需时间不确定的
AsyncTask
。
What you are looking for is Services in Android . 您正在寻找的是Android 服务 。
Why even use AsyncTask if we have services?
如果我们有服务,为什么还要使用AsyncTask?
Well, say for instance you require to download an image/song from an Activity
on click of a Button
or you need to perform a task that would take some time to finish its execution. 好吧,举例来说,您需要单击一个
Button
从Activity
下载图像/歌曲,或者您需要执行需要花费一些时间才能完成其执行的任务。 Performing these tasks from the Main thread(aka UI thread) is a bad approach and would make your app sluggish and eventually can lead to an ANR . 从Main线程(又名UI线程)执行这些任务是一种不好的方法,会使您的应用程序运行缓慢,并最终导致ANR 。 So these tasks are to be processed asynchronously from a separate thread to keep the app butter smooth.
因此,这些任务要从单独的线程异步处理,以保持应用程序平稳运行。
Services is one part of a solution, but note that a service runs on the foreground thread. 服务是解决方案的一部分,但请注意,服务在前台线程上运行。 You would want to run your AsyncTask from the service to ensure that it continues to run on a background thread.
您可能想从服务运行AsyncTask,以确保其继续在后台线程上运行。
Personally, I would recommend against using a service in favor of the JobScheduler or if you need to support devices below API 21, Evernote's JobManager (which is also a bit easier to use). 就个人而言,我会建议不要赞成的使用服务的jobscheduler或者如果你需要支持低于API 21设备,Evernote的的JobManager (这也有点更容易使用)。 These will help you schedule your background operations at appropriate times, to minimize battery use or when the device is idle.
这些将帮助您安排在适当的时间进行后台操作,以最大程度地减少电池消耗或设备空闲时的消耗。 It's important to be a good citizen when using the device's resource.
使用设备资源时,成为好公民很重要。
您必须检查服务或/和IntentServices
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.