下面列出了android.content.Intent#resolveActivity ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void dispatchAction() {
if (Intent.ACTION_CALL.equals(calloutAction)) {
tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
Intent call = new Intent(Intent.ACTION_CALL);
call.setData(Uri.parse("tel:" + number));
if (call.resolveActivity(getPackageManager()) != null) {
startActivityForResult(call, CALL_RESULT);
} else {
Toast.makeText(this, Localization.get("callout.failure.dialer"), Toast.LENGTH_SHORT).show();
finish();
}
} else {
Intent sms = new Intent(Intent.ACTION_SENDTO);
sms.setData(Uri.parse("smsto:" + number));
if (sms.resolveActivity(getPackageManager()) != null) {
startActivityForResult(sms, SMS_RESULT);
} else {
Toast.makeText(this, Localization.get("callout.failure.sms"), Toast.LENGTH_SHORT).show();
finish();
}
}
}
/**
* This method fires off an implicit Intent to open a webpage.
*
* @param url Url of webpage to open. Should start with http:// or https:// as that is the
* scheme of the URI expected with this Intent according to the Common Intents page
*/
private void openWebPage(String url) {
/*
* We wanted to demonstrate the Uri.parse method because its usage occurs frequently. You
* could have just as easily passed in a Uri as the parameter of this method.
*/
Uri webpage = Uri.parse(url);
/*
* Here, we create the Intent with the action of ACTION_VIEW. This action allows the user
* to view particular content. In this case, our webpage URL.
*/
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
/*
* This is a check we perform with every implicit Intent that we launch. In some cases,
* the device where this code is running might not have an Activity to perform the action
* with the data we've specified. Without this check, in those cases your app would crash.
*/
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
/**
* Matches an intent if its package is the same as the target package for the instrumentation
* test.
*/
public static Matcher<Intent> isInternal() {
final Context targetContext = getApplicationContext();
return new TypeSafeMatcher<Intent>() {
@Override
public void describeTo(Description description) {
description.appendText("target package: " + targetContext.getPackageName());
}
@Override
public boolean matchesSafely(Intent intent) {
ComponentName component = intent.resolveActivity(targetContext.getPackageManager());
if (component != null) {
return hasMyPackageName().matches(component);
}
return false;
}
};
}
/**
* Call.
*
* @param context the context
* @param number the number
*/
@RequiresPermission(permission.CALL_PHONE)
public static void call(Context context, String number) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + number));
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) !=
PackageManager.PERMISSION_GRANTED) {
// Permission is not granted, return
return;
}
if (intent.resolveActivity(context.getPackageManager()) != null) {
context.startActivity(intent);
}
}
@Override
public void onClick(View view) {
final Activity activity = PopupComposeStatus.this;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA);
return;
}
}
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
File photoFile;
try {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
File storageDir = FileUtil.getWritableAlbumStorageDir();
String imageFileName = "JPEG_" + timeStamp + "_";
String suffix = ".jpg";
photoFile = File.createTempFile(
imageFileName, /* prefix */
suffix, /* suffix */
storageDir /* directory */
);
pictureTaken = photoFile.getName();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
activity.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} catch (IOException error) {
Log.e(TAG, "[!] cannot create photo file > " + error.getMessage());
}
}
}
private void launchPreview(BuildContext context) {
// Stop the old sketch
global.sendBroadcast(new Intent("com.calsignlabs.apde.STOP_SKETCH_PREVIEW"));
String dexUri = makeFileAvailableToPreview(PREVIEW_SKETCH_DEX.get(context)).toString();
String dataUri = context.hasData() ?
makeFileAvailableToPreview(PREVIEW_SKETCH_DATA.get(context)).toString() : "";
String[] libUris = new String[context.getLibraryDexedLibs().size()];
for (int i = 0; i < libUris.length; i ++) {
libUris[i] = makeFileAvailableToPreview(new File(context.getRootFilesDir(),
previewDexJarPrefix + context.getLibraryDexedLibs().get(i).getName())).toString();
}
// Build intent specifically for sketch previewer
Intent intent = new Intent("com.calsignlabs.apde.RUN_SKETCH_PREVIEW");
intent.setPackage("com.calsignlabs.apde.sketchpreview");
intent.putExtra("SKETCH_DEX", dexUri);
intent.putExtra("SKETCH_DATA_FOLDER", dataUri);
intent.putExtra("SKETCH_DEXED_LIBS", libUris);
intent.putExtra("SKETCH_ORIENTATION", context.getManifest().getOrientation());
intent.putExtra("SKETCH_PACKAGE_NAME", context.getPackageName());
intent.putExtra("SKETCH_CLASS_NAME", context.getSketchName());
// Launch in multi-window mode if available
if (android.os.Build.VERSION.SDK_INT >= 24) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
} else {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
if (intent.resolveActivity(global.getPackageManager()) != null) {
global.startActivity(intent);
}
}
private void onImportCertificate(Intent intent) {
Intent open = new Intent(Intent.ACTION_GET_CONTENT);
open.addCategory(Intent.CATEGORY_OPENABLE);
open.setType("*/*");
if (open.resolveActivity(getPackageManager()) == null) // system whitelisted
ToastEx.makeText(this, R.string.title_no_saf, Toast.LENGTH_LONG).show();
else
startActivityForResult(Helper.getChooser(this, open), REQUEST_IMPORT_CERTIFICATE);
}
/**
* This method uses the URI scheme for showing a location found on a map in conjunction with
* an implicit Intent. This super-handy intent is detailed in the "Common Intents" page of
* Android's developer site:
*
* @see "http://developer.android.com/guide/components/intents-common.html#Maps"
* <p>
* Protip: Hold Command on Mac or Control on Windows and click that link to automagically
* open the Common Intents page
*/
private void openLocationInMap() {
String addressString = "1600 Ampitheatre Parkway, CA";
Uri geoLocation = Uri.parse("geo:0,0?q=" + addressString);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Log.d(TAG, "Couldn't call " + geoLocation.toString() + ", no receiving apps installed!");
}
}
/**
* This checks to see if there is a suitable activity to handle the `ACTION_PICK` intent
* and returns it if found. {@link Intent#ACTION_PICK} is for picking an image from an external app.
*
* @return A prepared intent if found.
*/
@Nullable
private Intent createPickIntent() {
if (pickerType != PickerType.CAMERA) {
Intent picImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (picImageIntent.resolveActivity(getActivity().getPackageManager()) != null) {
return picImageIntent;
}
}
return null;
}
public void composeEmail(String[] addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:[email protected]")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
/**
* Use Intent to open a YouTube link in either the native app or a web browser of choice
*
* @param videoUrl The first trailer's YouTube URL
*/
private void launchTrailer(String videoUrl) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(videoUrl));
if (intent.resolveActivity(this.getPackageManager()) != null) {
startActivity(intent);
}
}
private void openFileChooser() {
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(fileTypeTmp == DfuService.TYPE_AUTO ? DfuService.MIME_TYPE_ZIP : DfuService.MIME_TYPE_OCTET_STREAM);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (intent.resolveActivity(getPackageManager()) != null) {
// file browser has been found on the device
startActivityForResult(intent, SELECT_FILE_REQ);
} else {
// there is no any file browser app, let's try to download one
final View customView = getLayoutInflater().inflate(R.layout.app_file_browser, null);
final ListView appsList = customView.findViewById(android.R.id.list);
appsList.setAdapter(new FileBrowserAppsAdapter(this));
appsList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
appsList.setItemChecked(0, true);
new AlertDialog.Builder(this)
.setTitle(R.string.dfu_alert_no_filebrowser_title)
.setView(customView)
.setNegativeButton(R.string.no, (dialog, which) -> dialog.dismiss())
.setPositiveButton(R.string.ok, (dialog, which) -> {
final int pos = appsList.getCheckedItemPosition();
if (pos >= 0) {
final String query = getResources().getStringArray(R.array.dfu_app_file_browser_action)[pos];
final Intent storeIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(query));
startActivity(storeIntent);
}
})
.show();
}
}
public void startPhotoPicker(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, OTHER_REQUEST);
}
}
private void launchGooglePlus() {
Intent google = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.google_plus_url)));
if (google.resolveActivity(getPackageManager()) != null) {
startActivity(google);
} else {
Crouton.showText(this, R.string.url_error, Style.ALERT);
}
}
public static void openWebPage(Activity activity, Uri webpage) {
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivity(intent);
}
}
public void map() {
String query = ((String) jsonObject.opt("query"));
String dirFrom = (String) jsonObject.opt("directions-from");
String dirTo = (String) jsonObject.opt("directions-to");
String mode = (String) jsonObject.opt("mode");
String avoid = (String) jsonObject.opt("avoid");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0"));
mapIntent.setPackage("com.google.android.apps.maps");
if (query != null) {
query = Uri.encode(query);
mapIntent.setData(Uri.parse("geo:0,0?q="+query));
}
if (dirTo != null && dirFrom == null) {
String directions = "google.navigation:q="+Uri.encode(dirTo);
StringBuilder sb = new StringBuilder(directions);
if (mode != null) {
if (mode.contains("driv")) sb.append("&mode=d");
else if (mode.contains("walk")) sb.append("&mode=w");
else if (mode.contains("bic") || mode.contains("bik")) sb.append("&mode=b");
} else if (avoid != null) {
sb.append("&avoid=");
if (avoid.contains("toll")) sb.append("t");
if (avoid.contains("high")) sb.append("h");
if (avoid.contains("ferr")) sb.append("f");
}
directions = sb.toString();
mapIntent.setData(Uri.parse(directions));
} else if (dirTo != null && dirFrom != null) {
mapIntent.setData(Uri.parse("http://maps.google.com/maps?saddr="+Uri.encode(dirFrom)+"&daddr="+Uri.encode(dirTo)));
}
if (mapIntent.resolveActivity(manager) != null) {
context.startActivity(mapIntent);
} else {
MainActivity.showMessage("Google maps not available on your device", (Activity)context);
}
}
@Override
public boolean onSendButtonClicked(final Feedback feedback) {
final Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT,
mSubject != null ? mSubject : DEFAULT_EMAIL_SUBJECT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
if (mToAddresses != null) {
intent.putExtra(Intent.EXTRA_EMAIL, mToAddresses);
}
if (mCcAddresses != null) {
intent.putExtra(Intent.EXTRA_CC, mCcAddresses);
}
if (mBccAddresses != null) {
intent.putExtra(Intent.EXTRA_BCC, mBccAddresses);
}
}
if (mMimeType != null) {
intent.setType(mMimeType);
}
final StringBuilder body = new StringBuilder();
if (mBodyHeader != null) {
body.append(mBodyHeader).append("\n\n");
}
body.append(feedback.userComment).append("\n\n");
body.append("\n------------\n");
body.append("- Feedback ID: ").append(feedback.id).append("\n");
final Map<CharSequence, Object> additionalData = feedback.getAdditionalData();
if (additionalData != null) {
body.append("\n------ Extra-fields ------\n");
for (final Map.Entry<CharSequence, Object> entry : additionalData.entrySet()) {
body.append("- ")
.append(entry.getKey()).append(": ").
append(entry.getValue()).append("\n");
}
}
body.append("\n------ Application ------\n");
if (feedback.appInfo != null) {
if (feedback.appInfo.applicationId != null) {
body.append("- Application ID: ").append(feedback.appInfo.applicationId).append("\n");
}
if (feedback.appInfo.caller != null) {
body.append("- Activity: ").append(feedback.appInfo.caller).append("\n");
}
if (feedback.appInfo.buildType != null) {
body.append("- Build Type: ").append(feedback.appInfo.buildType).append("\n");
}
if (feedback.appInfo.flavor != null) {
body.append("- Flavor: ").append(feedback.appInfo.flavor).append("\n");
}
if (feedback.appInfo.versionCode != null) {
body.append("- Version Code: ").append(feedback.appInfo.versionCode).append("\n");
}
if (feedback.appInfo.versionName != null) {
body.append("- Version Name: ").append(feedback.appInfo.versionName).append("\n");
}
}
body.append("\n------ Device ------\n");
if (feedback.deviceInfo != null) {
body.append(feedback.deviceInfo.toString());
}
body.append("\n\n");
if (mBodyFooter != null) {
body.append("\n--").append(mBodyFooter);
}
intent.putExtra(Intent.EXTRA_TEXT, body.toString());
final ComponentName componentName = intent.resolveActivity(mContext.getPackageManager());
if (componentName != null) {
//Add screenshot as attachment
final ArrayList<Uri> attachmentsUris = new ArrayList<>();
if (feedback.screenshotFileUri != null) {
//Grant READ permission to the intent
mContext.grantUriPermission(componentName.getPackageName(),
feedback.screenshotFileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
attachmentsUris.add(feedback.screenshotFileUri);
}
//Add logs file as attachment
if (feedback.logsFileUri != null) {
//Grant READ permission to the intent
mContext.grantUriPermission(componentName.getPackageName(),
feedback.logsFileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
attachmentsUris.add(feedback.logsFileUri);
}
if (!attachmentsUris.isEmpty()) {
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachmentsUris);
}
mContext.startActivity(intent);
}
return true;
}
private static boolean canHandleIntent(Context context, Intent intent) {
PackageManager packageManager = context.getPackageManager();
return intent.resolveActivity(packageManager) != null;
}
@Override
public void showFileChooser(ValueCallback<Uri[]> filePathCallback) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = Utils.createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(Constants.TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[] { takePictureIntent };
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
mActivity.startActivityForResult(chooserIntent, 1);
}
static boolean intentHandlerAvailableFor(Context ctx, Intent intent) {
return intent.resolveActivity(ctx.getPackageManager()) != null;
}