Android应用程序关闭/设置为后台时如何执行后台任务? [英] How to execute background task when Android app is closed / set to background?
问题描述
我的Android 4+应用程序已连接到自定义Web服务,该服务每隔几分钟便用于同步数据.为了确保在线数据始终是最新的,我想在应用关闭或发送到后台时触发同步.
My Android 4+ app is connected to a custom web service that is used to sync data every few minutes. To make sure, that the online data is always up to date, I want to trigger the sync when ever the app is closed / send to background.
在iOS下,这非常简单:
Under iOS this is quite easy:
- 在AppDelegate中收听
applicationDidEnterBackground:
- 使用
beginBackgroundTaskWithName:
启动您长期运行的后台任务,并避免在任务仍在运行时被暂停
- Listen to
applicationDidEnterBackground:
in the AppDelegate - Use
beginBackgroundTaskWithName:
to start you long running background task and to avoid being suspended while the task is still running
如何在Android上执行此操作?
第一个问题是,没有什么等同于applicationDidEnterBackground:
.到目前为止,我发现的所有解决方案都建议使用主要的Activity onPause()
方法.但是,这会在主Activity
暂停的任何时间调用,这在应用程序中启动另一个Activity
时也是如此.对于ActivityLifecycleCallbacks
界面中的onActivityPaused()
方法,它是正确的.
First problem is, that there is nothing equivalent to applicationDidEnterBackground:
. All solution I found so far propose to use the main Activities onPause()
method. However this called any time the main Activity
is paused, which is also the case when another Activity
is started within the app. The is true for the onActivityPaused()
method from ActivityLifecycleCallbacks
interface.
那么,如何检测 app (不仅仅是Activity
)已关闭或发送到后台?
So, how to detect that the app (not just an Activity
) is closed or send to the background?
第二个问题是,我没有找到有关如何运行后台任务的任何信息.所有解决方案都指向仅启动AsyncTask
,但这真的是正确的解决方案吗?
Second problem is, that I did not find any information on how to run background task. All solutions point to simply start an AsyncTask
, but is this really the correct solution?
AsyncTask
将启动一个新任务,但是当应用程序关闭/处于非活动状态时,此任务也将运行吗?为了防止应用程序和任务在几秒钟后挂起,我该怎么办?我如何确保在应用程序完全挂起之前可以完成任务?
AsyncTask
will start a new task, but will this task also run, when the app is closed/inactive? What do I have to do, to prevent the app and the task from being suspended after a few seconds? How can I make sure, that the task can complete, before the app is completely suspended?
推荐答案
以下代码将帮助您在应用关闭或在后台运行时发布内容:
The following code will help you to post your contents when your app is closed or in the background:
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class SendDataService extends Service {
private final LocalBinder mBinder = new LocalBinder();
protected Handler handler;
protected Toast mToast;
public class LocalBinder extends Binder {
public SendDataService getService() {
return SendDataService .this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
// write your code to post content on server
}
});
return android.app.Service.START_STICKY;
}
}
我的代码的更多解释是:
More explanation of my code is:
即使您的应用程序在后台运行,服务也会在后台运行,但是请记住,该服务始终在主线程上运行,因此,我创建了一个单独的线程来执行后台操作.
Service runs in the background even if your application is in the background, but remember, it always runs on the main thread, because of which I created a separate thread to perform your background operations.
服务是作为粘性服务启动的,即使由于某种原因您的服务在后台被破坏,它也会自动重新启动.
Service is started as a sticky one, as even if because of any reason your service got destroyed in the background it will automatically get restarted.
更多详细信息可以在这里找到: https://developer.android.com/guide/components/services.html
More details can be found here: https://developer.android.com/guide/components/services.html
要检查您的应用是否在前台/后台,以下代码将有所帮助:
And to check if your app is in the foreground/background, the following code will help:
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
// Use like this:
boolean foregroud = new ForegroundCheckTask().execute(context).get();
快乐编码!!!
这篇关于Android应用程序关闭/设置为后台时如何执行后台任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!