2

我正在尝试创建 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 中不起作用。

从最近的应用程序中清除活动后,如何确保同步继续/重试?

先感谢您。

4

1 回答 1

0

经过一番研究,我发现,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);
}
}
于 2014-08-01T08:19:29.480 回答