android.os.CancellationSignal Java Examples

The following examples show how to use android.os.CancellationSignal. 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 Project: FireFiles   Author: gigabytedevelopers   File: StorageProvider.java    License: Apache License 2.0 6 votes vote down vote up
protected ParcelFileDescriptor openAudioThumbnailCleared(long id, CancellationSignal signal)
        throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();

    Cursor cursor = null;
    try {
        cursor = resolver.query(Audio.Albums.EXTERNAL_CONTENT_URI,
        		AudioThumbnailQuery.PROJECTION, Audio.Albums._ID + "=" + id,
                null, null);
        if (cursor.moveToFirst()) {
            final String data = cursor.getString(AudioThumbnailQuery._DATA);
            return ParcelFileDescriptor.open(
                    new File(data), ParcelFileDescriptor.MODE_READ_ONLY);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    return null;
}
 
Example #2
Source Project: squidb   Author: yahoo   File: SQLiteSession.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Executes a statement that returns a single BLOB result as a
 * file descriptor to a shared memory region.
 *
 * @param sql The SQL statement to execute.
 * @param bindArgs The arguments to bind, or null if none.
 * @param connectionFlags The connection flags to use if a connection must be
 * acquired by this operation.  Refer to {@link SQLiteConnectionPool}.
 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
 * @return The file descriptor for a shared memory region that contains
 * the value of the first column in the first row of the result set as a BLOB,
 * or null if none.
 *
 * @throws SQLiteException if an error occurs, such as a syntax error
 * or invalid number of bind arguments.
 * @throws OperationCanceledException if the operation was canceled.
 */
public ParcelFileDescriptor executeForBlobFileDescriptor(String sql, Object[] bindArgs,
        int connectionFlags, CancellationSignal cancellationSignal) {
    if (sql == null) {
        throw new IllegalArgumentException("sql must not be null.");
    }

    if (executeSpecial(sql, bindArgs, connectionFlags, cancellationSignal)) {
        return null;
    }

    acquireConnection(sql, connectionFlags, cancellationSignal); // might throw
    try {
        return mConnection.executeForBlobFileDescriptor(sql, bindArgs,
                cancellationSignal); // might throw
    } finally {
        releaseConnection(); // might throw
    }
}
 
Example #3
Source Project: AndroidComponentPlugin   Author: androidmalin   File: ContentResolver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This allows clients to request an explicit refresh of content identified by {@code uri}.
 * <p>
 * Client code should only invoke this method when there is a strong indication (such as a user
 * initiated pull to refresh gesture) that the content is stale.
 * <p>
 *
 * @param url The Uri identifying the data to refresh.
 * @param args Additional options from the client. The definitions of these are specific to the
 *            content provider being called.
 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
 *            none. For example, if you called refresh on a particular uri, you should call
 *            {@link CancellationSignal#throwIfCanceled()} to check whether the client has
 *            canceled the refresh request.
 * @return true if the provider actually tried refreshing.
 */
public final boolean refresh(@NonNull Uri url, @Nullable Bundle args,
        @Nullable CancellationSignal cancellationSignal) {
    Preconditions.checkNotNull(url, "url");
    IContentProvider provider = acquireProvider(url);
    if (provider == null) {
        return false;
    }

    try {
        ICancellationSignal remoteCancellationSignal = null;
        if (cancellationSignal != null) {
            cancellationSignal.throwIfCanceled();
            remoteCancellationSignal = provider.createCancellationSignal();
            cancellationSignal.setRemote(remoteCancellationSignal);
        }
        return provider.refresh(mPackageName, url, args, remoteCancellationSignal);
    } catch (RemoteException e) {
        // Arbitrary and not worth documenting, as Activity
        // Manager will kill this process shortly anyway.
        return false;
    } finally {
        releaseProvider(provider);
    }
}
 
Example #4
Source Project: android_9.0.0_r45   Author: lulululbj   File: ContentProviderClient.java    License: Apache License 2.0 6 votes vote down vote up
/** See {@link ContentProvider#openTypedAssetFile ContentProvider.openTypedAssetFile} */
public final @Nullable AssetFileDescriptor openTypedAssetFileDescriptor(@NonNull Uri uri,
        @NonNull String mimeType, @Nullable Bundle opts, @Nullable CancellationSignal signal)
                throws RemoteException, FileNotFoundException {
    Preconditions.checkNotNull(uri, "uri");
    Preconditions.checkNotNull(mimeType, "mimeType");

    beforeRemote();
    try {
        ICancellationSignal remoteSignal = null;
        if (signal != null) {
            signal.throwIfCanceled();
            remoteSignal = mContentProvider.createCancellationSignal();
            signal.setRemote(remoteSignal);
        }
        return mContentProvider.openTypedAssetFile(
                mPackageName, uri, mimeType, opts, remoteSignal);
    } catch (DeadObjectException e) {
        if (!mStable) {
            mContentResolver.unstableProviderDied(mContentProvider);
        }
        throw e;
    } finally {
        afterRemote();
    }
}
 
Example #5
Source Project: springreplugin   Author: wangyupeng1-iri   File: PluginProviderClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 调用插件里的Provider
 *
 * @see android.content.ContentResolver#query(Uri, String[], String, String[], String, CancellationSignal)
 */
@TargetApi(16)
public static Cursor query(Context c, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, CancellationSignal cancellationSignal) {
    if (c == null) {
        return null;
    }

    if (!RePluginFramework.mHostInitialized) {
        return c.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
    }

    try {
        return (Cursor) ProxyRePluginProviderClientVar.query2.call(null, c, uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
    } catch (Exception e) {
        if (LogDebug.LOG) {
            e.printStackTrace();
        }
    }

    return null;
}
 
Example #6
Source Project: android_9.0.0_r45   Author: lulululbj   File: TextClassifierService.java    License: Apache License 2.0 6 votes vote down vote up
/** @hide */
public void onSuggestSelection(
        @NonNull CharSequence text,
        @IntRange(from = 0) int selectionStartIndex,
        @IntRange(from = 0) int selectionEndIndex,
        @Nullable TextSelection.Options options,
        @NonNull CancellationSignal cancellationSignal,
        @NonNull Callback<TextSelection> callback) {
    final TextClassificationSessionId sessionId = options.getSessionId();
    final TextSelection.Request request = options.getRequest() != null
            ? options.getRequest()
            : new TextSelection.Request.Builder(
                    text, selectionStartIndex, selectionEndIndex)
                    .setDefaultLocales(options.getDefaultLocales())
                    .build();
    onSuggestSelection(sessionId, request, cancellationSignal, callback);
}
 
Example #7
Source Project: MiPushFramework   Author: MiPushFramework   File: EventDb.java    License: GNU General Public License v3.0 6 votes vote down vote up
@RequiresPermission(value = Constants.permissions.READ_SETTINGS)
public static List<Event> query(@Nullable Integer skip,
                                @Nullable Integer limit,
                                @Nullable String pkg,
                                Context context,
                                @Nullable CancellationSignal signal) {
    return getInstance(context)
            .queryAndConvert(signal, pkg == null ? null : Event.KEY_PKG + "=?",
                    pkg != null ? new String[]{pkg} : null,
                    DatabaseUtils.order(Event.KEY_DATE, "desc") +
                            DatabaseUtils.limitAndOffset(limit, skip),
                    new DatabaseUtils.Converter<Event>() {
                        @Override
                        @NonNull
                        public Event convert(@NonNull Cursor cursor) {
                            return Event.create(cursor);
                        }
                    });
}
 
Example #8
Source Project: secure-quick-reliable-login   Author: kalaspuffar   File: RescueCodePrintDocumentAdapter.java    License: MIT License 6 votes vote down vote up
@Override
public void onWrite(
        final PageRange[] pageRanges,
        final ParcelFileDescriptor destination,
        final CancellationSignal cancellationSignal,
        final WriteResultCallback callback
) {
    PdfDocument.Page page = mPdfDocument.startPage(0);

    if (cancellationSignal.isCanceled()) {
        callback.onWriteCancelled();
        mPdfDocument.close();
        mPdfDocument = null;
        return;
    }

    drawPage(page);

    mPdfDocument.finishPage(page);
    try {
        mPdfDocument.writeTo(new FileOutputStream(
                destination.getFileDescriptor()));
    } catch (IOException e) {
        callback.onWriteFailed(e.toString());
        return;
    } finally {
        mPdfDocument.close();
        mPdfDocument = null;
    }
    callback.onWriteFinished(pageRanges);
}
 
Example #9
Source Project: FireFiles   Author: gigabytedevelopers   File: StorageProvider.java    License: Apache License 2.0 6 votes vote down vote up
protected ParcelFileDescriptor openImageThumbnailCleared(long id, CancellationSignal signal)
        throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();

    Cursor cursor = null;
    try {
        cursor = resolver.query(Images.Thumbnails.EXTERNAL_CONTENT_URI,
                ImageThumbnailQuery.PROJECTION, Images.Thumbnails.IMAGE_ID + "=" + id, null,
                null);
        if (cursor.moveToFirst()) {
            final String data = cursor.getString(ImageThumbnailQuery._DATA);
            return ParcelFileDescriptor.open(
                    new File(data), ParcelFileDescriptor.MODE_READ_ONLY);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    return null;
}
 
Example #10
Source Project: FireFiles   Author: gigabytedevelopers   File: NonMediaDocumentsProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
        throws FileNotFoundException {

    if (!"r".equals(mode)) {
        throw new IllegalArgumentException("Media is read-only");
    }

    final Uri target = getUriForDocumentId(docId);

    // Delegate to real provider
    final long token = Binder.clearCallingIdentity();
    try {
        return getContext().getContentResolver().openFileDescriptor(target, mode);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
Example #11
Source Project: whorlwind   Author: square   File: RealWhorlwindTest.java    License: Apache License 2.0 6 votes vote down vote up
@Ignore @Test public void immediateUnsubscribeShouldntCallAuthenticate()
    throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException {
  Key key = mock(Key.class);
  shadowContext.grantPermissions(USE_FINGERPRINT);
  when(fingerprintManager.isHardwareDetected()).thenReturn(true);
  when(fingerprintManager.hasEnrolledFingerprints()).thenReturn(true);
  when(keyStore.getKey("test", null)).thenReturn(key);

  Observable<ReadResult> read = whorlwind.read("test").take(1);

  ReadResult readResult = read.blockingSingle();
  assertEquals(ReadResult.ReadState.NEEDS_AUTH, readResult.readState);

  verify(fingerprintManager, never()).authenticate(any(FingerprintManager.CryptoObject.class),
      any(CancellationSignal.class), anyInt(),
      any(FingerprintManager.AuthenticationCallback.class), any(Handler.class));
}
 
Example #12
Source Project: FireFiles   Author: gigabytedevelopers   File: DocumentsContract.java    License: 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,
 *      CancellationSignal)
 */
public static Bitmap getDocumentThumbnail(
        ContentResolver resolver, Uri documentUri, Point size, CancellationSignal signal) {
	final ContentProviderClient client = ContentProviderClientCompat.acquireUnstableContentProviderClient(resolver, 
			documentUri.getAuthority());
    try {
        if(UsbStorageProvider.AUTHORITY.equals(documentUri.getAuthority())) {
            return ImageUtils.getThumbnail(resolver, documentUri, size.x, size.y);
        }
        return getDocumentThumbnails(client, documentUri, size, signal);
    } catch (Exception e) {
        if (!(e instanceof OperationCanceledException)) {
            Log.w(TAG, "Failed to load thumbnail for " + documentUri + ": " + e);
        }
        return null;
    } finally {
    	ContentProviderClientCompat.releaseQuietly(client);
    }
}
 
Example #13
Source Project: android_9.0.0_r45   Author: lulululbj   File: SQLiteSession.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Executes a statement that returns a count of the number of rows
 * that were changed.  Use for UPDATE or DELETE SQL statements.
 *
 * @param sql The SQL statement to execute.
 * @param bindArgs The arguments to bind, or null if none.
 * @param connectionFlags The connection flags to use if a connection must be
 * acquired by this operation.  Refer to {@link SQLiteConnectionPool}.
 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
 * @return The number of rows that were changed.
 *
 * @throws SQLiteException if an error occurs, such as a syntax error
 * or invalid number of bind arguments.
 * @throws OperationCanceledException if the operation was canceled.
 */
public int executeForChangedRowCount(String sql, Object[] bindArgs, int connectionFlags,
        CancellationSignal cancellationSignal) {
    if (sql == null) {
        throw new IllegalArgumentException("sql must not be null.");
    }

    if (executeSpecial(sql, bindArgs, connectionFlags, cancellationSignal)) {
        return 0;
    }

    acquireConnection(sql, connectionFlags, cancellationSignal); // might throw
    try {
        return mConnection.executeForChangedRowCount(sql, bindArgs,
                cancellationSignal); // might throw
    } finally {
        releaseConnection(); // might throw
    }
}
 
Example #14
Source Project: squidb   Author: yahoo   File: SQLiteSession.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Executes a statement that returns a count of the number of rows
 * that were changed.  Use for UPDATE or DELETE SQL statements.
 *
 * @param sql The SQL statement to execute.
 * @param bindArgs The arguments to bind, or null if none.
 * @param connectionFlags The connection flags to use if a connection must be
 * acquired by this operation.  Refer to {@link SQLiteConnectionPool}.
 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
 * @return The number of rows that were changed.
 *
 * @throws SQLiteException if an error occurs, such as a syntax error
 * or invalid number of bind arguments.
 * @throws OperationCanceledException if the operation was canceled.
 */
public int executeForChangedRowCount(String sql, Object[] bindArgs, int connectionFlags,
        CancellationSignal cancellationSignal) {
    if (sql == null) {
        throw new IllegalArgumentException("sql must not be null.");
    }

    if (executeSpecial(sql, bindArgs, connectionFlags, cancellationSignal)) {
        return 0;
    }

    acquireConnection(sql, connectionFlags, cancellationSignal); // might throw
    try {
        return mConnection.executeForChangedRowCount(sql, bindArgs,
                cancellationSignal); // might throw
    } finally {
        releaseConnection(); // might throw
    }
}
 
Example #15
Source Project: arcusandroid   Author: arcus-smart-home   File: FingerprintHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Start an authentication request
 * @param listener              The listener to be notified
 * @param keepSensorActive      Determines if we should retry
 */
public void authenticate(final AuthenticationListener listener,
                                Fingerprint.KeepSensorActive keepSensorActive){
    // If somehow the phone has no way to detect fingerprints and we got here, send a fatal message and kick back
    // to username/password login. This shouldn't happen.
    if(mAuthenticator == null) {
        logger.debug("Failing fingerprint authentication - Unsupported device - at {}", getClass().getSimpleName());
        listener.onFailure(AuthenticationFailureReason.NO_SENOR, true,
                "no authentication method", 0, 0);
        return;
    }

    // If there's no hardware to detect fingerprint, send a fatal message and kick back to username/password login.
    if(!mAuthenticator.isHardwareAvailable()){
        logger.debug("Failing fingerprint authentication for reason {}, at:  ", AuthenticationFailureReason.NO_SENOR, getClass().getSimpleName());
        listener.onFailure(AuthenticationFailureReason.NO_SENOR, true,
                sensorMissing, 0, 0);
        return;
    }

    // If there are no fingerprints enrolled, send a fatal message and kick back to username/password login.
    if(!mAuthenticator.hasRegisteredFingerprint()){
        logger.debug("Failing fingerprint authentication for reason {}, at:  ", AuthenticationFailureReason.NO_REGISTERED_FINGERPRINTS, getClass().getSimpleName());
        listener.onFailure(AuthenticationFailureReason.NO_REGISTERED_FINGERPRINTS, true,
                fingerprintNotSetup, 0, 0);
    }

    mCancellationSignal = new CancellationSignal();
    mAuthenticator.authenticate(mCancellationSignal, listener, keepSensorActive);
}
 
Example #16
Source Project: android_9.0.0_r45   Author: lulululbj   File: AutofillService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onFillRequest(FillRequest request, IFillCallback callback) {
    ICancellationSignal transport = CancellationSignal.createTransport();
    try {
        callback.onCancellable(transport);
    } catch (RemoteException e) {
        e.rethrowFromSystemServer();
    }
    mHandler.sendMessage(obtainMessage(
            AutofillService::onFillRequest,
            AutofillService.this, request, CancellationSignal.fromTransport(transport),
            new FillCallback(callback, request.getId())));
}
 
Example #17
Source Project: squidb   Author: yahoo   File: SQLiteSession.java    License: Apache License 2.0 5 votes vote down vote up
private void acquireConnection(String sql, int connectionFlags,
        CancellationSignal cancellationSignal) {
    if (mConnection == null) {
        assert mConnectionUseCount == 0;
        mConnection = mConnectionPool.acquireConnection(sql, connectionFlags,
                cancellationSignal); // might throw
        mConnectionFlags = connectionFlags;
    }
    mConnectionUseCount += 1;
}
 
Example #18
Source Project: secure-quick-reliable-login   Author: kalaspuffar   File: LoginActivity.java    License: MIT License 5 votes vote down vote up
private void doLoginBiometric() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return;

    BioAuthenticationCallback biometricCallback =
            new BioAuthenticationCallback(LoginActivity.this.getApplicationContext(), () ->
                    handler.post(() -> doLogin(false, useCps, false))
            );

    BiometricPrompt bioPrompt = new BiometricPrompt.Builder(this)
            .setTitle(getString(R.string.login_title))
            .setSubtitle(mSqrlMatcher.group(1))
            .setDescription(getString(R.string.login_verify_domain_text))
            .setNegativeButton(
                    getString(R.string.button_cps_cancel),
                    this.getMainExecutor(),
                    (dialogInterface, i) -> {}
            ).build();

    CancellationSignal cancelSign = new CancellationSignal();
    cancelSign.setOnCancelListener(() -> {});

    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        KeyStore.Entry entry = keyStore.getEntry("quickPass", null);
        Cipher decCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING"); //or try with "RSA"
        decCipher.init(Cipher.DECRYPT_MODE, ((KeyStore.PrivateKeyEntry) entry).getPrivateKey());
        bioPrompt.authenticate(new BiometricPrompt.CryptoObject(decCipher), cancelSign, this.getMainExecutor(), biometricCallback);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #19
Source Project: android_9.0.0_r45   Author: lulululbj   File: DocumentsProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Implementation is provided by the parent class. Cannot be overridden.
 *
 * @see #openDocument(String, String, CancellationSignal)
 */
@Override
public final ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
        throws FileNotFoundException {
    enforceTree(uri);
    return openDocument(getDocumentId(uri), mode, signal);
}
 
Example #20
Source Project: shillelagh   Author: AndrewReitz   File: Shillelagh.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * The equivalent of calling
 * {@link SQLiteDatabase#query(boolean, String, String[], String, String[], String, String,
 * String, String, android.os.CancellationSignal)}
 * and then calling {@link Shillelagh#map(Class, android.database.Cursor)} on the result
 *
 * Only available for API 16+
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public <T extends List<M>, M> T query(Class<? extends M> tableObject, boolean distinct,
    String[] columns, String selection, String[] selectionArgs, String groupBy, String having,
    String orderBy, String limit, CancellationSignal cancellationSignal) {
  Cursor results = sqliteOpenHelper.getReadableDatabase()
      .query(distinct, getTableName(tableObject), columns, selection, selectionArgs, groupBy,
          having, orderBy, limit, cancellationSignal);
  return map(tableObject, results);
}
 
Example #21
Source Project: FireFiles   Author: gigabytedevelopers   File: DocumentsProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Implementation is provided by the parent class. Cannot be overriden.
 *
 * @see #openDocument(String, String, CancellationSignal)
 */
@Override
public final ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
        throws FileNotFoundException {
    enforceTree(uri);
    return openDocument(getDocumentId(uri), mode, signal);
}
 
Example #22
Source Project: FireFiles   Author: gigabytedevelopers   File: DownloadStorageProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
        throws FileNotFoundException {
    // Delegate to real provider
    final long token = Binder.clearCallingIdentity();
    try {
        final long id = Long.parseLong(docId);
        final ContentResolver resolver = getContext().getContentResolver();
        return resolver.openFileDescriptor(mDm.getUriForDownloadedFile(id), mode);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
Example #23
Source Project: FireFiles   Author: gigabytedevelopers   File: DocumentArchiveHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Opens a file within an archive.
 *
 */
public ParcelFileDescriptor openDocument(
        String documentId, String mode, final CancellationSignal signal)
        throws FileNotFoundException {
    Loader loader = null;
    try {
        loader = obtainInstance(documentId);
        return loader.get().openDocument(documentId, mode, signal);
    } finally {
        releaseInstance(loader);
    }
}
 
Example #24
Source Project: Applozic-Android-SDK   Author: AppLozic   File: LocalStorageProvider.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public ParcelFileDescriptor openDocument(final String documentId, final String mode,
                                         final CancellationSignal signal) throws FileNotFoundException {
    File file = new File(documentId);
    final boolean isWrite = (mode.indexOf('w') != -1);
    if (isWrite) {
        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);
    } else {
        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    }
}
 
Example #25
Source Project: android_9.0.0_r45   Author: lulululbj   File: DocumentsProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Implementation is provided by the parent class. Cannot be overridden.
 *
 * @see #openDocument(String, String, CancellationSignal)
 */
@Override
@SuppressWarnings("resource")
public final AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
        throws FileNotFoundException {
    enforceTree(uri);
    final ParcelFileDescriptor fd = openDocument(getDocumentId(uri), mode, signal);
    return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
}
 
Example #26
Source Project: MHViewer   Author: axlecho   File: SecurityScene.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onResume() {
    super.onResume();

    if (null != mShakeDetector) {
        mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
    }

    if (isFingerprintAuthAvailable()) {
        mFingerprintCancellationSignal = new CancellationSignal();
        // The line below prevents the false positive inspection from Android Studio
        // noinspection ResourceType
        mFingerprintManager.authenticate(null, mFingerprintCancellationSignal, 0,
                new FingerprintManager.AuthenticationCallback() {
                    @Override
                    public void onAuthenticationError(int errMsgId, CharSequence errString) {
                        fingerprintError(true);
                    }

                    @Override
                    public void onAuthenticationFailed() {
                        fingerprintError(false);
                    }

                    @Override
                    public void onAuthenticationSucceeded(
                            FingerprintManager.AuthenticationResult result) {
                        mFingerprintIcon.setImageResource(R.drawable.fingerprint_success);
                        mFingerprintIcon.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startSceneForCheckStep(CHECK_STEP_SECURITY, getArguments());
                                finish();
                            }
                        }, SUCCESS_DELAY_MILLIS);

                    }
                }, null);
    }
}
 
Example #27
Source Project: android_9.0.0_r45   Author: lulululbj   File: PrintFileDocumentAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public WriteFileAsyncTask(ParcelFileDescriptor destination,
        CancellationSignal cancellationSignal, WriteResultCallback callback) {
    mDestination = destination;
    mResultCallback = callback;
    mCancellationSignal = cancellationSignal;
    mCancellationSignal.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel() {
            cancel(true);
        }
    });
}
 
Example #28
Source Project: Carbon   Author: ZieIony   File: TypefaceCompat.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a Typeface from a given FontInfo list and a map that matches them to ByteBuffers.
 *
 * @hide
 */
@Nullable
@RestrictTo(LIBRARY_GROUP_PREFIX)
public static Typeface createFromFontInfo(@NonNull Context context,
                                          @Nullable CancellationSignal cancellationSignal, @NonNull FontInfo[] fonts, boolean italic, int weight) {
    return sTypefaceCompatImpl.createFromFontInfo(context, cancellationSignal, fonts, italic, weight);
}
 
Example #29
Source Project: qiniu-lab-android   Author: qiniudemo   File: LocalStorageProvider.java    License: MIT License 5 votes vote down vote up
@Override
public ParcelFileDescriptor openDocument(final String documentId, final String mode,
                                         final CancellationSignal signal) throws FileNotFoundException {
    File file = new File(documentId);
    final boolean isWrite = (mode.indexOf('w') != -1);
    if (isWrite) {
        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);
    } else {
        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    }
}
 
Example #30
Source Project: android_9.0.0_r45   Author: lulululbj   File: ContentProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
        Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
    Bundle.setDefusable(opts, true);
    uri = validateIncomingUri(uri);
    uri = maybeGetUriWithoutUserId(uri);
    enforceFilePermission(callingPkg, uri, "r", null);
    final String original = setCallingPackage(callingPkg);
    try {
        return ContentProvider.this.openTypedAssetFile(
                uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
    } finally {
        setCallingPackage(original);
    }
}