下面列出了怎么用android.provider.Browser的API类实例代码及写法,或者点击链接到github查看源代码。
private static void openUrl(Activity activity, String url, ComponentName componentName) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.putExtra(Browser.EXTRA_APPLICATION_ID,
activity.getApplicationContext().getPackageName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (componentName != null) {
intent.setComponent(componentName);
} else {
// If the bookmark manager is shown in a tab on a phone (rather than in a separate
// activity) the component name may be null. Send the intent through
// ChromeLauncherActivity instead to avoid crashing. See crbug.com/615012.
intent.setClass(activity, ChromeLauncherActivity.class);
}
IntentHandler.startActivityForTrustedIntent(intent, activity);
}
/**
* @return Intent that tells Chrome to bring an Activity for a particular Tab back to the
* foreground, or null if this isn't possible.
*/
public static Intent createBringTabToFrontIntent(int tabId) {
// Iterate through all {@link CustomTab}s and check whether the given tabId belongs to a
// {@link CustomTab}. If so, return null as the client app's task cannot be foregrounded.
List<WeakReference<Activity>> list = ApplicationStatus.getRunningActivities();
for (WeakReference<Activity> ref : list) {
Activity activity = ref.get();
if (activity instanceof CustomTabActivity
&& ((CustomTabActivity) activity).getActivityTab() != null
&& tabId == ((CustomTabActivity) activity).getActivityTab().getId()) {
return null;
}
}
String packageName = ContextUtils.getApplicationContext().getPackageName();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, packageName);
intent.putExtra(TabOpenType.BRING_TAB_TO_FRONT.name(), tabId);
intent.setPackage(packageName);
return intent;
}
/**
* Returns a String (or null) containing the extra headers sent by the intent, if any.
*
* This methods skips the referrer header.
*
* @param intent The intent containing the bundle extra with the HTTP headers.
*/
public static String getExtraHeadersFromIntent(Intent intent) {
Bundle bundleExtraHeaders = IntentUtils.safeGetBundleExtra(intent, Browser.EXTRA_HEADERS);
if (bundleExtraHeaders == null) return null;
StringBuilder extraHeaders = new StringBuilder();
Iterator<String> keys = bundleExtraHeaders.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = bundleExtraHeaders.getString(key);
if ("referer".equals(key.toLowerCase(Locale.US))) continue;
if (extraHeaders.length() != 0) extraHeaders.append("\n");
extraHeaders.append(key);
extraHeaders.append(": ");
extraHeaders.append(value);
}
return extraHeaders.length() == 0 ? null : extraHeaders.toString();
}
/**
* Returns a String (or null) containing the extra headers sent by the intent, if any.
*
* This methods skips the referrer header.
*
* @param intent The intent containing the bundle extra with the HTTP headers.
*/
public static String getExtraHeadersFromIntent(Intent intent) {
Bundle bundleExtraHeaders = IntentUtils.safeGetBundleExtra(intent, Browser.EXTRA_HEADERS);
if (bundleExtraHeaders == null) return null;
StringBuilder extraHeaders = new StringBuilder();
Iterator<String> keys = bundleExtraHeaders.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = bundleExtraHeaders.getString(key);
if ("referer".equals(key.toLowerCase(Locale.US))) continue;
if (extraHeaders.length() != 0) extraHeaders.append("\n");
extraHeaders.append(key);
extraHeaders.append(": ");
extraHeaders.append(value);
}
return extraHeaders.length() == 0 ? null : extraHeaders.toString();
}
/**
* Creates a webclip on the device home screen.
* @param url - URL should be passed in as a String.
* @param title - Title(Web app title) should be passed in as a String.
*/
public void createWebAppBookmark(String url, String title) {
final Intent bookmarkIntent = new Intent();
final Intent actionIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
long urlHash = url.hashCode();
long uniqueId = (urlHash << MAX_URL_HASH) | actionIntent.hashCode();
actionIntent.putExtra(Browser.EXTRA_APPLICATION_ID, Long.toString(uniqueId));
bookmarkIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, actionIntent);
bookmarkIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
bookmarkIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(context,
R.drawable.ic_bookmark)
);
bookmarkIntent.setAction(resources.getString(R.string.application_package_launcher_action));
context.sendBroadcast(bookmarkIntent);
}
private static void openUrl(Activity activity, String url, ComponentName componentName) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.putExtra(Browser.EXTRA_APPLICATION_ID,
activity.getApplicationContext().getPackageName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(IntentHandler.EXTRA_PAGE_TRANSITION_TYPE, PageTransition.AUTO_BOOKMARK);
if (componentName != null) {
intent.setComponent(componentName);
} else {
// If the bookmark manager is shown in a tab on a phone (rather than in a separate
// activity) the component name may be null. Send the intent through
// ChromeLauncherActivity instead to avoid crashing. See crbug.com/615012.
intent.setClass(activity, ChromeLauncherActivity.class);
}
IntentHandler.startActivityForTrustedIntent(intent, activity);
}
/**
* Sends the intent associated with the quick action if one is available.
*/
public void sendIntent() {
if (mIntent == null) return;
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Set the Browser application ID to us in case the user chooses Chrome
// as the app from the intent picker.
Context context = getContext();
mIntent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
mIntent.putExtra(Browser.EXTRA_CREATE_NEW_TAB, true);
if (context instanceof ChromeTabbedActivity2) {
// Set the window ID so the new tab opens in the correct window.
mIntent.putExtra(IntentHandler.EXTRA_WINDOW_ID, 2);
}
IntentUtils.safeStartActivity(mContext, mIntent);
}
private void loadBookmarks() {
Log.i(TAG, "Entered loadBookmarks()");
String text = "";
Cursor query = getContentResolver().query(Browser.BOOKMARKS_URI,
projection, null, null, null);
query.moveToFirst();
while (query.moveToNext()) {
text += query.getString(query
.getColumnIndex(Browser.BookmarkColumns.TITLE));
text += "\n";
text += query.getString(query
.getColumnIndex(Browser.BookmarkColumns.URL));
text += "\n\n";
}
TextView box = (TextView) findViewById(R.id.text);
box.setText(text);
Log.i(TAG, "Bookmarks loaded");
}
private long addBookmark(ContentValues values) {
String url = values.getAsString(Browser.BookmarkColumns.URL);
String title = values.getAsString(Browser.BookmarkColumns.TITLE);
boolean isFolder = false;
if (values.containsKey(BOOKMARK_IS_FOLDER_PARAM)) {
isFolder = values.getAsBoolean(BOOKMARK_IS_FOLDER_PARAM);
}
long parentId = INVALID_BOOKMARK_ID;
if (values.containsKey(BOOKMARK_PARENT_ID_PARAM)) {
parentId = values.getAsLong(BOOKMARK_PARENT_ID_PARAM);
}
long id = nativeAddBookmark(mNativeChromeBrowserProvider, url, title, isFolder, parentId);
if (id == INVALID_BOOKMARK_ID) return id;
if (isFolder) {
updateLastModifiedBookmarkFolder(id);
} else {
updateLastModifiedBookmarkFolder(parentId);
}
return id;
}
/**
* @return Intent that tells Chrome to bring an Activity for a particular Tab back to the
* foreground, or null if this isn't possible.
*/
@Nullable
public static Intent createBringTabToFrontIntent(int tabId) {
// Iterate through all {@link CustomTab}s and check whether the given tabId belongs to a
// {@link CustomTab}. If so, return null as the client app's task cannot be foregrounded.
List<WeakReference<Activity>> list = ApplicationStatus.getRunningActivities();
for (WeakReference<Activity> ref : list) {
Activity activity = ref.get();
if (activity instanceof CustomTabActivity
&& ((CustomTabActivity) activity).getActivityTab() != null
&& tabId == ((CustomTabActivity) activity).getActivityTab().getId()) {
return null;
}
}
String packageName = ContextUtils.getApplicationContext().getPackageName();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, packageName);
intent.putExtra(TabOpenType.BRING_TAB_TO_FRONT.name(), tabId);
intent.setPackage(packageName);
return intent;
}
/**
* Returns a String (or null) containing the extra headers sent by the intent, if any.
*
* This methods skips the referrer header.
*
* @param intent The intent containing the bundle extra with the HTTP headers.
*/
public static String getExtraHeadersFromIntent(Intent intent) {
Bundle bundleExtraHeaders = IntentUtils.safeGetBundleExtra(intent, Browser.EXTRA_HEADERS);
if (bundleExtraHeaders == null) return null;
StringBuilder extraHeaders = new StringBuilder();
Iterator<String> keys = bundleExtraHeaders.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = bundleExtraHeaders.getString(key);
if ("referer".equals(key.toLowerCase(Locale.US))) continue;
if (extraHeaders.length() != 0) extraHeaders.append("\n");
extraHeaders.append(key);
extraHeaders.append(": ");
extraHeaders.append(value);
}
return extraHeaders.length() == 0 ? null : extraHeaders.toString();
}
/**
* 设置链接跳转与高亮样式
*
* @param url
* @return
*/
private static ClickableSpan getClickableSpan(final String url) {
return new ClickableSpan() {
@Override
public void onClick(View widget) {
Uri uri = Uri.parse(url);
Context context = widget.getContext();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
context.startActivity(intent);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(Color.BLUE);
ds.setUnderlineText(false);
}
};
}
private static void openUrl(Activity activity, String url, ComponentName componentName) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.putExtra(Browser.EXTRA_APPLICATION_ID,
activity.getApplicationContext().getPackageName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(IntentHandler.EXTRA_PAGE_TRANSITION_TYPE, PageTransition.AUTO_BOOKMARK);
if (componentName != null) {
intent.setComponent(componentName);
} else {
// If the bookmark manager is shown in a tab on a phone (rather than in a separate
// activity) the component name may be null. Send the intent through
// ChromeLauncherActivity instead to avoid crashing. See crbug.com/615012.
intent.setClass(activity, ChromeLauncherActivity.class);
}
IntentHandler.startActivityForTrustedIntent(intent);
}
@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);
}
}
}
@Override
public void startActivity(Intent intent) {
if (intent.getStringExtra(Browser.EXTRA_APPLICATION_ID) != null) {
intent.removeExtra(Browser.EXTRA_APPLICATION_ID);
}
try {
super.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, e);
Toast.makeText(this, R.string.ConversationActivity_there_is_no_app_available_to_handle_this_link_on_your_device, Toast.LENGTH_LONG).show();
}
}
@NonNull
private static List<LabeledIntent> createForUrl(Context context, String text) {
if (Uri.parse(text).getScheme() == null) {
text = "http://" + text;
}
return Arrays.asList(new LabeledIntent(
context.getString(com.android.internal.R.string.browse),
context.getString(com.android.internal.R.string.browse_desc),
new Intent(Intent.ACTION_VIEW, Uri.parse(text))
.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName()),
LabeledIntent.DEFAULT_REQUEST_CODE));
}
@Override
public void onClick(View widget) {
Uri uri = Uri.parse(getURL());
Context context = widget.getContext();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w("URLSpan", "Actvity was not found for intent, " + intent.toString());
}
}
public static void startURL(Activity activity, Uri uri) {
if (!XposedApp.getPreferences().getBoolean("chrome_tabs", true)) {
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, activity.getPackageName());
activity.startActivity(intent);
return;
}
CustomTabsIntent.Builder customTabsIntent = new CustomTabsIntent.Builder();
customTabsIntent.setShowTitle(true);
customTabsIntent.setToolbarColor(XposedApp.getColor(activity));
customTabsIntent.build().launchUrl(activity, uri);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String installedXposedVersion;
try {
installedXposedVersion = XposedApp.getInstance().mXposedProp.getVersion();
} catch (NullPointerException e) {
installedXposedVersion = null;
}
String xposedStatus;
switch (getXposedStatus(installedXposedVersion)) {
case 2:
xposedStatus = getString(R.string.status_2) + " (" + installedXposedVersion + ")";
break;
case 1:
xposedStatus = getString(R.string.status_1) + " (" + installedXposedVersion + ")";
break;
case 0:
default:
xposedStatus = getString(R.string.status_0);
}
new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(R.string.app_name)
.setMessage(getString(R.string.status_text) + ": " + xposedStatus + "\n\n" + getString(R.string.upgrade_msg))
.setPositiveButton(android.R.string.ok, (d, w) -> {
Intent intent = new Intent(Intent.ACTION_VIEW, parseURL("https://github.com/ElderDrivers/EdXposedManager/releases/latest"));
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
startActivity(intent);
finish();
})
.setNegativeButton(android.R.string.cancel, (d, w) -> finish())
.show();
}
public static void openUrl(Context c, String url) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, c.getPackageName());
checkContextIsActivity(c, intent);
c.startActivity(intent);
}
@Override
public void onClick(View widget) {
Uri uri = Uri.parse(getURL());
Context context = widget.getContext();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
context.startActivity(intent);
}
private void startAuthorizationFlow() {
// create and store random string to verify auth results later
state = UUID.randomUUID().toString();
final String authUrl = RedditOauthBuilder.createAuthUrl(state, "identity", "history");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
startActivityForResult(intent, RC_AUTHORIZE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_addBookmark:
// ブックマークの追加
Browser.saveBookmark(this, "TechBooster", "http://techbooster.org/");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_browser_open) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mUrl));
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "该url无法解析", Toast.LENGTH_SHORT).show();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
cursor = getContentResolver().query(Browser.BOOKMARKS_URI, BOOKMARK_PROJECTION,
BOOKMARK_SELECTION, null, null);
if (cursor == null) {
Log.w(TAG, "No cursor returned for bookmark query");
finish();
return;
}
setListAdapter(new BookmarkAdapter(this, cursor));
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
cursor = getContentResolver().query(Browser.BOOKMARKS_URI, BOOKMARK_PROJECTION,
BOOKMARK_SELECTION, null, null);
if (cursor == null) {
Log.w(TAG, "No cursor returned for bookmark query");
finish();
return;
}
setListAdapter(new BookmarkAdapter(this, cursor));
}
protected static void launchFallbackSupportUri(Context context) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(FALLBACK_SUPPORT_URL));
// Let Chrome know that this intent is from Chrome, so that it does not close the app when
// the user presses 'back' button.
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
intent.putExtra(Browser.EXTRA_CREATE_NEW_TAB, true);
intent.setPackage(context.getPackageName());
context.startActivity(intent);
}
private static void openUrl(Uri uri) {
Context context = ContextUtils.getApplicationContext();
Intent intent = new Intent()
.setAction(Intent.ACTION_VIEW)
.setData(uri)
.setClass(context, ChromeLauncherActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName())
.putExtra(ShortcutHelper.REUSE_URL_MATCHING_TAB_ELSE_NEW_TAB, true);
IntentHandler.addTrustedIntentExtras(intent);
context.startActivity(intent);
}
/**
* Opens a new Tab with the possibility of showing it in a Custom Tab, instead.
*
* See IntentHandler#processUrlViewIntent() for an explanation most of the parameters.
* @param forceNewTab If not handled by a Custom Tab, forces the new tab to be created.
*/
private void openNewTab(String url, String referer, String headers,
String externalAppId, Intent intent, boolean forceNewTab) {
boolean isAllowedToReturnToExternalApp = IntentUtils.safeGetBooleanExtra(intent,
ChromeLauncherActivity.EXTRA_IS_ALLOWED_TO_RETURN_TO_PARENT, true);
String herbFlavor = FeatureUtilities.getHerbFlavor();
if (isAllowedToReturnToExternalApp
&& ChromeLauncherActivity.canBeHijackedByHerb(intent)
&& TextUtils.equals(ChromeSwitches.HERB_FLAVOR_DILL, herbFlavor)) {
Log.d(TAG, "Sending to CustomTabActivity");
mActivityStopMetrics.setStopReason(
ActivityStopMetrics.STOP_REASON_CUSTOM_TAB_STARTED);
Intent newIntent = ChromeLauncherActivity.createCustomTabActivityIntent(
ChromeTabbedActivity.this, intent, false);
newIntent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
newIntent.putExtra(
CustomTabIntentDataProvider.EXTRA_IS_OPENED_BY_CHROME, true);
ChromeLauncherActivity.updateHerbIntent(ChromeTabbedActivity.this,
newIntent, Uri.parse(IntentHandler.getUrlFromIntent(newIntent)));
// Launch the Activity on top of this task.
int updatedFlags = newIntent.getFlags();
updatedFlags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
updatedFlags &= ~Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
newIntent.setFlags(updatedFlags);
startActivityForResult(newIntent, CCT_RESULT);
} else {
// Create a new tab.
Tab newTab =
launchIntent(url, referer, headers, externalAppId, forceNewTab, intent);
newTab.setIsAllowedToReturnToExternalApp(isAllowedToReturnToExternalApp);
RecordUserAction.record("MobileReceivedExternalIntent");
}
}
/**
* Shows a dialog to ask whether user wants to open the nextURL.
*
* @param omaInfo Information about the OMA content.
*/
private void showNextUrlDialog(OMAInfo omaInfo) {
if (omaInfo.isValueEmpty(OMA_NEXT_URL)) {
return;
}
final String nextUrl = omaInfo.getValue(OMA_NEXT_URL);
final Activity activity = ApplicationStatus.getLastTrackedFocusedActivity();
DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == AlertDialog.BUTTON_POSITIVE) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(nextUrl));
intent.putExtra(Browser.EXTRA_APPLICATION_ID, activity.getPackageName());
intent.putExtra(Browser.EXTRA_CREATE_NEW_TAB, true);
intent.setPackage(mContext.getPackageName());
activity.startActivity(intent);
}
}
};
new AlertDialog.Builder(activity)
.setTitle(R.string.open_url_post_oma_download)
.setPositiveButton(R.string.ok, clickListener)
.setNegativeButton(R.string.cancel, clickListener)
.setMessage(nextUrl)
.setCancelable(false)
.show();
}