[英]SyncAdapter process killed when swiped from recents
我正在尝试创建运行后台操作(没有前台通知)的SyncAdapter。
它正在工作,但触发ContentResolver.requestSync(...)
活动(任务)从最近的应用程序中消失的情况除外。 在这种情况下,进程将被onPerformSync(...)
, onPerformSync(...)
尚未完成。
我知道,这是Android的预期行为,但是在常规Service
我会设置
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_REDELIVER_INTENT;
}
或使用
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
restartSynchronization();
}
重试同步,但是在SyncAdapterService中不起作用。
从最近的应用程序中清除活动后,如何确保同步继续/重试?
先感谢您。
经过一番研究,我发现,仅在startService(...)
时才调用onTaskRemoved(...)
而不是仅在有人绑定到它时才调用。
因此,我通过在onBind(...)
启动服务并在onUnbind(...)
方法中停止该服务及其进程来解决了onUnbind(...)
。
这是最终代码:
public class SyncAdapterService extends Service {
private static final Object sSyncAdapterLock = new Object();
private static MySyncAdapter sSyncAdapter = null;
@Override
public void onCreate() {
super.onCreate();
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new MySyncAdapter(getApplicationContext());
}
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
/*
* Rescheduling sync due to running one is killed on removing from recent applications.
*/
SyncHelper.requestSyncNow(this);
}
@Override
public IBinder onBind(Intent intent) {
/*
* Start service to watch {@link @onTaskRemoved(Intent)}
*/
startService(new Intent(this, SyncAdapterService.class));
return sSyncAdapter.getSyncAdapterBinder();
}
@Override
public boolean onUnbind(Intent intent) {
/*
* No more need watch task removes.
*/
stopSelf();
/*
* Stops current process, it's not necessarily required. Assumes sync process is different
* application one. (<service android:process=":sync" /> for example).
*/
Process.killProcess(Process.myPid());
return super.onUnbind(intent);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.