下面列出了怎么用android.content.IntentSender的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), MainActivity.this, 0).show();
return;
}
if (!authInProgress) {
try {
authInProgress = true;
result.startResolutionForResult(MainActivity.this, REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Toast.makeText(MainActivity.this, R.string.connection_failed, Toast.LENGTH_LONG).show();
finish();
}
}
}
public boolean resolveConnectionFailure(ConnectionResult result, int requestCode) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(activity, requestCode);
return true;
} catch (IntentSender.SendIntentException e) {
// The intent was canceled before it was sent. Return to the default
// state and attempt to connect to get an updated ConnectionResult.
googleApiClient.connect();
return false;
}
} else {
// not resolvable... so show an error message
int errorCode = result.getErrorCode();
if (errorCode == ConnectionResult.INTERNAL_ERROR) {
googleApiClient.connect();
}
GodotLib.calldeferred(instance_id, "_on_google_play_game_services_connection_failed", new Object[] { });
Log.i(TAG, "GPGS: onConnectionFailed error code: " + String.valueOf(errorCode));
return false;
}
}
/**
* Called when the Load Hints button is clicked. Requests a Credential "hint" which will
* be the basic profile information and an ID token for an account on the device. This is useful
* to auto-fill sign-up forms with an email address, picture, and name or to do password-free
* authentication with a server by providing an ID Token.
*/
private void loadHintClicked() {
HintRequest hintRequest = new HintRequest.Builder()
.setHintPickerConfig(new CredentialPickerConfig.Builder()
.setShowCancelButton(true)
.build())
.setIdTokenRequested(shouldRequestIdToken())
.setEmailAddressIdentifierSupported(true)
.setAccountTypes(IdentityProviders.GOOGLE)
.build();
;
PendingIntent intent = mCredentialsClient.getHintPickerIntent(hintRequest);
try {
startIntentSenderForResult(intent.getIntentSender(), RC_HINT, null, 0, 0, 0);
mIsResolving = true;
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Could not start hint picker Intent", e);
mIsResolving = false;
}
}
private synchronized void downloadKey(final long keyId, Intent actionIntent) {
PendingIntent pi = getGpgEncryptionHandler(getMView().getContext()).getDownloadKeyPendingIntent(keyId, actionIntent);
if (pi != null) {
mTempDownloadKeyId = keyId;
try {
getActivity().startIntentSenderForResult(pi.getIntentSender(), EncryptionParamsActivityContract.REQUEST_CODE_DOWNLOAD_KEY, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
//TODO what now?
}
}
}
@Override
public void uninstall(String packageName, String callerPackageName, int flags, IntentSender statusReceiver, int userId) throws RemoteException {
boolean success = VAppManagerService.get().uninstallApp(packageName);
if (statusReceiver != null) {
final Intent fillIn = new Intent();
fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, packageName);
fillIn.putExtra(PackageInstaller.EXTRA_STATUS, success ? PackageInstaller.STATUS_SUCCESS : PackageInstaller.STATUS_FAILURE);
fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE, PackageHelper.deleteStatusToString(success));
fillIn.putExtra("android.content.pm.extra.LEGACY_STATUS", success ? 1 : -1);
try {
statusReceiver.sendIntent(mContext, 0, fillIn, null, null);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}
@Override
public void startIntentSender(IntentSender intent, Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags, Bundle options)
throws IntentSender.SendIntentException {
try {
String resolvedType = null;
if (fillInIntent != null) {
fillInIntent.migrateExtraStreamToClipData();
fillInIntent.prepareToLeaveProcess(this);
resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
}
int result = ActivityManager.getService()
.startActivityIntentSender(mMainThread.getApplicationThread(),
intent != null ? intent.getTarget() : null,
intent != null ? intent.getWhitelistToken() : null,
fillInIntent, resolvedType, null, null,
0, flagsMask, flagsValues, options);
if (result == ActivityManager.START_CANCELED) {
throw new IntentSender.SendIntentException();
}
Instrumentation.checkStartActivityResult(result, null);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public void startIntentSender(IntentSender intent, Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags, Bundle options)
throws IntentSender.SendIntentException {
try {
String resolvedType = null;
if (fillInIntent != null) {
fillInIntent.migrateExtraStreamToClipData();
fillInIntent.prepareToLeaveProcess(this);
resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
}
int result = ActivityManager.getService()
.startActivityIntentSender(mMainThread.getApplicationThread(),
intent != null ? intent.getTarget() : null,
intent != null ? intent.getWhitelistToken() : null,
fillInIntent, resolvedType, null, null,
0, flagsMask, flagsValues, options);
if (result == ActivityManager.START_CANCELED) {
throw new IntentSender.SendIntentException();
}
Instrumentation.checkStartActivityResult(result, null);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public void startIntentSender(IntentSender intent, Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags, Bundle options)
throws IntentSender.SendIntentException {
try {
String resolvedType = null;
if (fillInIntent != null) {
fillInIntent.setAllowFds(false);
resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
}
int result = ActivityManagerNative.getDefault()
.startActivityIntentSender(mMainThread.getApplicationThread(), intent,
fillInIntent, resolvedType, null, null,
0, flagsMask, flagsValues, options);
if (result == ActivityManager.START_CANCELED) {
throw new IntentSender.SendIntentException();
}
Instrumentation.checkStartActivityResult(result, null);
} catch (RemoteException e) {
}
}
@Override
public void onPackageInstalled(String basePackageName, int returnCode, String msg,
Bundle extras) {
final Intent fillIn = new Intent();
fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, basePackageName);
fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId);
fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
installStatusToPublicStatus(returnCode));
fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE,
installStatusToString(returnCode, msg));
fillIn.putExtra("android.content.pm.extra.LEGACY_STATUS", returnCode);
if (extras != null) {
final String existing = extras.getString("android.content.pm.extra.FAILURE_EXISTING_PACKAGE");
if (!TextUtils.isEmpty(existing)) {
fillIn.putExtra(PackageInstaller.EXTRA_OTHER_PACKAGE_NAME, existing);
}
}
try {
mTarget.sendIntent(mContext, 0, fillIn, null, null);
} catch (IntentSender.SendIntentException ignored) {
}
}
private void handleUnsuccessfulNearbyResult(Status status) {
Log.v(TAG, "Processing error, status = " + status);
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (status.hasResolution()) {
try {
mResolvingError = true;
status.startResolutionForResult(getActivity(),
REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
mResolvingError = false;
Log.v(TAG, "Failed to resolve error status.", e);
}
} else {
if (status.getStatusCode() == CommonStatusCodes.NETWORK_ERROR) {
Toast.makeText(getActivity(),
"No connectivity, cannot proceed. Fix in 'Settings' and try again.",
Toast.LENGTH_LONG).show();
} else {
// To keep things simple, pop a toast for all other error messages.
Toast.makeText(getActivity(), "Unsuccessful: " +
status.getStatusMessage(), Toast.LENGTH_LONG).show();
}
}
}
private void showHint() {
ui.clearKeyboard();
HintRequest hintRequest = new HintRequest.Builder()
.setHintPickerConfig(new CredentialPickerConfig.Builder()
.setShowCancelButton(true)
.build())
.setPhoneNumberIdentifierSupported(true)
.build();
PendingIntent intent =
Auth.CredentialsApi.getHintPickerIntent(mCredentialsApiClient, hintRequest);
try {
startIntentSenderForResult(intent.getIntentSender(), RC_HINT, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Could not start hint picker Intent", e);
}
}
@Override
public void startIntentSender(IntentSender intent, Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags, Bundle options)
throws IntentSender.SendIntentException {
try {
String resolvedType = null;
if (fillInIntent != null) {
fillInIntent.setAllowFds(false);
resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
}
int result = ActivityManagerNative.getDefault()
.startActivityIntentSender(mMainThread.getApplicationThread(), intent,
fillInIntent, resolvedType, null, null,
0, flagsMask, flagsValues, options);
if (result == ActivityManager.START_CANCELED) {
throw new IntentSender.SendIntentException();
}
Instrumentation.checkStartActivityResult(result, null);
} catch (RemoteException e) {
}
}
@Override
public void onResult(DriveApi.DriveContentsResult result) {
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setTitle("cumulustv_channels.json")
.setDescription("JSON list of channels that can be imported using CumulusTV to view live streams")
.setMimeType("application/json").build();
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setActivityTitle("cumulustv_channels.json")
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(result.getDriveContents())
.build(CloudStorageProvider.getInstance().getClient());
try {
mActivity.startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
@Override
public void startIntentSender(IntentSender intent, Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags, Bundle options)
throws IntentSender.SendIntentException {
try {
String resolvedType = null;
if (fillInIntent != null) {
fillInIntent.migrateExtraStreamToClipData();
fillInIntent.prepareToLeaveProcess();
resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
}
int result = ActivityManagerNative.getDefault()
.startActivityIntentSender(mMainThread.getApplicationThread(), intent,
fillInIntent, resolvedType, null, null,
0, flagsMask, flagsValues, options);
if (result == ActivityManager.START_CANCELED) {
throw new IntentSender.SendIntentException();
}
Instrumentation.checkStartActivityResult(result, null);
} catch (RemoteException e) {
}
}
private void continueUpdateForImmediate() {
instance.appUpdateManager
.getAppUpdateInfo()
.addOnSuccessListener(new OnSuccessListener<AppUpdateInfo>() {
@Override
public void onSuccess(AppUpdateInfo appUpdateInfo) {
if (appUpdateInfo.updateAvailability()
== UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
// If an in-app update is already running, resume the update.
try {
instance.appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
instance.mode,
getActivity(),
UpdateManagerConstant.REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
Log.d(TAG, "" + e.getMessage());
}
}
}
});
}
@Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution() && mActivity != null) {
try {
mResolvingError = true;
result.startResolutionForResult(mActivity, 1000);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
Log.e(TAG, "Connection to Google API client has failed");
mResolvingError = false;
if (mListener != null) mListener.onDataUpdated();
Wearable.MessageApi.removeListener(mGoogleApiClient, this);
Wearable.DataApi.removeListener(mGoogleApiClient, this);
}
}
private void signIn() {
if (mApiClient.isConnected()) {
return;
}
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// Retry connecting
mConnectionResult = null;
mApiClient.connect();
}
}
}
@Test
public void purchaseFailsIfResultIntentIsNull() throws RemoteException, IntentSender.SendIntentException {
mockDependeniesForSuccessfulPurchaseFlow();
InAppBillingV3Vendor vendor = new InAppBillingV3Vendor(api, null);
vendor.initialize(mock(Context.class), initializationListener);
Product inappPurchase = Product
.create(
InAppBillingConstants.VENDOR_PACKAGE,
"1",
"1",
"1",
"1",
"1",
false,
1);
PurchaseListener purchaseListener = mock(PurchaseListener.class);
vendor.purchase(activity, inappPurchase, null, purchaseListener);
vendor.onActivityResult(vendor.getRequestCode(), Activity.RESULT_OK, null);
verify(purchaseListener, times(1)).failure(inappPurchase, new Vendor.Error(PURCHASE_FAILURE, BILLING_RESPONSE_RESULT_ERROR));
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Could not connect to Google Play Services. The user needs to select an account,
// grant permissions or resolve an error in order to sign in. Refer to the javadoc for
// ConnectionResult to see possible error codes.
Log.d(TAG, "onConnectionFailed: " + connectionResult);
if (!mIsResolving && mShouldResolve) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(FriendlyPingActivity.this,
REQUEST_CODE_SIGN_IN);
mIsResolving = true;
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Could not resolve ConnectionResult.", e);
mIsResolving = false;
mGoogleApiClient.connect();
}
} else {
showErrorDialog(connectionResult);
}
} else {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment, getSignInFragment()).commit();
mProgressView.setVisibility(View.GONE);
mContentView.setVisibility(View.VISIBLE);
mShouldResolve = true;
}
}
private IntentSender createIntentSenderForOriginalIntent(int callingUid, int flags) {
Bundle activityOptions = deferCrossProfileAppsAnimationIfNecessary();
final IIntentSender target = mService.getIntentSenderLocked(
INTENT_SENDER_ACTIVITY, mCallingPackage, callingUid, mUserId, null /*token*/,
null /*resultCode*/, 0 /*requestCode*/,
new Intent[] { mIntent }, new String[] { mResolvedType },
flags, activityOptions);
return new IntentSender(target);
}
/**
* Wraps autofill data in a {@link Dataset} object with an IntentSender, which can then be
* sent back to the client.
*/
public Dataset buildDataset(HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint,
DatasetWithFilledAutofillFields datasetWithFilledAutofillFields,
RemoteViews remoteViews, IntentSender intentSender) {
Dataset.Builder datasetBuilder = new Dataset.Builder(remoteViews);
if (intentSender != null) {
datasetBuilder.setAuthentication(intentSender);
}
boolean setAtLeastOneValue = bindDataset(fieldTypesByAutofillHint,
datasetWithFilledAutofillFields, datasetBuilder);
if (!setAtLeastOneValue) {
return null;
}
return datasetBuilder.build();
}
public FillResponse buildManualResponse(IntentSender sender, RemoteViews remoteViews) {
FillResponse.Builder responseBuilder = new FillResponse.Builder();
int saveType = mClientViewMetadata.getSaveType();
AutofillId[] focusedIds = mClientViewMetadata.getFocusedIds();
if (focusedIds != null && focusedIds.length > 0) {
SaveInfo saveInfo = new SaveInfo.Builder(saveType, focusedIds).build();
return responseBuilder.setSaveInfo(saveInfo)
.setAuthentication(focusedIds, sender, remoteViews)
.build();
} else {
return null;
}
}
@Test public void shouldStartIntentAfterSuccessfulLaunchPurchaseForSubscription() throws Exception {
shouldStartSetup_SuccessCase();
Bundle response = new Bundle();
response.putParcelable(RESPONSE_BUY_INTENT, PendingIntent.getActivity(Robolectric.application, 0, new Intent(), 0));
when(service.getBuyIntent(API_VERSION, Robolectric.application.getPackageName(), "sku", "subs", "")).thenReturn(response);
Activity activity = mock(Activity.class);
helper.launchPurchaseFlow(activity, "sku", SUBS, TEST_REQUEST_CODE, purchaseFinishedListener, "");
verify(activity).startIntentSenderForResult(any(IntentSender.class), eq(TEST_REQUEST_CODE), any(Intent.class), eq(0), eq(0), eq(0));
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
/**
* Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
* After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
* Either {@param shortcut} or {@param appWidget} should be non-null.
*/
private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut,
AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) {
verifyCaller(packageName, userId);
verifyShortcutInfoPackage(packageName, shortcut);
final boolean ret;
synchronized (mLock) {
throwIfUserLockedL(userId);
Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
"Calling application must have a foreground activity or a foreground service");
// If it's a pin shortcut request, and there's already a shortcut with the same ID
// that's not visible to the caller (i.e. restore-blocked; meaning it's pinned by
// someone already), then we just replace the existing one with this new one,
// and then proceed the rest of the process.
if (shortcut != null) {
final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(
packageName, userId);
final String id = shortcut.getId();
if (ps.isShortcutExistsAndInvisibleToPublisher(id)) {
ps.updateInvisibleShortcutForPinRequestWith(shortcut);
packageShortcutsChanged(packageName, userId);
}
}
// Send request to the launcher, if supported.
ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras,
userId, resultIntent);
}
verifyStates();
return ret;
}
@Override
public void authenticate(int sessionId, int authenticationId, IntentSender intent,
Intent fillInIntent) {
final AutofillManager afm = mAfm.get();
if (afm != null) {
afm.post(() -> afm.authenticate(sessionId, authenticationId, intent, fillInIntent));
}
}
void handleIntent() {
Status status = getIntent().getParcelableExtra(ARG_STATUS);
try {
status.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (IntentSender.SendIntentException | NullPointerException e) {
setResolutionResultAndFinish(Activity.RESULT_CANCELED);
}
}
@Override
public void freeStorage(String volumeUuid, long freeStorageSize, IntentSender pi) {
try {
mPM.freeStorage(volumeUuid, freeStorageSize, pi);
} catch (RemoteException e) {
// Should never happen!
}
}
/**
* Resolve a connection failure from
* {@link com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener#onConnectionFailed(com.google.android.gms.common.ConnectionResult)}
*
* @param activity the Activity trying to resolve the connection failure.
* @param client the GoogleAPIClient instance of the Activity.
* @param result the ConnectionResult received by the Activity.
* @param requestCode a request code which the calling Activity can use to identify the result
* of this resolution in onActivityResult.
* @param fallbackErrorMessage a generic error message to display if the failure cannot be resolved.
* @return true if the connection failure is resolved, false otherwise.
*/
public static boolean resolveConnectionFailure(Activity activity,
GoogleApiClient client, ConnectionResult result, int requestCode,
String fallbackErrorMessage) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(activity, requestCode);
return true;
} catch (IntentSender.SendIntentException e) {
// The intent was canceled before it was sent. Return to the default
// state and attempt to connect to get an updated ConnectionResult.
client.connect();
return false;
}
} else {
// not resolvable... so show an error message
int errorCode = result.getErrorCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(errorCode,
activity, requestCode);
if (dialog != null) {
dialog.show();
} else {
// no built-in dialog: show the fallback error message
showAlert(activity, fallbackErrorMessage);
}
return false;
}
}
@Override
public void freeStorage(String volumeUuid, long freeStorageSize, IntentSender pi) {
try {
mPM.freeStorage(volumeUuid, freeStorageSize, 0, pi);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}