1

我的应用程序使用 SyncAdapter 定期将服务器数据与 SQLite 同步。它还同步此数据以响应指示新/更新的服务器数据的 GCM 消息;通过。一个意图服务。

这些组件各自在不同的后台线程中工作,由不同的系统进程(SyncManager/GCM 广播)创建,具有不同的生命周期;出乎意料!

容错协调这些组件的最佳方法是什么:例如

  • 让 Activity 向每个人发出信号,表明他们不应该做任何工作
  • 当 GCM IntentService 正在工作时,向 SyncAdapter 发出不做任何工作的信号,反之亦然。
4

1 回答 1

3

你应该

  1. 将所有同步代码放入 SyncAdapter
  2. 删除 IntentService
  3. 在 GcmBroadcastReceiver 中,您启动 SyncAdapter 而不是 IntentService。

下面是从SyncAdapter 文档中复制的示例代码。

public class GcmBroadcastReceiver extends BroadcastReceiver {
    ...
    // Constants
    // Content provider authority
    public static final String AUTHORITY = "com.example.android.datasync.provider"
    // Account type
    public static final String ACCOUNT_TYPE = "com.example.android.datasync";
    // Account
    public static final String ACCOUNT = "default_account";
    // Incoming Intent key for extended data
    public static final String KEY_SYNC_REQUEST =
        "com.example.android.datasync.KEY_SYNC_REQUEST";
    ...
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get a GCM object instance
        GoogleCloudMessaging gcm =
            GoogleCloudMessaging.getInstance(context);
            // Get the type of GCM message
        String messageType = gcm.getMessageType(intent);
        /*
         * Test the message type and examine the message contents.
         * Since GCM is a general-purpose messaging system, you
         * may receive normal messages that don't require a sync
         * adapter run.
         * The following code tests for a a boolean flag indicating
         * that the message is requesting a transfer from the device.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)
            &&
            intent.getBooleanExtra(KEY_SYNC_REQUEST)) {
            /*
             * Signal the framework to run your sync adapter. Assume that
             * app initialization has already created the account.
             */
            ContentResolver.requestSync(ACCOUNT, AUTHORITY, null);
            ...
        }
        ...
    }
    ...
}
于 2014-06-27T02:00:01.017 回答