由于这是我见过的唯一一个与此问题相关的问题,因此这里有 > 年迟到的答案。由于android系统自动同步我的自定义帐户,我还遇到了永久唤醒锁定问题。
处理此问题的最佳方法,它需要最少的代码,并且实际上使帐户永远不会同步,除非专门调用以在代码中同步:
ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0);
现在这要求您在创建帐户时调用此静态方法。而第一个参数是设置此设置的帐户,第二个参数是使用的内容提供者的权限,第三个是整数,当设置为正数时启用同步,设置为 0 时禁用同步,设置为其他任何值让它不为人知。要使用的权限可以在您的 SyncAdapter 使用的 contentAuthority 属性下的“sync_something.xml”中找到:
<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
android:contentAuthority="com.android.contacts"
android:accountType="com.myapp.account"/> <!-- This being your own account type-->
上面的 xml 文件是在你的 AndroidManifest.xml 的服务部分中指定的:
<service android:name=".DummySyncAdapterService"
exported="true"
android:process=":contacts">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data android:name="android.content.SyncAdapter"
android:resource="@xml/sync_something" /> <!--This points to your SyncAdapter XML-->
</service>
这是我用来在我的 LoginActivity 中创建自定义帐户的代码 sn-p:
Account account = new Account("John Doe", "com.myapp.account");
ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0);
AccountManager am = AccountManager.get(LoginActivity.this);
boolean accountCreated = am.addAccountExplicitly(account, "Password", null);
Bundle extras = LoginActivity.this.getIntent().getExtras();
if(extras != null){
if (accountCreated) {
AccountAuthenticatorResponse response = extras.getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, "John Doe");
result.putString(AccountManager.KEY_ACCOUNT_TYPE, "com.myapp.account");
response.onResult(result);
}
}
这很重要的是,当系统尝试同步服务时,它会首先检查服务是否可同步,如果设置为 false,则会取消同步。现在您不必创建自己的ContentProvider,您的ContentProvider 也不会显示在数据和同步下。 但是,您确实需要有一个 AbstractThreadedSyncAdapter 的存根实现,它在其 onBind 方法中返回一个 IBinder。 最后但并非最不重要的一点是,它使用户无法启用同步或使用“立即同步” " 按钮,除非您已在应用中添加了该功能。