下面列出了怎么用android.content.ContentProviderClient的API类实例代码及写法,或者点击链接到github查看源代码。
public static boolean uncompressDocument(ContentResolver resolver, Uri fromDocumentUri) {
final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
fromDocumentUri.getAuthority());
try {
final Bundle in = new Bundle();
in.putString(Document.COLUMN_DOCUMENT_ID, getDocumentId(fromDocumentUri));
in.putParcelable(DocumentsContract.EXTRA_URI, fromDocumentUri);
resolver.call(fromDocumentUri, METHOD_UNCOMPRESS_DOCUMENT, null, in);
return true;
} catch (Exception e) {
Log.w(TAG, "Failed to uncompress document", e);
return false;
} finally {
ContentProviderClientCompat.releaseQuietly(client);
}
}
/**
* Return thumbnail representing the document at the given URI. Callers are
* responsible for their own in-memory caching.
*
* @param documentUri document to return thumbnail for, which must have
* {@link Document#FLAG_SUPPORTS_THUMBNAIL} set.
* @param size optimal thumbnail size desired. A provider may return a
* thumbnail of a different size, but never more than double the
* requested size.
* @param signal signal used to indicate if caller is no longer interested
* in the thumbnail.
* @return decoded thumbnail, or {@code null} if problem was encountered.
* @see DocumentsProvider#openDocumentThumbnail(String, Point,
* android.os.CancellationSignal)
*/
public static Bitmap getDocumentThumbnail(
ContentResolver resolver, Uri documentUri, Point size, CancellationSignal signal)
throws FileNotFoundException {
final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
documentUri.getAuthority());
try {
return getDocumentThumbnail(client, documentUri, size, signal);
} catch (Exception e) {
if (!(e instanceof OperationCanceledException)) {
Log.w(TAG, "Failed to load thumbnail for " + documentUri + ": " + e);
}
rethrowIfNecessary(resolver, e);
return null;
} finally {
ContentProviderClient.releaseQuietly(client);
}
}
/**
* 调用插件里的Provider
*
* @see android.content.ContentProviderClient#update(Uri, ContentValues, String, String[])
*/
public static int update(Context c, Uri uri, ContentValues values, String selection, String[] selectionArgs) {
ContentProviderClient client = PluginProviderClient.acquireContentProviderClient(c, "");
if (client != null) {
try {
Uri toUri = toCalledUri(c, uri);
return client.update(toUri, values, selection, selectionArgs);
} catch (RemoteException e) {
if (LogDebug.LOG) {
Log.d(TAG, e.toString());
}
}
}
if (LogDebug.LOG) {
Log.d(TAG, String.format("call update %s", uri.toString()));
}
return -1;
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
if (!DelayedSyncController.getInstance().shouldPerformSync(getContext(), extras, account)) {
return;
}
// Browser startup is asynchronous, so we will need to wait for startup to finish.
Semaphore semaphore = new Semaphore(0);
// Configure the callback with all the data it needs.
BrowserStartupController.StartupCallback callback =
getStartupCallback(mApplication, account, extras, syncResult, semaphore);
startBrowserProcess(callback, syncResult, semaphore);
try {
// Wait for startup to complete.
semaphore.acquire();
} catch (InterruptedException e) {
Log.w(TAG, "Got InterruptedException when trying to request a sync.", e);
// Using numIoExceptions so Android will treat this as a soft error.
syncResult.stats.numIoExceptions++;
}
}
/**
* Removes the given document from a parent directory.
*
* <p>In contrast to {@link #deleteDocument} it requires specifying the parent.
* This method is especially useful if the document can be in multiple parents.
*
* @param documentUri document with {@link Document#FLAG_SUPPORTS_REMOVE}
* @param parentDocumentUri parent document of the document to remove.
* @return true if the document was removed successfully.
*/
public static boolean removeDocument(ContentResolver resolver, Uri documentUri,
Uri parentDocumentUri) throws FileNotFoundException {
final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
documentUri.getAuthority());
try {
removeDocument(client, documentUri, parentDocumentUri);
return true;
} catch (Exception e) {
Log.w(TAG, "Failed to remove document", e);
rethrowIfNecessary(resolver, e);
return false;
} finally {
ContentProviderClient.releaseQuietly(client);
}
}
/**
* Return the given site's download directory. Create it if it doesn't exist.
*
* @param context Context to use for the action
* @param site Site to get the download directory for
* @return Download directory of the given Site
*/
@Nullable
static DocumentFile getOrCreateSiteDownloadDir(@NonNull Context context, @Nullable ContentProviderClient client, @NonNull Site site) {
String appUriStr = Preferences.getStorageUri();
if (appUriStr.isEmpty()) {
Timber.e("No storage URI defined for the app");
return null;
}
DocumentFile appFolder = DocumentFile.fromTreeUri(context, Uri.parse(appUriStr));
if (null == appFolder || !appFolder.exists()) {
Timber.e("App folder %s does not exist", appUriStr);
return null;
}
String siteFolderName = site.getFolder();
DocumentFile siteFolder;
if (null == client)
siteFolder = FileHelper.findFolder(context, appFolder, siteFolderName);
else
siteFolder = FileHelper.findFolder(context, appFolder, client, siteFolderName);
if (null == siteFolder) // Create
return appFolder.createDirectory(siteFolderName);
else return siteFolder;
}
@Override
@SuppressWarnings("ConstantConditions")
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult result) {
final boolean manual = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL);
final Map<String, Long> synced = syncer.sync(provider, manual);
if (synced.containsKey(RESULT_ERROR)) {
final long error = synced.get(RESULT_ERROR);
if (error == ERROR_DB) {
result.databaseError = true;
} else if (error == ERROR_IO) {
result.stats.numIoExceptions++;
}
return;
}
if (synced.containsKey(RESULT_INSERTS) && synced.containsKey(RESULT_DELETES)) {
result.stats.numInserts = synced.get(RESULT_INSERTS);
result.stats.numDeletes = synced.get(RESULT_DELETES);
}
if (synced.containsKey(RESULT_DELAY_UNTIL)) {
result.delayUntil = synced.get(RESULT_DELAY_UNTIL);
}
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
Logger.d(TAG, "onPerformSync: account: " + account.name);
try {
// Check if internet is available. If not then don't perform any sync.
if (!NetworkConnectionUtil.isNetworkAvailable(getContext())) {
return;
}
// Get the auth token for the current account.
String authToken = mAccountManager.blockingGetAuthToken(account,
PredatorSharedPreferences.getAuthTokenType(getContext().getApplicationContext()),
true);
// Fetch latest posts.
mPostsPresenter.getPosts(authToken,
mPostsPresenter.getSortType(getContext()),
true);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected Uri doInBackground(Void... params) {
final ContentResolver resolver = mActivity.getContentResolver();
ContentProviderClient client = null;
Uri childUri = null;
try {
client = DocumentsApplication.acquireUnstableProviderOrThrow(
resolver, mCwd.derivedUri.getAuthority());
childUri = DocumentsContract.createDocument(
resolver, mCwd.derivedUri, mMimeType, mDisplayName);
} catch (Exception e) {
Log.w(DocumentsActivity.TAG, "Failed to create document", e);
Crashlytics.logException(e);
} finally {
ContentProviderClientCompat.releaseQuietly(client);
}
return childUri;
}
/**
* Queries a content provider for word list data for some locale and stage the returned files
*
* This will query a content provider for word list data for a given locale, and copy the
* files locally so that they can be mmap'ed. This may overwrite previously cached word lists
* with newer versions if a newer version is made available by the content provider.
* @throw FileNotFoundException if the provider returns non-existent data.
* @throw IOException if the provider-returned data could not be read.
*/
public static void installDictToStagingFromContentProvider(final Locale locale,
final Context context, final boolean hasDefaultWordList) {
final ContentProviderClient providerClient;
try {
providerClient = context.getContentResolver().
acquireContentProviderClient(getProviderUriBuilder("").build());
} catch (final SecurityException e) {
Log.e(TAG, "No permission to communicate with the dictionary provider", e);
return;
}
if (null == providerClient) {
Log.e(TAG, "Can't establish communication with the dictionary provider");
return;
}
try {
final List<WordListInfo> idList = getWordListWordListInfos(locale, context,
hasDefaultWordList);
for (WordListInfo id : idList) {
installWordListToStaging(id.mId, id.mLocale, id.mRawChecksum, providerClient,
context);
}
} finally {
providerClient.release();
}
}
@Override
protected Uri doInBackground(Void... params) {
final ContentResolver resolver = getContentResolver();
final DocumentInfo cwd = getCurrentDirectory();
ContentProviderClient client = null;
Uri childUri = null;
try {
client = DocumentsApplication.acquireUnstableProviderOrThrow(
resolver, cwd.derivedUri.getAuthority());
childUri = DocumentsContract.createDocument(
resolver, cwd.derivedUri, mMimeType, mDisplayName);
} catch (Exception e) {
Log.w(TAG, "Failed to create document", e);
Crashlytics.logException(e);
} finally {
ContentProviderClientCompat.releaseQuietly(client);
}
if (childUri != null) {
saveStackBlocking();
}
return childUri;
}
private boolean renameFolder(@NonNull DocumentFile folder, @NonNull final Content content, @NonNull ContentProviderClient client, @NonNull final String newName) {
try {
if (folder.renameTo(newName)) {
// 1- Update the book folder's URI
content.setStorageUri(folder.getUri().toString());
// 2- Update the JSON's URI
DocumentFile jsonFile = FileHelper.findFile(this, folder, client, Consts.JSON_FILE_NAME_V2);
if (jsonFile != null) content.setJsonUri(jsonFile.getUri().toString());
// 3- Update the image's URIs -> will be done by the next block back in startImport
return true;
}
} catch (Exception e) {
Timber.e(e);
}
return false;
}
@Override
protected Uri doInBackground(Void... params) {
final ContentResolver resolver = getContentResolver();
final DocumentInfo cwd = getCurrentDirectory();
ContentProviderClient client = null;
Uri childUri = null;
try {
client = DocumentsApplication.acquireUnstableProviderOrThrow(
resolver, cwd.derivedUri.getAuthority());
childUri = DocumentsContract.createDocument(
resolver, cwd.derivedUri, mMimeType, mDisplayName);
} catch (Exception e) {
Log.w(TAG, "Failed to create document", e);
CrashReportingManager.logException(e);
} finally {
ContentProviderClientCompat.releaseQuietly(client);
}
if (childUri != null) {
saveStackBlocking();
}
return childUri;
}
@Override
protected Uri doInBackground(Void... params) {
final ContentResolver resolver = mActivity.getContentResolver();
ContentProviderClient client = null;
Uri childUri = null;
try {
client = DocumentsApplication.acquireUnstableProviderOrThrow(
resolver, mCwd.derivedUri.getAuthority());
childUri = DocumentsContract.createDocument(
resolver, mCwd.derivedUri, mMimeType, mDisplayName);
} catch (Exception e) {
Log.w(DocumentsActivity.TAG, "Failed to create document", e);
CrashReportingManager.logException(e);
} finally {
ContentProviderClientCompat.releaseQuietly(client);
}
return childUri;
}
@Override
protected DocumentInfo doInBackground(Void... params) {
final ContentResolver resolver = mActivity.getContentResolver();
ContentProviderClient client = null;
try {
client = DocumentsApplication.acquireUnstableProviderOrThrow(resolver, mCwd.derivedUri.getAuthority());
final Uri childUri = DocumentsContract.createDocument(
resolver, mCwd.derivedUri, Document.MIME_TYPE_DIR, mDisplayName);
return DocumentInfo.fromUri(resolver, childUri);
} catch (Exception e) {
Log.w(TAG, "Failed to create directory", e);
CrashReportingManager.logException(e);
return null;
} finally {
ContentProviderClientCompat.releaseQuietly(client);
}
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
String authToken = extras.getString(EXTRA_AUTH_TOKEN);
if (TextUtils.isEmpty(authToken)) {
Log.d(TAG, "Not authorized. Cannot sync.");
return;
}
mApiClient.blockingConnect(5, TimeUnit.SECONDS);
try {
String cookie = getCookie(authToken);
syncCheckins(provider, cookie);
if (!extras.getBoolean(EXTRA_ONLY_CHECKINS, false)) {
syncEvents(provider, cookie);
}
} catch (IOException e) {
Log.e(TAG, "Error performing sync.", e);
}
}
@Override
protected Uri doInBackground(Void... params) {
final ContentResolver resolver = getContentResolver();
final DocumentInfo cwd = getCurrentDirectory();
ContentProviderClient client = null;
Uri childUri = null;
try {
client = DocumentsApplication.acquireUnstableProviderOrThrow(
resolver, cwd.derivedUri.getAuthority());
childUri = DocumentsContract.createDocument(
resolver, cwd.derivedUri, mMimeType, mDisplayName);
} catch (Exception e) {
Log.w(TAG, "Failed to create document", e);
Crashlytics.logException(e);
} finally {
ContentProviderClientCompat.releaseQuietly(client);
}
if (childUri != null) {
saveStackBlocking();
}
return childUri;
}
private void handleSendUnpinned() {
try (ContentProviderClient client = getClient()) {
if (client == null) return;
Bundle b = new Bundle();
b.putParcelable(SliceProvider.EXTRA_BIND_URI, mUri);
try {
client.call(SliceProvider.METHOD_UNPIN, null, b);
} catch (RemoteException e) {
Log.w(TAG, "Unable to contact " + mUri, e);
}
}
}
public static void updateRoots(Context context, String authority){
final ContentProviderClient client =
ContentProviderClientCompat.acquireUnstableContentProviderClient(
context.getContentResolver(), authority);
try {
((DocumentsProvider) client.getLocalContentProvider()).updateRoots();
} finally {
ContentProviderClientCompat.releaseQuietly(client);
}
}
public static void removeDocument(ContentProviderClient client, Uri documentUri,
Uri parentDocumentUri) throws RemoteException {
final Bundle in = new Bundle();
in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
in.putParcelable(DocumentsContract.EXTRA_PARENT_URI, parentDocumentUri);
client.call(METHOD_REMOVE_DOCUMENT, null, in);
}
@Override
protected Bitmap doInBackground(Uri... params) {
if (isCancelled())
return null;
final Context context = mIconThumb.getContext();
final ContentResolver resolver = context.getContentResolver();
ContentProviderClient client = null;
Bitmap result = null;
try {
if (Utils.isAPK(mMimeType)) {
result = ((BitmapDrawable) IconUtils.loadPackagePathIcon(context, mPath, Document.MIME_TYPE_APK)).getBitmap();
} else {
client = DocumentsApplication.acquireUnstableProviderOrThrow(resolver, mUri.getAuthority());
result = DocumentsContract.getDocumentThumbnail(resolver, mUri, mThumbSize, mSignal);
}
if (null == result){
result = ImageUtils.getThumbnail(mPath, mMimeType, mThumbSize.x, mThumbSize.y);
}
if (result != null) {
final ThumbnailCache thumbs = DocumentsApplication.getThumbnailsCache(context, mThumbSize);
thumbs.put(mUri, result);
}
} catch (Exception e) {
if (!(e instanceof OperationCanceledException)) {
Log.w(TAG, "Failed to load thumbnail for " + mUri + ": " + e);
}
Crashlytics.logException(e);
} finally {
ContentProviderClientCompat.releaseQuietly(client);
}
return result;
}
/**
* Initialize a client record with the dictionary content provider.
*
* This merely acquires the content provider and calls
* #reinitializeClientRecordInDictionaryContentProvider.
*
* @param context the context for resources and providers.
* @param clientId the client ID to use.
*/
public static void initializeClientRecordHelper(final Context context, final String clientId) {
try {
final ContentProviderClient client = context.getContentResolver().
acquireContentProviderClient(getProviderUriBuilder("").build());
if (null == client) return;
reinitializeClientRecordInDictionaryContentProvider(context, client, clientId);
} catch (RemoteException e) {
Log.e(TAG, "Cannot contact the dictionary content provider", e);
}
}
public static void releaseQuietly(ContentProviderClient client) {
if (client != null) {
try {
if (VERSION.SDK_INT >= Build.VERSION_CODES.N) {
client.close();
} else {
client.release();
}
} catch (Exception ignored) {
}
}
}
/** {@hide} */
public static Uri renameDocument(ContentProviderClient client, Uri documentUri,
String displayName) throws RemoteException {
final Bundle in = new Bundle();
in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
in.putString(Document.COLUMN_DISPLAY_NAME, displayName);
final Bundle out = client.call(METHOD_RENAME_DOCUMENT, null, in);
final Uri outUri = out.getParcelable(DocumentsContract.EXTRA_URI);
return (outUri != null) ? outUri : documentUri;
}
/** {@hide} */
public static void deleteDocument(ContentProviderClient client, Uri documentUri)
throws RemoteException {
final Bundle in = new Bundle();
in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
client.call(METHOD_DELETE_DOCUMENT, null, in);
}
/**
* Copies the given document.
*
* @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_COPY}
* @param targetParentDocumentUri document which will become a parent of the source
* document's copy.
* @return the copied document, or {@code null} if failed.
*/
public static Uri copyDocument(ContentResolver resolver, Uri sourceDocumentUri,
Uri targetParentDocumentUri) throws FileNotFoundException {
final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
sourceDocumentUri.getAuthority());
try {
return copyDocument(client, sourceDocumentUri, targetParentDocumentUri);
} catch (Exception e) {
Log.w(TAG, "Failed to copy document", e);
rethrowIfNecessary(resolver, e);
return null;
} finally {
ContentProviderClient.releaseQuietly(client);
}
}
@Override
public String getType(Uri uri) {
String targetAuthority = uri.getQueryParameter(Env.EXTRA_TARGET_AUTHORITY);
if (!TextUtils.isEmpty(targetAuthority) && !TextUtils.equals(targetAuthority, uri.getAuthority())) {
ContentProviderClient client = getContentProviderClient(targetAuthority);
try {
return client.getType(buildNewUri(uri, targetAuthority));
} catch (RemoteException e) {
handleExpcetion(e);
}
}
return null;
}
public static <T> void delete(Context context, ContentProviderClient provider, T dataModelObject) throws RemoteException {
TableDetails tableDetails = QuantumFlux.findTableDetails(dataModelObject.getClass());
Object columnValue = ModelInflater.deflateColumn(tableDetails, tableDetails.findPrimaryKeyColumn(), dataModelObject);
Uri itemUri = UriMatcherHelper.generateItemUriBuilder(tableDetails, String.valueOf(columnValue))
.appendQueryParameter(QuantumFluxContentProvider.PARAMETER_SYNC, "false").build();
provider.delete(itemUri, null, null);
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
String targetAuthority = uri.getQueryParameter(Env.EXTRA_TARGET_AUTHORITY);
if (!TextUtils.isEmpty(targetAuthority) && !TextUtils.equals(targetAuthority, uri.getAuthority())) {
ContentProviderClient client = getContentProviderClient(targetAuthority);
try {
return client.update(buildNewUri(uri, targetAuthority), values, selection, selectionArgs);
} catch (RemoteException e) {
handleExpcetion(e);
}
}
return 0;
}
/**
* Ejects the given root. It throws {@link IllegalStateException} when ejection failed.
*
* @param rootUri root with {@link Root#FLAG_SUPPORTS_EJECT} to be ejected
*/
public static void ejectRoot(ContentResolver resolver, Uri rootUri) {
final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
rootUri.getAuthority());
try {
ejectRoot(client, rootUri);
} catch (RemoteException e) {
e.rethrowAsRuntimeException();
} finally {
ContentProviderClient.releaseQuietly(client);
}
}