下面列出了android.content.Intent#createChooser ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Subscribe
public void onShareAnecdote(ShareAnecdoteEvent event) {
if (mApplication == null) return;
EventTracker.trackAnecdoteShare(event.websiteName);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(
Intent.EXTRA_SUBJECT,
mApplication.getString(R.string.app_name));
sharingIntent.putExtra(
Intent.EXTRA_TEXT,
event.shareString);
Intent startIntent =Intent.createChooser(
sharingIntent,
mApplication.getResources().getString(R.string.anecdote_share_title));
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mApplication.startActivity(startIntent);
}
public static Intent createEmailOnlyChooserIntent(Context context, Intent source,
CharSequence chooserTitle) {
Stack<Intent> intents = new Stack<>();
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
"[email protected]", null));
List<ResolveInfo> activities = context.getPackageManager()
.queryIntentActivities(i, 0);
for (ResolveInfo ri : activities) {
Intent target = new Intent(source);
target.setPackage(ri.activityInfo.packageName);
intents.add(target);
}
if (!intents.isEmpty()) {
Intent chooserIntent = Intent.createChooser(intents.remove(0),
chooserTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
intents.toArray(new Parcelable[intents.size()]));
return chooserIntent;
} else {
return Intent.createChooser(source, chooserTitle);
}
}
public void startPhotoPickerIntent(ValueCallback<Uri> filePathCallback, String acceptType) {
filePathCallbackLegacy = filePathCallback;
Intent fileChooserIntent = getFileChooserIntent(acceptType);
Intent chooserIntent = Intent.createChooser(fileChooserIntent, "");
ArrayList<Parcelable> extraIntents = new ArrayList<>();
if (acceptsImages(acceptType)) {
extraIntents.add(getPhotoIntent());
}
if (acceptsVideo(acceptType)) {
extraIntents.add(getVideoIntent());
}
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents.toArray(new Parcelable[]{}));
if (chooserIntent.resolveActivity(getCurrentActivity().getPackageManager()) != null) {
getCurrentActivity().startActivityForResult(chooserIntent, PICKER_LEGACY);
} else {
Log.w("Web3WevbiewModule", "there is no Activity to handle this Intent");
}
}
private void openResult() {
String path = mEditOutPath.getText().toString();
if (!path.isEmpty()) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File(path);
Uri url = FileProvider.getUriForFile(getContext(),
getContext().getPackageName() + ".fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(url, "text/plain");
Intent chooser = Intent.createChooser(intent, "Choose an application to open with:");
startActivity(chooser);
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
private void pickImage() {
List<Intent> cameraIntents = new ArrayList<Intent>();
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.temp_photo_name_with_date).replace("%s", String.valueOf(System.currentTimeMillis())));
imageToUploadUri = Uri.fromFile(file);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageToUploadUri);
cameraIntents.add(captureIntent);
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.image_picker_title));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, ADD_PHOTO);
}
private void sendLogFile(Location logLocation)
{
Context ctx = getActivity();
Uri uri = MainContentProvider.getContentUriFromLocation(logLocation);
Intent actionIntent = new Intent(Intent.ACTION_SEND);
actionIntent.setType("text/plain");
actionIntent.putExtra(Intent.EXTRA_STREAM, uri);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
ClipData cp = ClipData.newUri(
ctx.getContentResolver(),
ctx.getString(R.string.get_program_log),
uri
);
actionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
actionIntent.setClipData(cp);
}
Intent startIntent = Intent.createChooser(
actionIntent,
ctx.getString(R.string.save_log_file_to)
);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(startIntent);
}
@Override
public void handleMessage(Message msg) {
String logsText = parseLogsToText();
if (logsText == null) {
stopSelf(msg.arg1);
return;
}
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, logsText);
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, getResources().getString(R.string.app_name_EFR_Connect) + " LOGS");
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(shareIntent);
stopSelf(msg.arg1);
}
private void pickImage() {
pickedPhotoForContactUri = null;
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.temp_photo_name));
pickedPhotoForContactUri = Uri.fromFile(file);
captureIntent.putExtra("outputX", PHOTO_SIZE);
captureIntent.putExtra("outputY", PHOTO_SIZE);
captureIntent.putExtra("aspectX", 0);
captureIntent.putExtra("aspectY", 0);
captureIntent.putExtra("scale", true);
captureIntent.putExtra("return-data", false);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, pickedPhotoForContactUri);
cameraIntents.add(captureIntent);
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.image_picker_title));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, ADD_PHOTO);
}
public void selectUploadFile(View view) {
Intent target = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(target,
this.getString(R.string.choose_file));
try {
this.startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException ex) {
}
}
public void selectUploadFile(View view) {
Intent target = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(target,
this.getString(R.string.choose_file));
try {
this.startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException ex) {
}
}
private static Intent createChooserIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
return Intent.createChooser(intent, null);
}
@Override
public void shareImage(Intent shareIntent){
Intent intent2 = Intent.createChooser(shareIntent, getString(R.string.share_via));
/** From version 24 we need to take file read permission */
if(Build.VERSION.SDK_INT>=24){
intent2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivityForResult(intent2, SHARE_IMAGE_REQUEST_CODE);
}
/**
* Open a chooser dialog to send text content to other apps.
*
* Refer http://developer.android.com/intl/ko/training/sharing/send.html
*
* @param content the data to send
* @param dialogTitle the title of the chooser dialog
*/
@ReactMethod
public void share(ReadableMap content, String dialogTitle, Promise promise) {
if (content == null) {
promise.reject(ERROR_INVALID_CONTENT, "Content cannot be null");
return;
}
try {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setTypeAndNormalize("text/plain");
if (content.hasKey("title")) {
intent.putExtra(Intent.EXTRA_SUBJECT, content.getString("title"));
}
if (content.hasKey("message")) {
intent.putExtra(Intent.EXTRA_TEXT, content.getString("message"));
}
Intent chooser = Intent.createChooser(intent, dialogTitle);
chooser.addCategory(Intent.CATEGORY_DEFAULT);
Activity currentActivity = getCurrentActivity();
if (currentActivity != null) {
currentActivity.startActivity(chooser);
} else {
getReactApplicationContext().startActivity(chooser);
}
WritableMap result = Arguments.createMap();
result.putString("action", ACTION_SHARED);
promise.resolve(result);
} catch (Exception e) {
promise.reject(ERROR_UNABLE_TO_OPEN_DIALOG, "Failed to open share dialog");
}
}
public void chooseFile(CallbackContext callbackContext) {
// type and title should be configurable
Context context=this.cordova.getActivity().getApplicationContext();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setClass(context,FileChooserActivity.class);
Intent chooser = Intent.createChooser(intent, "Select File");
cordova.startActivityForResult(this, chooser, PICK_FILE_REQUEST);
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callback = callbackContext;
callbackContext.sendPluginResult(pluginResult);
}
public void selectUploadFile(View view) {
Intent target = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(target,
this.getString(R.string.choose_file));
try {
this.startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException ex) {
}
}
Intent createChooserIntent(@NonNull Intent intent, @NonNull String title) {
return Intent.createChooser(intent, title);
}
private static Intent createActivityChooserIntent(Context context, Intent intent,
Uri uri, List<String> ignorPackageList) {
final PackageManager pm = context.getPackageManager();
final List<ResolveInfo> activities = pm.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
final ArrayList<Intent> chooserIntents = new ArrayList<>();
final String ourPackageName = context.getPackageName();
Collections.sort(activities, new ResolveInfo.DisplayNameComparator(pm));
for (ResolveInfo resInfo : activities) {
ActivityInfo info = resInfo.activityInfo;
if (!info.enabled || !info.exported) {
continue;
}
if (info.packageName.equals(ourPackageName)) {
continue;
}
if (ignorPackageList != null && ignorPackageList.contains(info.packageName)) {
continue;
}
Intent targetIntent = new Intent(intent);
targetIntent.setPackage(info.packageName);
targetIntent.setDataAndType(uri, intent.getType());
chooserIntents.add(targetIntent);
}
if (chooserIntents.isEmpty()) {
return null;
}
final Intent lastIntent = chooserIntents.remove(chooserIntents.size() - 1);
if (chooserIntents.isEmpty()) {
// there was only one, no need to showImage the chooser
return lastIntent;
}
Intent chooserIntent = Intent.createChooser(lastIntent, null);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
chooserIntents.toArray(new Intent[chooserIntents.size()]));
return chooserIntent;
}
/**
* Find and open the appropriate app for a given Uri. If appropriate, let the user select between
* multiple supported apps. Returns a boolean indicating whether the URL was handled. A fallback
* URL will be opened in the supplied WebView if appropriate (in which case the URL was handled,
* and true will also be returned). If not handled, we should fall back to webviews error handling
* (which ends up calling our error handling code as needed).
*
* Note: this method "leaks" the target Uri to Android before asking the user whether they
* want to use an external app to open the uri. Ultimately the OS can spy on anything we're
* doing in the app, so this isn't an actual "bug".
*/
public static boolean handleExternalUri(final Context context, final IWebView webView, final String uri) {
// This code is largely based on Fennec's ExternalIntentDuringPrivateBrowsingPromptFragment.java
final Intent intent;
try {
intent = Intent.parseUri(uri, 0);
} catch (URISyntaxException e) {
// Let the browser handle the url (i.e. let the browser show it's unsupported protocol /
// invalid URL page).
return false;
}
// Since we're a browser:
intent.addCategory(Intent.CATEGORY_BROWSABLE);
final PackageManager packageManager = context.getPackageManager();
// This is where we "leak" the uri to the OS. If we're using the system webview, then the OS
// already knows that we're opening this uri. Even if we're using GeckoView, the OS can still
// see what domains we're visiting, so there's no loss of privacy here:
final List<ResolveInfo> matchingActivities = packageManager.queryIntentActivities(intent, 0);
if (matchingActivities.size() == 0) {
return handleUnsupportedLink(webView, intent);
} else if (matchingActivities.size() == 1) {
final ResolveInfo info;
if (matchingActivities.size() == 1) {
info = matchingActivities.get(0);
} else {
// Ordering isn't guaranteed if there is more than one available activity - hence
// we fetch the default (this code isn't currently run because we handle the > 1
// case separately, but would be needed if we ever decide to prefer the default
// app for the > 1 case.
info = packageManager.resolveActivity(intent, 0);
}
final CharSequence externalAppTitle = info.loadLabel(packageManager);
showConfirmationDialog(context, intent, context.getString(R.string.external_app_prompt_title), R.string.external_app_prompt, externalAppTitle);
return true;
} else { // matchingActivities.size() > 1
// By explicitly showing the chooser, we can avoid having a (default) app from opening
// the link immediately. This isn't perfect - we'd prefer to highlight the default app,
// but it's not clear if there's any way of doing that. An alternative
// would be to reuse the same dialog as for the single-activity case, and offer
// a "open in other app this time" button if we have more than one matchingActivity.
final String chooserTitle = context.getString(R.string.external_multiple_apps_matched_exit);
final Intent chooserIntent = Intent.createChooser(intent, chooserTitle);
context.startActivity(chooserIntent);
return true;
}
}
/**
* Creates an Intent that allows viewing the given file in an internal media viewer.
* @param fileUri URI pointing at the file, ideally in file:// form. Used only when
* the media viewer is trying to locate the file on disk.
* @param contentUri content:// URI pointing at the file.
* @param mimeType MIME type of the file.
* @return Intent that can be fired to open the file.
*/
public static Intent getMediaViewerIntentForDownloadItem(
Uri fileUri, Uri contentUri, String mimeType) {
Context context = ContextUtils.getApplicationContext();
Intent viewIntent = createViewIntentForDownloadItem(contentUri, mimeType);
Bitmap closeIcon = BitmapFactory.decodeResource(
context.getResources(), R.drawable.ic_arrow_back_white_24dp);
Bitmap shareIcon = BitmapFactory.decodeResource(
context.getResources(), R.drawable.ic_share_white_24dp);
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setToolbarColor(Color.BLACK);
builder.setCloseButtonIcon(closeIcon);
builder.setShowTitle(true);
// Create a PendingIntent that can be used to view the file externally.
// TODO(dfalcantara): Check if this is problematic in multi-window mode, where two
// different viewers could be visible at the same time.
Intent chooserIntent = Intent.createChooser(viewIntent, null);
chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String openWithStr = context.getString(R.string.download_manager_open_with);
PendingIntent pendingViewIntent = PendingIntent.getActivity(
context, 0, chooserIntent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.addMenuItem(openWithStr, pendingViewIntent);
// Create a PendingIntent that shares the file with external apps.
PendingIntent pendingShareIntent = PendingIntent.getActivity(
context, 0, createShareIntent(contentUri, mimeType), 0);
builder.setActionButton(
shareIcon, context.getString(R.string.share), pendingShareIntent, true);
// The color of the media viewer is dependent on the file type.
int backgroundRes;
if (DownloadFilter.fromMimeType(mimeType) == DownloadFilter.FILTER_IMAGE) {
backgroundRes = R.color.image_viewer_bg;
} else {
backgroundRes = R.color.media_viewer_bg;
}
int mediaColor = ApiCompatibilityUtils.getColor(context.getResources(), backgroundRes);
// Build up the Intent further.
Intent intent = builder.build().intent;
intent.setPackage(context.getPackageName());
intent.setData(contentUri);
intent.putExtra(CustomTabIntentDataProvider.EXTRA_IS_MEDIA_VIEWER, true);
intent.putExtra(CustomTabIntentDataProvider.EXTRA_MEDIA_VIEWER_URL, fileUri.toString());
intent.putExtra(CustomTabIntentDataProvider.EXTRA_ENABLE_EMBEDDED_MEDIA_EXPERIENCE, true);
intent.putExtra(
CustomTabIntentDataProvider.EXTRA_INITIAL_BACKGROUND_COLOR, mediaColor);
intent.putExtra(
CustomTabsIntent.EXTRA_TOOLBAR_COLOR, mediaColor);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
IntentHandler.addTrustedIntentExtras(intent);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(context, ChromeLauncherActivity.class);
return intent;
}
private Intent getImageUri() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
return Intent.createChooser(intent, "Select Picture");
}