我正在尝试使用BroadcastReceiver在数据库服务器发生更改时触发SyncAdapter(使用GCM)。
当告知接收方开始同步过程时,我收到以下错误
ContentResolver.requestSync(accounts[0], AUTHORITY, null);
这就是我的BroadcastReceiver的样子
public class GcmBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "GcmBroadcastReceiver";
public static final String AUTHORITY = TournamentContract.CONTENT_AUTHORITY;
public static final String ACCOUNT_TYPE = TournamentContract.CONTENT_AUTHORITY;
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";
public static final String MESSAGE_TYPE = "gcm";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive: here");
// 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 (MESSAGE_TYPE.equals(messageType) && intent.getBooleanExtra(KEY_SYNC_REQUEST, true)) {
AccountManager am = AccountManager.get(context);
Account[] accounts = am.getAccountsByType(ACCOUNT_TYPE);
if (accounts.length == 0) {
// todo create account if not already there
}
/*
* Signal the framework to run your sync adapter. Assume that
* app initialization has already created the account.
*/
ContentResolver.requestSync(accounts[0], AUTHORITY, null);
}
}
}
我确信我的SyncAdapter工作正常,因为我没有发现周期性同步存在任何问题。
您认为我如何解决这个问题?
提前谢谢! :d
答案 0 :(得分:4)
你没有发布实际的错误,所以很难说其他什么可能是错的,但肯定有一件事是错的:
requestSync(Account, String, Bundle)
的extras
参数不得为null
。
如果您查看来源,则会明确检查extras
的{{1}}值。
null
因此,如果public static void requestSync(Account account, String authority, Bundle extras) {
requestSyncAsUser(account, authority, UserHandle.myUserId(), extras);
}
public static void requestSyncAsUser(Account account, String authority, int userId,
Bundle extras) {
if (extras == null) {
throw new IllegalArgumentException("Must specify extras.");
}
requestSync
为requestSyncAsUser
,您可以看到IllegalArgumentException
来电extras
会引发Bundle
。
如果你没有任何额外的东西要通过,你应该通过Bundle.EMPTY
,如下:
null