下面列出了android.content.Intent#parseUri ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void launchCustomApp(String uri) {
if (uri == null) {
try {
Handler handler = (Handler) XposedHelpers.getObjectField(mPhoneWindowManager, "mHandler");
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, mStrCustomAppNone, Toast.LENGTH_SHORT).show();
}
});
} catch (Throwable t) {
}
return;
}
try {
Intent i = Intent.parseUri(uri, 0);
launchCustomApp(i);
} catch (URISyntaxException e) {
log("launchCustomApp: error parsing uri: " + e.getMessage());
}
}
/**
* Fetches the list of resolve infos from the PackageManager that can handle the URL.
*
* @param context The application context.
* @param url The url to check.
* @return The list of resolve infos found that can handle the URL.
*/
private static List<ResolveInfo> resolveInfosForUrl(Context context, String url) {
Intent intent;
try {
intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
} catch (Exception e) {
return new LinkedList<>();
}
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setComponent(null);
Intent selector = intent.getSelector();
if (selector != null) {
selector.addCategory(Intent.CATEGORY_BROWSABLE);
selector.setComponent(null);
}
return context.getPackageManager().queryIntentActivities(
intent, PackageManager.GET_RESOLVED_FILTER);
}
public static CharSequence getDisplayValue(Context context, String value) {
if (TextUtils.isEmpty(value)) {
return context.getString(R.string.pref_shortcut_default);
}
Intent intent;
try {
intent = Intent.parseUri(value, Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
return context.getString(R.string.pref_shortcut_default);
}
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
if (resolveInfos.size() == 0) {
return null;
}
StringBuilder label = new StringBuilder();
label.append(resolveInfos.get(0).loadLabel(pm));
if (intent.getData() != null && intent.getData().getScheme() != null &&
intent.getData().getScheme().startsWith("http")) {
label.append(": ").append(intent.getDataString());
}
return label;
}
@Override
public void onClick(View v) {
if (mResetCertDecisionsButton == v) {
nativeResetCertDecisions(mNativeConnectionInfoPopup, mWebContents);
mDialog.dismiss();
} else if (mCertificateViewer == v) {
byte[][] certChain = CertificateChainHelper.getCertificateChain(mWebContents);
if (certChain == null) {
// The WebContents may have been destroyed/invalidated. If so,
// ignore this request.
return;
}
CertificateViewer.showCertificateChain(mContext, certChain);
} else if (mMoreInfoLink == v) {
mDialog.dismiss();
try {
Intent i = Intent.parseUri(mLinkUrl, Intent.URI_INTENT_SCHEME);
i.putExtra(Browser.EXTRA_CREATE_NEW_TAB, true);
i.putExtra(Browser.EXTRA_APPLICATION_ID, mContext.getPackageName());
mContext.startActivity(i);
} catch (Exception ex) {
// Do nothing intentionally.
Log.w(TAG, "Bad URI %s", mLinkUrl, ex);
}
}
}
private void openApp(String url) {
Intent intent;
try {
intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
XUtil.getContext().startActivity(intent);
} catch (Exception e) {
XToastUtils.error("您所打开的第三方App未安装!");
}
}
@Override
protected Intent parseIntent(XmlResourceParser parser) {
String uri;
try {
uri = getAttributeValue(parser, ATTR_URI);
return Intent.parseUri(uri, 0);
} catch (URISyntaxException e) {
e.printStackTrace();
return null; // Oh well
}
}
public static Intent getIntentValue(String value, Intent defaultIntent) {
try {
if (TextUtils.isEmpty(value)) {
return defaultIntent;
}
return Intent.parseUri(value, Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
return defaultIntent;
}
}
/**
* Creates intent to launch a WebAPK.
* @param webApkPackageName Package name of the WebAPK to launch.
* @param url URL to navigate WebAPK to.
* @param forceNavigation Whether the WebAPK should be navigated to the url if the WebAPK is
* already open. If {@link forceNavigation} is false and the WebAPK is already running,
* the WebAPK will be brought to the foreground.
* @return The intent.
*/
public static Intent createLaunchWebApkIntent(
String webApkPackageName, String url, boolean forceNavigation) {
Intent intent;
try {
intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
} catch (Exception e) {
return null;
}
intent.setPackage(webApkPackageName);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(WebApkConstants.EXTRA_WEBAPK_FORCE_NAVIGATION, forceNavigation);
return intent;
}
public static Intent getIntentFromString(String string) {
try {
return Intent.parseUri(string, 0);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static boolean startIntentUrl(Activity activity, String intentFullUrl) {
try {
Intent intent = Intent.parseUri(
intentFullUrl,
Intent.URI_INTENT_SCHEME
);
activity.startActivity(intent);
return true;
} catch (URISyntaxException e) {
e.printStackTrace();
return false;
}
}
public Intent getIntent() {
Intent intent = null;
try {
intent = Intent.parseUri(action, Intent.URI_INTENT_SCHEME);
intent.putExtra(Observations.Contract.ID, id);
intent.putExtra(Observations.Contract.CONCEPT, concept);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return intent;
}
/**
* Determines whether the URL needs to be sent as an intent to the system,
* and sends it, if appropriate.
* @return Whether the URL generated an intent, caused a navigation in
* current tab, or wasn't handled at all.
*/
public OverrideUrlLoadingResult shouldOverrideUrlLoading(ExternalNavigationParams params) {
Intent intent;
// Perform generic parsing of the URI to turn it into an Intent.
try {
intent = Intent.parseUri(params.getUrl(), Intent.URI_INTENT_SCHEME);
} catch (Exception ex) {
Log.w(TAG, "Bad URI %s", params.getUrl(), ex);
return OverrideUrlLoadingResult.NO_OVERRIDE;
}
boolean hasBrowserFallbackUrl = false;
String browserFallbackUrl =
IntentUtils.safeGetStringExtra(intent, EXTRA_BROWSER_FALLBACK_URL);
if (browserFallbackUrl != null
&& UrlUtilities.isValidForIntentFallbackNavigation(browserFallbackUrl)) {
hasBrowserFallbackUrl = true;
} else {
browserFallbackUrl = null;
}
long time = SystemClock.elapsedRealtime();
OverrideUrlLoadingResult result = shouldOverrideUrlLoadingInternal(
params, intent, hasBrowserFallbackUrl, browserFallbackUrl);
RecordHistogram.recordTimesHistogram("Android.StrictMode.OverrideUrlLoadingTime",
SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS);
if (result == OverrideUrlLoadingResult.NO_OVERRIDE && hasBrowserFallbackUrl
&& (params.getRedirectHandler() == null
// For instance, if this is a chained fallback URL, we ignore it.
|| !params.getRedirectHandler().shouldNotOverrideUrlLoading())) {
return clobberCurrentTabWithFallbackUrl(browserFallbackUrl, params);
}
return result;
}
@Override
public void onClick(View v) {
mDialog.dismiss();
if (mCertificateViewer == v) {
byte[][] certChain = nativeGetCertificateChain(mContentViewCore);
CertificateViewer.showCertificateChain(mContext, certChain);
} else if (mMoreInfoLink == v) {
try {
Intent i = Intent.parseUri(mLinkUrl, Intent.URI_INTENT_SCHEME);
i.putExtra(Browser.EXTRA_CREATE_NEW_TAB, true);
i.putExtra(Browser.EXTRA_APPLICATION_ID, mContext.getPackageName());
mContext.startActivity(i);
} catch (URISyntaxException ex) {}
}
}
/**
* @return Whether the |url| could be handled by an external application on the system.
*/
public boolean canExternalAppHandleUrl(String url) {
if (url.startsWith(SCHEME_WTAI_MC)) return true;
try {
Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
if (intent.getPackage() != null) return true;
List<ResolveInfo> resolvingInfos = mDelegate.queryIntentActivities(intent);
if (resolvingInfos != null && resolvingInfos.size() > 0) return true;
} catch (Exception ex) {
// Ignore the error.
Log.w(TAG, "Bad URI %s", url, ex);
}
return false;
}
/**
* 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;
}
}
private void resolveIntent() {
try {
mIntent = Intent.parseUri(mQuickActionUri, 0);
} catch (URISyntaxException e) {
// If the intent cannot be parsed, there is no quick action available.
ContextualSearchUma.logQuickActionIntentResolution(mQuickActionCategory, 0);
reset();
return;
}
PackageManager packageManager = mContext.getPackageManager();
// If a default is set, PackageManager#resolveActivity() will return the ResolveInfo
// for the default activity.
ResolveInfo possibleDefaultActivity = packageManager.resolveActivity(mIntent, 0);
// PackageManager#queryIntentActivities() will return a list of activities that can handle
// the intent, sorted from best to worst. If there are no matching activities, an empty
// list is returned.
List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(
mIntent, 0);
int numMatchingActivities = 0;
ResolveInfo defaultActivityResolveInfo = null;
for (ResolveInfo resolveInfo : resolveInfoList) {
// TODO(twellington): do not count browser activities as a match?
if (resolveInfo.activityInfo != null && resolveInfo.activityInfo.exported) {
numMatchingActivities++;
// Return early if this resolveInfo matches the possibleDefaultActivity.
ActivityInfo possibleDefaultActivityInfo = possibleDefaultActivity.activityInfo;
if (possibleDefaultActivityInfo == null) continue;
ActivityInfo resolveActivityInfo = resolveInfo.activityInfo;
boolean matchesPossibleDefaultActivity =
TextUtils.equals(resolveActivityInfo.name,
possibleDefaultActivityInfo.name)
&& TextUtils.equals(resolveActivityInfo.packageName,
possibleDefaultActivityInfo.packageName);
if (matchesPossibleDefaultActivity) {
defaultActivityResolveInfo = resolveInfo;
break;
}
}
}
ContextualSearchUma.logQuickActionIntentResolution(mQuickActionCategory,
numMatchingActivities);
if (numMatchingActivities == 0) {
reset();
return;
}
mHasQuickAction = true;
Drawable iconDrawable = null;
int iconResId = 0;
if (defaultActivityResolveInfo != null) {
iconDrawable = defaultActivityResolveInfo.loadIcon(mContext.getPackageManager());
if (mQuickActionCategory != QuickActionCategory.PHONE) {
// Use the default app's name to construct the caption.
mCaption = mContext.getResources().getString(
DEFAULT_APP_CAPTION_MAP.get(mQuickActionCategory),
defaultActivityResolveInfo.loadLabel(packageManager));
} else {
// The caption for phone numbers does not use the app's name.
mCaption = mContext.getResources().getString(
DEFAULT_APP_CAPTION_MAP.get(mQuickActionCategory));
}
} else {
iconResId = ICON_MAP.get(mQuickActionCategory);
mCaption = mContext.getResources().getString(
FALLBACK_CAPTION_MAP.get(mQuickActionCategory));
}
inflate();
if (iconDrawable != null) {
((ImageView) getView()).setImageDrawable(iconDrawable);
} else {
((ImageView) getView()).setImageResource(iconResId);
}
invalidate();
}
@Override
protected long invalidPackageOrClass(XmlResourceParser parser) {
final String uri = getAttributeValue(parser, ATTR_URI);
if (TextUtils.isEmpty(uri)) {
return -1;
}
final Intent metaIntent;
try {
metaIntent = Intent.parseUri(uri, 0);
} catch (URISyntaxException e) {
e.printStackTrace();
return -1;
}
ResolveInfo resolved = mPackageManager.resolveActivity(metaIntent,
PackageManager.MATCH_DEFAULT_ONLY);
final List<ResolveInfo> appList = mPackageManager.queryIntentActivities(
metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
// Verify that the result is an app and not just the resolver dialog asking which
// app to use.
if (wouldLaunchResolverActivity(resolved, appList)) {
// If only one of the results is a system app then choose that as the default.
final ResolveInfo systemApp = getSingleSystemActivity(appList);
if (systemApp == null) {
// There is no logical choice for this meta-favorite, so rather than making
// a bad choice just add nothing.
return -1;
}
resolved = systemApp;
}
final ActivityInfo info = resolved.activityInfo;
final Intent intent = mPackageManager.getLaunchIntentForPackage(info.packageName);
if (intent == null) {
return -1;
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
return addShortcut(info.loadLabel(mPackageManager).toString(), intent,
Favorites.ITEM_TYPE_APPLICATION);
}
/** A Volume {@link android.view.KeyEvent} has been long pressed. */
public void onVolumeLongPress(KeyEvent event) {
if (null == event) return;
// Set the action based on the KeyEvent.
String longPressAction = null;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_VOLUME_UP:
longPressAction = longPressActionUp;
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:
longPressAction = longPressActionDown;
break;
}
// If the event was volume up/ down, handle it. If the user is currently
// in the middle of a call, only handle volume up/ down events.
LOGI("VolumePanel", "onVolumeLongPress(" + event.getKeyCode() + ") action=" + longPressAction);
boolean callIdle = (mCallState == TelephonyManager.CALL_STATE_IDLE);
if (!TextUtils.isEmpty(longPressAction) && callIdle) {
try {
Intent action = Intent.parseUri(longPressAction, Intent.URI_INTENT_SCHEME);
startActivity(action);
} catch (URISyntaxException e) {
LOGE("VolumePanel", "Error parsing long press action as an Intent.", e);
}
} else {
// If we don't have a long press event, use this timeout as
// a key timeout for volume manipulation.
final int adjust = ((event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) ?
AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER);
int flags = getFlags(lastStreamType);
flags &= ~FLAG_PLAY_SOUND;
flags &= ~FLAG_VIBRATE;
// Adjust stream volume, but avoid making noises continuously.
int stream = lastStreamType;
if (hasDefaultStream()) stream = defaultStream;
boolean ringerAffected = mAudioHelper.isStreamAffectedByRingerMode(stream);
// Ringer mode transition for long-press actions
/*if (ringerAffected) {
int volume = getStreamVolume(stream);
// If we're already at silent, stop listening.
if ((adjust == ADJUST_LOWER) && (volume == 0) &&
(mRingerMode == AudioManager.RINGER_MODE_SILENT)) {
return;
} else if (adjust == ADJUST_RAISE && volume == 0) {
int nextRinger = Utils.nextRingerMode(adjust, mRingerMode);
mAudioManager.setRingerMode(nextRinger);
}
}*/
LOGI("VolumePanel", "[stream=" + stream + ", lastStream=" + lastStreamType +
", ringerAffected=" + ringerAffected + ']');
adjustSuggestedStreamVolume(adjust, stream, flags);
mVolumeDirty = true; // This is needed to show our volume change!
mIgnoreNextKeyUp = false; // This is key to avoid infinite loops!
if (!noLongPress || hasLongPressAction(event.getKeyCode())) {
mHandler.sendMessageDelayed(mHandler.obtainMessage(
MSG_VOLUME_LONG_PRESS, event), (mLongPressTimeout / 3));
}
show();
}
}
@Override
protected Intent handleOk(Intent request, Intent response) {
int requestCode = (request != null)
? Intents.parseActionDescriptor(request) : Intents.NULL;
Uri uri = (response != null) ? response.getData() : Uri.EMPTY;
Logf.D(TAG, "handleOk(Intent)", "requestCode: " + requestCode
+ ", response descriptor: " + Uris.getDescriptor(uri));
boolean m = false;
// determine and return what replaces the top of the stack
switch (requestCode) {
case Intents.NULL:
Logf.D(TAG, "handleOk(Intent)", "....at NULL");
// If stack was empty send finish code
if (request == null) {
Logf.D(TAG, ".... Empty stack or unrecognizable Uri");
return new Intent(Intents.ACTION_FINISH);
} else {
Logf.D(TAG, "handleOk(Intent)", ".... Returning to pick activity");
return goTo(Intents.PICK_ACTIVITY);
}
case Intents.MAIN:
Logf.D(TAG, "handleOk(Intent)", "....at MAIN");
// MAIN should be root of stack so we
return PICK_OBSERVER;
case Intents.PICK_ACTIVITY:
Logf.D(TAG, "handleOk(Intent)", "....at PICK_ACTIVITY");
// the returned intent should hold the next intent to launch as
// the data
try {
return Intent.parseUri(response.getDataString(),
Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
e.printStackTrace();
throw new IllegalArgumentException(e);
}
case Intents.INSERT:
if (!m) Logf.D(TAG, "handleOk(Intent)", "....at INSERT");
m = true;
case Intents.INSERT_OR_EDIT:
if (!m) Logf.D(TAG, "handleOk(Intent)", "....at INSERT_OR_EDIT");
m = true;
case Intents.PICK:
if (!m) Logf.D(TAG, "handleOk(Intent)", "....at PICK");
m = true;
// content pick intent we should get data back
switch (Uris.getDescriptor(uri)) {
case Uris.OBSERVER_ITEM:
case Uris.OBSERVER_UUID:
Logf.D(TAG, "handleOk(Intent)", "....at PICK Observer-Selected");
return new Intent(Intents.ACTION_PICK_ACTIVITY);
case Uris.SUBJECT_ITEM:
case Uris.SUBJECT_UUID:
Logf.D(TAG, "handleOk(Intent)", "....at PICK Subject-Selected");
return PICK_PROCEDURE;
case Uris.ENCOUNTER_ITEM:
case Uris.ENCOUNTER_UUID:
Logf.D(TAG, "handleOk(Intent)", "....at PICK Procedure-Selected");
// require the subject to be set
return new Intent(Intent.ACTION_VIEW, uri);
case Uris.NOTIFICATION_ITEM:
case Uris.NOTIFICATION_UUID:
Logf.D(TAG, "handleOk(Intent)", "....at PICK Notification-Selected");
// require the subject to be set
return new Intent(Intent.ACTION_VIEW, uri);
case Uris.PROCEDURE_ITEM:
case Uris.PROCEDURE_UUID:
Logf.D(TAG, "handleOk(Intent)", "....at PICK Procedure-Selected");
// require the subject to be set
return new Intent(Intent.ACTION_VIEW, uri);
// DIR should indicate create new
case Uris.SUBJECT_DIR:
Logf.D(TAG, "handleOk(Intent)", "....at PICK Subject-None Picked");
default:
return goTo(Intents.PICK_ACTIVITY);
}
case Intents.VIEW:
// return to the predecessor of the view
Logf.D(TAG, "....at VIEW");
return goTo(Intents.PICK_ACTIVITY);
}
// Return the result intent back to the top
// stack should never be empty here
return goTo(Intents.PICK_ACTIVITY);
}
public static void startActivity(Context activity,String intentUri) throws URISyntaxException,ActivityNotFoundException {
Intent intent = Intent.parseUri(intentUri,Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
if(intent!= null){
activity.startActivity(intent);
}else {
throw new ActivityNotFoundException();
}
}