下面列出了怎么用android.os.CancellationSignal的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
/**
* 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
}
}
/**
* 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);
}
}
/** 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();
}
}
/**
* 调用插件里的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;
}
/** @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);
}
@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);
}
});
}
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;
}
@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);
}
}
@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));
}
/**
* 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);
}
}
/**
* 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
}
}
/**
* 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
}
}
/**
* 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);
}
@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())));
}
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;
}
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();
}
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
@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);
}
}
/**
* 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);
}
}
@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);
}
}
/**
* 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;
}
@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);
}
}
public WriteFileAsyncTask(ParcelFileDescriptor destination,
CancellationSignal cancellationSignal, WriteResultCallback callback) {
mDestination = destination;
mResultCallback = callback;
mCancellationSignal = cancellationSignal;
mCancellationSignal.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel() {
cancel(true);
}
});
}
/**
* 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);
}
@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);
}
}
@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);
}
}
/**
* Request the custom icon for a printer.
*
* @param printerId The printer to icon belongs to.
* @see android.print.PrinterInfo.Builder#setHasCustomPrinterIcon()
*/
void requestCustomPrinterIcon(@NonNull PrinterId printerId) {
if (!mIsDestroyed && mObserver != null) {
CustomPrinterIconCallback callback = new CustomPrinterIconCallback(printerId,
mObserver);
onRequestCustomPrinterIcon(printerId, new CancellationSignal(), callback);
}
}