Android : Sync Adapter not running in some devices

本秂侑毒 提交于 2019-12-07 15:19:01

问题


In my android project i have a sync adapter that will sync data from android device to the server and its working fine, but recently i noticed that the onPerfomSync is not calling in my moto g3 android phone, I don't know whether there is the same problem in any other phones,I have tested it in some other Samsung phones with different android api level,but didn't find any problem there.I have configured the sync when a successful user login found.What will be the reason for this behaviour.Correct me if i am doing anything wrong. Below is my codes.

        private void finishLogin(Intent intent) {
    String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
    String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
    final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));

    if (getIntent().getBooleanExtra(ARG_IS_ADDING_ACCOUNT, false)) {
        String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
        String authtokenType = authTokenType;
        String refreshToken = intent.getStringExtra(KEY_REFRESH_TOKEN);
        Bundle userData = new Bundle();
        userData.putString(KEY_REFRESH_TOKEN, refreshToken);
        accountManager.addAccountExplicitly(account, accountPassword, userData);
        accountManager.setAuthToken(account, authtokenType, authtoken);
        accountManager.setUserData(account,KEY_REFRESH_TOKEN,refreshToken);

        ContentResolver.setMasterSyncAutomatically(true); 
        ContentResolver.setSyncAutomatically(account, "com.myexample.mysampleproject", true);
        configurePeriodicSync(account, SYNC_INTERVAL, SYNC_FLEXTIME);

        try {



        } catch (Exception e) {
            e.printStackTrace();
        }



    } else {
        System.out.println("condition else getIntent().getBooleanExtra(ARG_IS_ADDING_ACCOUNT, false)");
        accountManager.setPassword(account, accountPassword);
    }
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

public void configurePeriodicSync(Account account, int syncInterval, int flexTime) {
    Log.d(TAG, "PERIODC SYNC CONFIGURED");
    Bundle mySyncExtras = new Bundle();
    mySyncExtras.putBoolean("MY_SYNC", true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        System.out.println("if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)");
        SyncRequest request = new SyncRequest.Builder().
                syncPeriodic(syncInterval, flexTime).
                setSyncAdapter(account, "com.myexample.mysampleproject").setExtras(mySyncExtras).build();
        ContentResolver.requestSync(request);
    } else {
        System.out.println("else (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)");
        ContentResolver.addPeriodicSync(account, "com.myexample.mysampleproject", mySyncExtras, syncInterval);
    }

}

SyncService.java :

    public class SyncService extends Service {

    private static SyncAdapter syncAdapter = null;

    private static final Object syncAdapterLock = new Object();

    @Override
    public void onCreate() {
        synchronized (syncAdapterLock) {
            if (syncAdapter == null) {
                syncAdapter = new SyncAdapter(getApplicationContext(), true);
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return syncAdapter.getSyncAdapterBinder();
    }
}

AndroidManifest.xml :

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

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

<application
    android:largeHeap="true"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".view.MainActivity"
        android:configChanges="orientation|screenSize"
        android:theme="@style/AppTheme"
        android:label="@string/app_name" >
    </activity>
    <activity android:name=".view.LoginActivity"
              android:configChanges="orientation|screenSize"
              android:theme="@style/AppTheme"
              android:label="@string/login_label"/>

    ........
    ........

    <provider
            android:name=".db.MyContentProvider"
            android:authorities="com.myexample.mysampleproject"
            android:exported="false"
            android:syncable="true" />
    <service
            android:name=".sync.SyncService"
            android:exported="true">
        <intent-filter>
            <action android:name="android.content.SyncAdapter" />
        </intent-filter>

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

</manifest>

sync_adapter.xml :

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

SyncAdapter.java :

    public class SyncAdapter extends AbstractThreadedSyncAdapter {

    ContentResolver contentResolver;

    Context context;
    String authToken;

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

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
        super(context, autoInitialize, allowParallelSyncs);
        contentResolver = context.getContentResolver();
    }

    @Override
    public void onPerformSync(Account account, final Bundle extras, String authority,
                            ContentProviderClient provider, SyncResult syncResult) {
        try {
            System.out.println("start sync ");
            AccountManager manager = AccountManager.get(context);
            authToken = manager.peekAuthToken(account, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS);
            try {
                if(authToken != null) {
                    if (isOnline()) {
                        // perform sync....

                    } else {
                        Log.d("ATTEMPT SYNC ERROR", "NO NETWORK CONNECTION");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

来源:https://stackoverflow.com/questions/41933786/android-sync-adapter-not-running-in-some-devices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!