Using ContentResolver instead of ContentProviderClient in SyncAdapter

让人想犯罪 __ 提交于 2019-12-05 06:29:23

There is no special limitation on ContentResolver's API when used from the context of SyncAdapter. IMHO, the only reason why the framework passes ContentProviderClient and authority to onPerformSync() is convenience and kind of a hint to developers as to how SyncAdapter intended work.

This fact is easily seen in the source code for AbstractThreadedSyncAdapter.SyncThread - the ContentProviderClient passed to onPerformSync() is obtained in a standard fashion:

    @Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

        // Trace this sync instance.  Note, conceptually this should be in
        // SyncStorageEngine.insertStartSyncEvent(), but the trace functions require unique
        // threads in order to track overlapping operations, so we'll do it here for now.
        Trace.traceBegin(Trace.TRACE_TAG_SYNC_MANAGER, mAuthority);

        SyncResult syncResult = new SyncResult();
        ContentProviderClient provider = null;
        try {
            if (isCanceled()) {
                return;
            }
            provider = mContext.getContentResolver().acquireContentProviderClient(mAuthority);
            if (provider != null) {
                AbstractThreadedSyncAdapter.this.onPerformSync(mAccount, mExtras,
                        mAuthority, provider, syncResult);
            } else {
                syncResult.databaseError = true;
            }
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYNC_MANAGER);

            if (provider != null) {
                provider.release();
            }
            if (!isCanceled()) {
                mSyncContext.onFinished(syncResult);
            }
            // synchronize so that the assignment will be seen by other threads
            // that also synchronize accesses to mSyncThreads
            synchronized (mSyncThreadLock) {
                mSyncThreads.remove(mThreadsKey);
            }
        }
    }

Therefore, the bootom line: you can use ContentResolver in your SyncAdapter as you wish - just call getContext().getContentResolver() and access any exported ContentProvider.

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