1

私のアプリは SyncAdapter を使用して、定期的にサーバー データを SQLite と同期します。また、新しい/更新されたサーバー データを示す GCM メッセージに応答して、このデータを同期します。経由。IntentService。

これらのコンポーネントはそれぞれ、異なるバックグラウンド スレッドで作業を行い、異なるシステム プロセス (SyncManager/GCM ブロードキャスト) によって作成され、異なるライフサイクルを持ちます。予想外!

これらのコンポーネントをフォールトトレラントに調整するための最良のアプローチは何ですか:

  • アクティビティが、作業を行わないことをそれぞれに通知するため
  • GCM IntentService が動作しているときに動作しないように SyncAdapter に通知し、その逆も同様です。
4

1 に答える 1

3

あなたがすべき

  1. すべての同期コードを SyncAdapter に入れます
  2. IntentService を削除します
  3. GcmBroadcastReceiver では、IntentService の代わりに SyncAdapter を開始します。

以下は、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 に答える