我正在尝试创建SyncAdapter运行后台操作(没有前台通知)。
它正在工作,除了触发ContentResolver.requestSync(...)
的活动(任务)从最近的应用程序中删除的情况。在这种情况下,进程被杀死,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中不起作用。
我如何确保同步继续/重试活动从最近的应用程序滑走后?
提前感谢。
经过一些研究,我发现,onTaskRemoved(...)
只在startService(...)
被调用时才被调用,而不是当有人只绑定它时才被调用。
所以我确实通过在onBind(...)
中启动服务并在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);
}
}