android.content.ContentProviderClient Java Examples

The following examples show how to use android.content.ContentProviderClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DocumentsActivity.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #2
Source File: DocumentsActivity.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: ImportService.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: DocumentsContract.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #5
Source File: DocumentsContract.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #6
Source File: ChromiumSyncAdapter.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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++;
    }
}
 
Example #7
Source File: PluginProviderClient2.java    From springreplugin with Apache License 2.0 6 votes vote down vote up
/**
 * 调用插件里的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;
}
 
Example #8
Source File: CreateFileFragment.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: CreateDirectoryFragment.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@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);
        }
    }
 
Example #10
Source File: DocumentsContract.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #11
Source File: DocumentsActivity.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #12
Source File: BinaryDictionaryFileDumper.java    From Android-Keyboard with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example #13
Source File: ContentHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #14
Source File: CreateFileFragment.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #15
Source File: PredatorSyncAdapter.java    From Capstone-Project with MIT License 6 votes vote down vote up
@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();
    }
}
 
Example #16
Source File: SyncAdapter.java    From attendee-checkin with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #17
Source File: EarthsSyncAdapter.java    From earth with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #18
Source File: IconHelper.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
@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 {
        client = DocumentsApplication.acquireUnstableProviderOrThrow(resolver, mUri.getAuthority());
        result = DocumentsContract.getDocumentThumbnail(resolver, mUri, mThumbSize, mSignal);

        if (null == result){
            result = ImageUtils.getThumbnail(mPath, mimeType, 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);
        }
        CrashReportingManager.logException(e);
    } finally {
        ContentProviderClientCompat.releaseQuietly(client);
    }
    return result;
}
 
Example #19
Source File: QuantumFluxSyncHelper.java    From QuantumFlux with Apache License 2.0 5 votes vote down vote up
public static <T> void updateColumnsExcluding(Context context, ContentProviderClient provider, T dataModelObject, String... columnsToExclude) throws RemoteException {
    TableDetails tableDetails = QuantumFlux.findTableDetails(dataModelObject.getClass());
    ContentValues contentValues = ModelInflater.deflate(tableDetails, dataModelObject);
    Object columnValue = ModelInflater.deflateColumn(tableDetails, tableDetails.findPrimaryKeyColumn(), dataModelObject);
    Uri itemUri = UriMatcherHelper.generateItemUriBuilder(tableDetails, String.valueOf(columnValue))
            .appendQueryParameter(QuantumFluxContentProvider.PARAMETER_SYNC, "false").build();

    for (String columnToExclude : columnsToExclude) {
        contentValues.remove(columnToExclude);
    }

    provider.update(itemUri, contentValues, null, null);
}
 
Example #20
Source File: DictionaryFactory.java    From Indic-Keyboard with Apache License 2.0 5 votes vote down vote up
/**
 * Kills a dictionary so that it is never used again, if possible.
 * @param context The context to contact the dictionary provider, if possible.
 * @param f A file address to the dictionary to kill.
 */
public static void killDictionary(final Context context, final AssetFileAddress f) {
    if (f.pointsToPhysicalFile()) {
        f.deleteUnderlyingFile();
        // Warn the dictionary provider if the dictionary came from there.
        final ContentProviderClient providerClient;
        try {
            providerClient = context.getContentResolver().acquireContentProviderClient(
                    BinaryDictionaryFileDumper.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;
        }
        final String wordlistId =
                DictionaryInfoUtils.getWordListIdFromFileName(new File(f.mFilename).getName());
        // TODO: this is a reasonable last resort, but it is suboptimal.
        // The following will remove the entry for this dictionary with the dictionary
        // provider. When the metadata is downloaded again, we will try downloading it
        // again.
        // However, in the practice that will mean the user will find themselves without
        // the new dictionary. That's fine for languages where it's included in the APK,
        // but for other languages it will leave the user without a dictionary at all until
        // the next update, which may be a few days away.
        // Ideally, we would trigger a new download right away, and use increasing retry
        // delays for this particular id/version combination.
        // Then again, this is expected to only ever happen in case of human mistake. If
        // the wrong file is on the server, the following is still doing the right thing.
        // If it's a file left over from the last version however, it's not great.
        BinaryDictionaryFileDumper.reportBrokenFileToDictionaryProvider(
                providerClient,
                context.getString(R.string.dictionary_pack_client_id),
                wordlistId);
    }
}
 
Example #21
Source File: BinaryDictionaryFileDumper.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the content URI builder for a specified type.
 *
 * Supported types include QUERY_PATH_DICT_INFO, which takes the locale as
 * the extraPath argument, and QUERY_PATH_DATAFILE, which needs a wordlist ID
 * as the extraPath argument.
 *
 * @param clientId the clientId to use
 * @param contentProviderClient the instance of content provider client
 * @param queryPathType the path element encoding the type
 * @param extraPath optional extra argument for this type (typically word list id)
 * @return a builder that can build the URI for the best supported protocol version
 * @throws RemoteException if the client can't be contacted
 */
private static Uri.Builder getContentUriBuilderForType(final Context context, final String clientId,
        final ContentProviderClient contentProviderClient, final String queryPathType,
        final String extraPath) throws RemoteException {
    // Check whether protocol v2 is supported by building a v2 URI and calling getType()
    // on it. If this returns null, v2 is not supported.
    final Uri.Builder uriV2Builder = getProviderUriBuilder(context, clientId);
    uriV2Builder.appendPath(queryPathType);
    uriV2Builder.appendPath(extraPath);
    uriV2Builder.appendQueryParameter(QUERY_PARAMETER_PROTOCOL,
            QUERY_PARAMETER_PROTOCOL_VALUE);
    if (null != contentProviderClient.getType(uriV2Builder.build())) return uriV2Builder;
    // Protocol v2 is not supported, so create and return the protocol v1 uri.
    return getProviderUriBuilder(context, extraPath);
}
 
Example #22
Source File: AbstractContentProviderStub.java    From DroidPlugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
@TargetApi(VERSION_CODES.JELLY_BEAN_MR1)
@Override
public Bundle call(String method, String arg, Bundle extras) {
    String targetAuthority = extras != null ? extras.getString(Env.EXTRA_TARGET_AUTHORITY) : null;
    String targetMethod = extras != null ? extras.getString(Env.EXTRA_TARGET_AUTHORITY) : null;
    if (!TextUtils.isEmpty(targetMethod) && !TextUtils.equals(targetMethod, method)) {
        ContentProviderClient client = getContentProviderClient(targetAuthority);
        try {
            return client.call(targetMethod, arg, extras);
        } catch (RemoteException e) {
            handleExpcetion(e);
        }
    }
    return super.call(method, arg, extras);
}
 
Example #23
Source File: BinaryDictionaryFileDumper.java    From openboard with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #24
Source File: DocumentsContract.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #25
Source File: DirectoryFragment.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
private synchronized ContentProviderClient getExternalStorageClient() {
	if (mExternalStorageClient == null) {
		mExternalStorageClient = getActivity().
				getContentResolver().acquireContentProviderClient(ExternalStorageProvider.AUTHORITY);
	}
	return mExternalStorageClient;
}
 
Example #26
Source File: CPSyncHelper.java    From CPOrm with MIT License 5 votes vote down vote up
public static <T> void updateColumnsExcluding(Context context, boolean notifyChanges, ContentProviderClient provider, T dataModelObject, String... columnsToExclude) throws RemoteException {
    TableDetails tableDetails = CPOrm.findTableDetails(context, dataModelObject.getClass());
    ContentValues contentValues = ModelInflater.deflate(tableDetails, dataModelObject);
    Object columnValue = ModelInflater.deflateColumn(tableDetails, tableDetails.findPrimaryKeyColumn(), dataModelObject);
    Uri itemUri = UriMatcherHelper.generateItemUri(context, tableDetails, String.valueOf(columnValue))
            .appendQueryParameter(CPOrmContentProvider.PARAMETER_SYNC, "false")
            .appendQueryParameter(CPOrmContentProvider.PARAMETER_NOTIFY_CHANGES, Boolean.toString(notifyChanges)).build();

    for (String columnToExclude : columnsToExclude) {

        contentValues.remove(columnToExclude);
    }

    provider.update(itemUri, contentValues, null, null);
}
 
Example #27
Source File: QuantumFluxSyncHelper.java    From QuantumFlux with Apache License 2.0 5 votes vote down vote up
public static <T> void update(Context context, ContentProviderClient provider, T dataModelObject) throws RemoteException {
    TableDetails tableDetails = QuantumFlux.findTableDetails(dataModelObject.getClass());
    ContentValues contentValues = ModelInflater.deflate(tableDetails, dataModelObject);
    Object columnValue = ModelInflater.deflateColumn(tableDetails, tableDetails.findPrimaryKeyColumn(), dataModelObject);
    Uri itemUri = UriMatcherHelper.generateItemUriBuilder(tableDetails, String.valueOf(columnValue))
            .appendQueryParameter(QuantumFluxContentProvider.PARAMETER_SYNC, "false").build();

    provider.update(itemUri, contentValues, null, null);
}
 
Example #28
Source File: MediaStore.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static String getFilePath(ContentResolver resolver, Uri mediaUri)
        throws RemoteException {

    try (ContentProviderClient client =
                 resolver.acquireUnstableContentProviderClient(AUTHORITY)) {
        final Cursor c = client.query(
                mediaUri,
                new String[]{ MediaColumns.DATA },
                null, /* selection */
                null, /* selectionArg */
                null /* sortOrder */);

        final String path;
        try {
            if (c.getCount() == 0) {
                throw new IllegalStateException("Not found media file under URI: " + mediaUri);
            }

            if (!c.moveToFirst()) {
                throw new IllegalStateException("Failed to move cursor to the first item.");
            }

            path = c.getString(0);
        } finally {
            IoUtils.closeQuietly(c);
        }

        return path;
    }
}
 
Example #29
Source File: ContentProviderClientCompat.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
public static void setDetectNotResponding(ContentProviderClient client, long anrTimeout){
	if(Utils.hasKitKat()){
		try {
			Method method = client.getClass().getMethod("setDetectNotResponding", long.class);
			if (method != null) {
				method.invoke(client, anrTimeout);
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example #30
Source File: ContentProviderCompat.java    From DroidPlugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static ContentProviderClient crazyAcquireContentProvider(Context context, Uri uri) {
    ContentProviderClient client = acquireContentProviderClient(context, uri);
    if (client == null) {
        int retry = 0;
        while (retry < 5 && client == null) {
            SystemClock.sleep(100);
            retry++;
            client = acquireContentProviderClient(context, uri);
        }
    }
    return client;
}