下面列出了android.os.CancellationSignal#setOnCancelListener ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void startAuth() {
final BiometricPromptCompat biometricPrompt =
new BiometricPromptCompat.Builder(MainActivity.this)
.setTitle("Title")
.setSubtitle("Subtitle")
.setDescription("Description: blablablablablablablablablablabla...")
.setNegativeButton("Use password", (dialog, which) -> Toast.makeText(
MainActivity.this,
"You requested password.",
Toast.LENGTH_LONG).show())
.build();
final CancellationSignal cancellationSignal = new CancellationSignal();
cancellationSignal.setOnCancelListener(() -> Toast.makeText(
MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show());
biometricPrompt.authenticate(cancellationSignal, this);
}
private void attachCancellationSignal(CancellationSignal cancellationSignal) {
if (cancellationSignal != null) {
cancellationSignal.throwIfCanceled();
mCancellationSignalAttachCount += 1;
if (mCancellationSignalAttachCount == 1) {
// Reset cancellation flag before executing the statement.
nativeResetCancel(mConnectionPtr, true /*cancelable*/);
// After this point, onCancel() may be called concurrently.
cancellationSignal.setOnCancelListener(this);
}
}
}
/**
* Per-user version, see {@link FingerprintManager#authenticate(CryptoObject,
* CancellationSignal, int, AuthenticationCallback, Handler)}
* @param userId the user ID that the fingerprint hardware will authenticate for.
* @hide
*/
@RequiresPermission(anyOf = {USE_BIOMETRIC, USE_FINGERPRINT})
public void authenticate(@Nullable CryptoObject crypto, @Nullable CancellationSignal cancel,
int flags, @NonNull AuthenticationCallback callback, Handler handler, int userId) {
if (callback == null) {
throw new IllegalArgumentException("Must supply an authentication callback");
}
if (cancel != null) {
if (cancel.isCanceled()) {
Slog.w(TAG, "authentication already canceled");
return;
} else {
cancel.setOnCancelListener(new OnAuthenticationCancelListener(crypto));
}
}
if (mService != null) try {
useHandler(handler);
mAuthenticationCallback = callback;
mCryptoObject = crypto;
long sessionId = crypto != null ? crypto.getOpId() : 0;
mService.authenticate(mToken, sessionId, userId, mServiceReceiver, flags,
mContext.getOpPackageName(), null /* bundle */, null /* receiver */);
} catch (RemoteException e) {
Slog.w(TAG, "Remote exception while authenticating: ", e);
if (callback != null) {
// Though this may not be a hardware issue, it will cause apps to give up or try
// again later.
callback.onAuthenticationError(FINGERPRINT_ERROR_HW_UNAVAILABLE,
getErrorString(FINGERPRINT_ERROR_HW_UNAVAILABLE, 0 /* vendorCode */));
}
}
}
/**
* Per-user version, see {@link FingerprintManager#authenticate(CryptoObject,
* CancellationSignal, Bundle, Executor, IBiometricPromptReceiver, AuthenticationCallback)}
* @param userId the user ID that the fingerprint hardware will authenticate for.
*/
private void authenticate(int userId,
@Nullable android.hardware.biometrics.CryptoObject crypto,
@NonNull CancellationSignal cancel,
@NonNull Bundle bundle,
@NonNull @CallbackExecutor Executor executor,
@NonNull IBiometricPromptReceiver receiver,
@NonNull BiometricAuthenticator.AuthenticationCallback callback) {
mCryptoObject = crypto;
if (cancel.isCanceled()) {
Slog.w(TAG, "authentication already canceled");
return;
} else {
cancel.setOnCancelListener(new OnAuthenticationCancelListener(crypto));
}
if (mService != null) {
try {
mExecutor = executor;
mAuthenticationCallback = callback;
final long sessionId = crypto != null ? crypto.getOpId() : 0;
mService.authenticate(mToken, sessionId, userId, mServiceReceiver,
0 /* flags */, mContext.getOpPackageName(), bundle, receiver);
} catch (RemoteException e) {
Slog.w(TAG, "Remote exception while authenticating", e);
mExecutor.execute(() -> {
callback.onAuthenticationError(FINGERPRINT_ERROR_HW_UNAVAILABLE,
getErrorString(FINGERPRINT_ERROR_HW_UNAVAILABLE, 0 /* vendorCode */));
});
}
}
}
/**
* Request fingerprint enrollment. This call warms up the fingerprint hardware
* and starts scanning for fingerprints. Progress will be indicated by callbacks to the
* {@link EnrollmentCallback} object. It terminates when
* {@link EnrollmentCallback#onEnrollmentError(int, CharSequence)} or
* {@link EnrollmentCallback#onEnrollmentProgress(int) is called with remaining == 0, at
* which point the object is no longer valid. The operation can be canceled by using the
* provided cancel object.
* @param token a unique token provided by a recent creation or verification of device
* credentials (e.g. pin, pattern or password).
* @param cancel an object that can be used to cancel enrollment
* @param flags optional flags
* @param userId the user to whom this fingerprint will belong to
* @param callback an object to receive enrollment events
* @hide
*/
@RequiresPermission(MANAGE_FINGERPRINT)
public void enroll(byte [] token, CancellationSignal cancel, int flags,
int userId, EnrollmentCallback callback) {
if (userId == UserHandle.USER_CURRENT) {
userId = getCurrentUserId();
}
if (callback == null) {
throw new IllegalArgumentException("Must supply an enrollment callback");
}
if (cancel != null) {
if (cancel.isCanceled()) {
Slog.w(TAG, "enrollment already canceled");
return;
} else {
cancel.setOnCancelListener(new OnEnrollCancelListener());
}
}
if (mService != null) try {
mEnrollmentCallback = callback;
mService.enroll(mToken, token, userId, mServiceReceiver, flags,
mContext.getOpPackageName());
} catch (RemoteException e) {
Slog.w(TAG, "Remote exception in enroll: ", e);
if (callback != null) {
// Though this may not be a hardware issue, it will cause apps to give up or try
// again later.
callback.onEnrollmentError(FINGERPRINT_ERROR_HW_UNAVAILABLE,
getErrorString(FINGERPRINT_ERROR_HW_UNAVAILABLE, 0 /* vendorCode */));
}
}
}
private CancellationSignal startTaskOnExecutor(AsyncApplyTask task, Executor executor) {
CancellationSignal cancelSignal = new CancellationSignal();
cancelSignal.setOnCancelListener(task);
task.executeOnExecutor(executor == null ? AsyncTask.THREAD_POOL_EXECUTOR : executor);
return cancelSignal;
}
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();
}
}
/**
* Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
* called on UI thread
*
* @return a request id which can be used to cancel the request.
*/
public CancellationSignal getPreview(WidgetItem item, int previewWidth,
int previewHeight, WidgetCell caller, boolean animate) {
String size = previewWidth + "x" + previewHeight;
WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller,
animate);
task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
CancellationSignal signal = new CancellationSignal();
signal.setOnCancelListener(task);
return signal;
}
private void biometricPromptTest() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
BiometricPrompt bp = new BiometricPrompt.Builder(this)
.setTitle("Authenticate Test")
.setDescription("setDescription")
.setNegativeButton(getString(android.R.string.cancel), getMainExecutor(), (dialogInterface, i) -> print("canceled"))
.setSubtitle("setSubtitle")
.build();
CancellationSignal signal = new CancellationSignal();
signal.setOnCancelListener(() -> print("canceled from CancellationSignal"));
bp.authenticate(signal, getMainExecutor(), new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationError(int errorCode, CharSequence errString) {
print("onAuthenticationError:" + varArgsToString(errorCode, errString));
}
@Override
public void onAuthenticationFailed() {
print("onAuthenticationFailed");
finish();
}
@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
print("onAuthenticationSucceeded");
}
@Override
public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
print("onAuthenticationHelp:" + varArgsToString(helpCode, helpString));
}
});
new Timer().schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(signal::cancel);
}
}, 5000);
}
}
private void attachCancellationSignal(CancellationSignal cancellationSignal) {
if (cancellationSignal != null) {
cancellationSignal.throwIfCanceled();
mCancellationSignalAttachCount += 1;
if (mCancellationSignalAttachCount == 1) {
// Reset cancellation flag before executing the statement.
nativeResetCancel(mConnectionPtr, true /*cancelable*/);
// After this point, onCancel() may be called concurrently.
cancellationSignal.setOnCancelListener(this);
}
}
}