Android同步适配器在安卓7.0以上(API > 23)无法触发

4
我需要从我的移动应用程序每1分钟连接一次系统服务器以同步数据。为此,我在我的应用程序中使用了SyncAdapter类。对于具有api <23的手机(直到marshmallow),它可以正常工作。当我在具有api> 23的手机上测试我的应用程序时,同步适配器类不会触发。它仅在我第一次在设备上安装应用程序时触发。
我在我的应用程序中使用以下代码。有人能帮我解决这个问题吗?
public class MyServiceSyncAdapter extends AbstractThreadedSyncAdapter {
    //TODO change this constant SYNC_INTERVAL to change the sync frequency
    public static final int SYNC_INTERVAL               = 20; //60 * 180;       // 60 seconds (1 minute) * 180 = 3 hours
    public static final int SYNC_FLEXTIME               = SYNC_INTERVAL/3;
    private static final int MOVIE_NOTIFICATION_ID      = 3004;
    public static DataBaseConnection mCon;

    public MyServiceSyncAdapter(Context context, boolean autoInitialize) {
        super(context, autoInitialize);
        mCon = new DataBaseConnection(this.getContext());
    }

     @Override
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {

        Log.i("MyServiceSyncAdapter", "onPerformSync");
        //TODO get some data from the internet, api calls, etc.
        //TODO save the data to database, sqlite, couchbase, etc

        try{

            //my code to perform the task

        }catch (Exception e){

        }

    }

   public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
        Account account = getSyncAccount(context);
        String authority = context.getString(R.string.content_authority);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // we can enable inexact timers in our periodic sync
            SyncRequest request = new SyncRequest.Builder()
                    .syncPeriodic(syncInterval, flexTime)
                    .setSyncAdapter(account, authority)
                    .setExtras(new Bundle()).build();
            ContentResolver.requestSync(request);

        } else {
            ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval);
        }
    }

    public static void syncImmediately(Context context) {
        Log.i("MyServiceSyncAdapter", "syncImmediately");
        Bundle bundle = new Bundle();
        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle);
    }


    public static Account getSyncAccount(Context context) {
        AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Get an instance of the Android account manager
        Account newAccount = new Account(context.getString(R.string.app_name), context.getString(R.string.sync_account_type)); // Create the account type and default account

        // If the password doesn't exist, the account doesn't exist
        if (accountManager.getPassword(newAccount) == null) {
            if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
                Log.e("MyServiceSyncAdapter", "getSyncAccount Failed to create new account.");
                return null;
            }
            onAccountCreated(newAccount, context);
        }
        return newAccount;
    }

    private static void onAccountCreated(Account newAccount, Context context) {
        Log.i("MyServiceSyncAdapter", "onAccountCreated");
        MyServiceSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME);
        ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true);
        syncImmediately(context);
    }

    public static void initializeSyncAdapter(Context context) {
        Log.d("MyServiceSyncAdapter", "initializeSyncAdapter");
        getSyncAccount(context);
    }
}
1个回答

4
你确定适配器没有触发,而不仅仅是运行时间非常长吗?根据syncPeriodic的文档:

pollFrequency long: 你希望周期同步之间经过的时间,以秒为单位。最小周期为1小时。

因此,如果你等待足够长的时间,你可能会看到你的周期性同步开始。我计时了一下(慢速日),同步最终确实开始了。

更新
根据这里的演示同步应用程序,我记录了API 23、24和28的onPerformSync()启动时间。下表中的时间已标准化到午夜。所有情况下尝试使用一分钟同步期间。

enter image description here

你可以看到,对于API 23,onPerformSync()大约每分钟运行一次。然而,API 24和API 28似乎会将调用onPerformSync()之间的时间锁定在15分钟左右。早于API 23的API尊重一分钟周期请求。

最近,我没有看到最小的一小时,但我确定过去曾经有过。

根据你的需求,你可能需要考虑其他同步方式。依次看一下WorkManagerJobSchedulerAlarmManager。(如果可以,请使用WorkManager。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接