我的应用使用SyncAdapter定期与SQLite同步服务器数据。它还同步这些数据以响应指示新的/更新的服务器数据的GCM消息;通过。一个IntentService。
这些组件各自在不同的后台线程中工作,由不同的系统进程(SyncManager / GCM广播)创建,并具有不同的生命周期;不可预知的!
我正在请求关于如何最好地容错地协调/控制这些组件的想法,例如,一个活动向两者表明他们不应该做任何工作;例如:当GCM IntentService工作时,发信号通知SyncAdapter不起作用。
答案 0 :(得分:3)
你应该
以下是从SyncAdapter documentation复制的示例代码。
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);
...
}
...
}
...
}