Android:ContentResolver.requestSync()没有触发onPerformSync()

标签 android android-contentprovider android-contentresolver android-syncadapter

我正在创建一个 Android 应用程序,它向用户提供一个刷新数据库的按钮,以便本地数据和服务器上的数据保持同步。

我已经创建了帐户验证器、内容提供商并通过服务绑定(bind)了它们。 ContentResolver.requestSync() 未触发 onPerformSync()。

这是我得到的代码:

public void refreshButton(View view) {
    Log.v("aye", "reached here");
    Bundle settings = new Bundle();
    settings.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL,true);
    settings.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    Account dummyAccount = createDummyAccount(this);

    ContentResolver.requestSync(dummyAccount,MyContract.AUTHORITY,settings);
}

private Account createDummyAccount(Context context) {

    Account dummyAccount = new Account("dummyaccount","com.example.sid.fetchdata");
    AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);
    try {
        accountManager.addAccountExplicitly(dummyAccount, null, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    ContentResolver.setSyncAutomatically(dummyAccount, MyContract.AUTHORITY, true);
    ContentResolver.setIsSyncable(dummyAccount,MyContract.AUTHORITY,1);
    return dummyAccount;
}

我正在使用一个虚拟帐户,并根据 Android 开发人员指南创建了一个 stub 帐户身份验证器。

这是我的 SyncAdapter 类的样子:

public class MySyncAdapter extends AbstractThreadedSyncAdapter {

private ContentResolver contentResolver;

public MySyncAdapter(Context context,boolean autoInitialize) {
    super(context,autoInitialize);
    contentResolver = context.getContentResolver();
}

public MySyncAdapter(Context context,boolean autoInitialize,boolean allowParallelSyncs) {
    super(context,autoInitialize,allowParallelSyncs);
    contentResolver = context.getContentResolver();
}
@Override
public void onPerformSync(Account account,Bundle extras,String authority,ContentProviderClient providerClient,SyncResult syncResult) {
    // android.os.Debug.waitForDebugger();
    // Log.e("first","Sync Started");
    GetData getData = new GetData(getContext());
    ContentValues[] questionsContentValues = getData.getAndParseDataContentValues();

    try {
        Log.d("inside","Inside");
        int deletedRows = providerClient.delete(MyContract.CONTENT_URI, null, null);
        // int addedRows = contentResolver.bulkInsert(MyContract.CONTENT_URI,questionsContentValues);
        // providerClient.insert(MyContract.CONTENT_URI,questionsContentValues[0]);
        // Log.v("third1","" + addedRows);
        contentResolver.notifyChange(MyContract.CONTENT_URI,null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

以下是我的 AndroidManfiest.xml 的结构:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sid.fetchdata">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_STATS" />



<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <service
        android:name=".RetrieveService"
        android:exported="false" />

    <activity
        android:name=".FetchActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ListActivity"
        android:label="@string/title_activity_list"
        android:parentActivityName=".FetchActivity"
        android:theme="@style/AppTheme.NoActionBar">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.sid.fetchdata.FetchActivity" />
    </activity>
    <activity
        android:name=".SwipeActivity"
        android:label="@string/title_activity_swipe"
        android:parentActivityName=".ListActivity"
        android:theme="@style/AppTheme.NoActionBar">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.sid.fetchdata.ListActivity" />
    </activity>

    <provider
        android:name=".MyContentProvider"
        android:syncable="true"
        android:exported="true"
        android:authorities="com.example.sid.fetchdata.provider" />

    <service
        android:name=".MyService"
        android:enabled="true"
        android:exported="true" >
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator"/>
        </intent-filter>

        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/account_authenticator" />
    </service>

    <service
        android:name=".SyncService"
        android:process=":sync"
        android:exported="true">
        <intent-filter>
            <action android:name="android.content.SyncAdapter"/>
        </intent-filter>

        <meta-data
            android:name="android.content.SyncAdapter"
            android:resource="@xml/my_sync_adapter" />
    </service>
</application>

对应的类是,MyService 绑定(bind)到 MyStubAuthenticator,SyncService 绑定(bind)到 SyncAdapter。

MyStubAuthenticaor 的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<account-authenticator
xmlns:android="http://schemas.android.com/apk/res/android"
android:icon="@mipmap/ic_launcher"
android:smallIcon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:accountType="com.example.sid.fetchdata" />

SyncAdapter 的 xml 文件是:

<?xml version="1.0" encoding="utf-8"?>
<sync-adapter
xmlns:android="http://schemas.android.com/apk/res/android"
android:isAlwaysSyncable="true"
android:allowParallelSyncs="false"
android:supportsUploading="false"
android:userVisible="true"
android:accountType="com.example.sid.fetchdata"
android:contentAuthority="com.example.sid.fetchdata.provider" />

Provider 的合约类如下:

public class MyContract {

public static final String AUTHORITY = "com.example.sid.fetchdata.provider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + QuestionDataBaseHelper.TABLE_QUESTIONS);

public static final int QUESTIONS = 1;
public static final int QUESTIONS_ID = 2;

public static final String SINGLE_RECORD_MIME_TYPE = "vnd.android.cursor.item/vnd.com.example.sid.fetchdata.provider.questions";
public static final String MULTIPLE_RECORDS_MIME_TYPE = "vnd.android.cursor.dir/vnd.com.example.sid.fetchdata.provider.questions";

}

我已经通过在单独的线程上使用 ContentProvider 来检查它是否正常工作。该帐户显示在手机“设置”选项的“帐户”部分中。同步卡在“正在同步”...

最佳答案

问题终于解决了。问题出在 onPerformSync() 函数上。该函数是由 requestSync() 触发的,但是

contentResolver.notifyChange(MyContract.CONTENT_URI,null);

就是问题所在。 Docs 中给出的函数告诉最后一个参数syncToNetwork 确定更改是否同步到网络。由于我没有将其传递为 false,因此触发了无限循环,因此同步需要无限的时间才能完成。

所以正确的调用是,

contentResolver.notifyChange(MyContract.CONTENT_URI,null,false);

关于Android:ContentResolver.requestSync()没有触发onPerformSync(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35098957/

相关文章:

android - startIntentSenderForResult 处的 NullPointer,inappbilling V3

以网络为数据源的Android ContentProvider

android - 如何使用 Corona SDK 将分享功能添加到 Android 应用程序?

android - Android Q保存媒体文件未显示在图库中

android - 无法解析内容 ://com. android.alarmclock/alarm 的提供商

android - 权限拒绝 : opening provider Android Studio

c# - (Unity) 使用 BuildPipeline 构建时启用 App Bundle (Google Play) 选项?

java - Firebase 远程配置无法在 OnComplete 中获取控制台值

java - 用两个 ImageView 填充横向模式下的宽度

java - 如何使用位图将图像分享到社交媒体?