애플리케이션에서 안드로이드 웹 브라우저의 URL을 열려면 어떻게 해야 합니까?
내 애플리케이션이 아닌 내장 웹 브라우저의 코드에서 URL을 여는 방법은 무엇입니까?
시도해 봤습니다.
try {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(download_link));
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application can handle this request."
+ " Please install a webbrowser", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
하지만 예외가 있습니다.
No activity found to handle Intent{action=android.intent.action.VIEW data =www.google.com
사용해 보십시오.
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
그것은 저에게 잘 맞습니다.
누락된 "http://"에 대해 저는 다음과 같은 것을 할 것입니다.
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
나는 또한 사용자가 "http://"로 URL을 입력하는 편집 텍스트를 미리 채울 것입니다.
코틀린에서:
if (!url.startsWith("http://") && !url.startsWith("https://")) {
"http://$url"
}
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(browserIntent)
이를 위한 일반적인 방법은 다음 코드를 사용하는 것입니다.
String url = "http://www.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
짧은 코드 버전으로 변경할 수 있습니다...
Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.stackoverflow.com"));
startActivity(intent);
또는 :
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com"));
startActivity(intent);
가장 짧은!:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));
간단한 대답
Android Developer의 공식 샘플을 보실 수 있습니다.
/**
* Open a web page of a specified URL
*
* @param url URL to open
*/
public void openWebPage(String url) {
Uri webpage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
작동 방식
다음의 생성자를 확인하십시오.
public Intent (String action, Uri uri)
합격할 수 있습니다android.net.Uri인스턴스에서 두 번째 매개 변수로 이동하면 지정된 데이터 URL을 기반으로 새 Intent가 생성됩니다.
그런 다음, 간단히 전화하세요.startActivity(Intent intent)URL과 Intent와 을 시작합니다.
가 합니까?if명세서를 확인하시겠습니까?
네, 서류에는 다음과 같이 적혀 있습니다.
단말기에 암묵적인 의도를 수신할 수 있는 앱이 없으면 startActivity()를 호출할 때 앱이 충돌합니다.먼저 앱이 의도를 수신할 수 있는지 확인하려면 의도 개체에 대한 활동 확인()을 호출합니다.결과가 null이 아닐 경우 의도를 처리할 수 있는 앱이 하나 이상 있으며 startActivity()를 호출해도 안전합니다.결과가 null이면 의도를 사용하지 않아야 하며 가능한 경우 의도를 호출하는 기능을 사용하지 않도록 설정해야 합니다.
보너스
다음과 같이 Intent 인스턴스를 만들 때 한 줄로 쓸 수 있습니다.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
2.3에서, 나는 더 나은 운을 얻었습니다.
final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url));
activity.startActivity(intent);
차이점은 사용하는 것입니다.Intent.ACTION_VIEW"android.intent.action.VIEW"
코틀린의 대답:
val browserIntent = Intent(Intent.ACTION_VIEW, uri)
ContextCompat.startActivity(context, browserIntent, null)
▁▁extension에 확장자를 했습니다.Uri을 훨씬 더 하기 ▁to위.
myUri.openInBrowser(context)
fun Uri?.openInBrowser(context: Context) {
this ?: return // Do nothing if uri is null
val browserIntent = Intent(Intent.ACTION_VIEW, this)
ContextCompat.startActivity(context, browserIntent, null)
}
추가로 문자열을 URI로 안전하게 변환할 수 있는 간단한 확장 기능이 있습니다.
"https://stackoverflow.com".asUri()?.openInBrowser(context)
fun String?.asUri(): Uri? {
return try {
Uri.parse(this)
} catch (e: Exception) {
null
}
}
사용해 보십시오.
Uri uri = Uri.parse("https://www.google.com");
startActivity(new Intent(Intent.ACTION_VIEW, uri));
또는 활동에서 웹 브라우저를 열고 싶다면 다음과 같이 하십시오.
WebView webView = (WebView) findViewById(R.id.webView1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl(URL);
브라우저에서 확대/축소 제어를 사용하려면 다음을 사용할 수 있습니다.
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
사용자가 기본 설정을 선택할 수 있도록 모든 브라우저 목록이 포함된 대화 상자를 표시하려면 다음과 같이 샘플 코드를 선택합니다.
private static final String HTTPS = "https://";
private static final String HTTP = "http://";
public static void openBrowser(final Context context, String url) {
if (!url.startsWith(HTTP) && !url.startsWith(HTTPS)) {
url = HTTP + url;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(Intent.createChooser(intent, "Choose browser"));// Choose browser is arbitrary :)
}
다른 사람들이 작성한 솔루션과 마찬가지로(잘 작동하는 솔루션), 저는 대부분이 사용하기를 선호하는 팁을 사용하여 동일한 답변을 하고 싶습니다.
새 작업에서 앱을 여는 경우 동일한 스택에 머무르지 않고 자신과 독립적으로 다음 코드를 사용할 수 있습니다.
final Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY|Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);
또한 Chrome 사용자 지정 탭에서 URL을 여는 방법도 있습니다. Kotlin의 예:
@JvmStatic
fun openWebsite(activity: Activity, websiteUrl: String, useWebBrowserAppAsFallbackIfPossible: Boolean) {
var websiteUrl = websiteUrl
if (TextUtils.isEmpty(websiteUrl))
return
if (websiteUrl.startsWith("www"))
websiteUrl = "http://$websiteUrl"
else if (!websiteUrl.startsWith("http"))
websiteUrl = "http://www.$websiteUrl"
val finalWebsiteUrl = websiteUrl
//https://github.com/GoogleChrome/custom-tabs-client
val webviewFallback = object : CustomTabActivityHelper.CustomTabFallback {
override fun openUri(activity: Activity, uri: Uri?) {
var intent: Intent
if (useWebBrowserAppAsFallbackIfPossible) {
intent = Intent(Intent.ACTION_VIEW, Uri.parse(finalWebsiteUrl))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
if (!CollectionUtil.isEmpty(activity.packageManager.queryIntentActivities(intent, 0))) {
activity.startActivity(intent)
return
}
}
// open our own Activity to show the URL
intent = Intent(activity, WebViewActivity::class.java)
WebViewActivity.prepareIntent(intent, finalWebsiteUrl)
activity.startActivity(intent)
}
}
val uri = Uri.parse(finalWebsiteUrl)
val intentBuilder = CustomTabsIntent.Builder()
val customTabsIntent = intentBuilder.build()
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
CustomTabActivityHelper.openCustomTab(activity, customTabsIntent, uri, webviewFallback)
}
다른 옵션 웹 보기를 사용하여 동일한 응용 프로그램의 URL 로드
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
이 길로도 갈 수 있습니다.
xml 단위:
<?xml version="1.0" encoding="utf-8"?>
<WebView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Java 코드:
public class WebViewActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
}
}
매니페스트에서 인터넷 권한을 추가하는 것을 잊지 마십시오.
그래서 저는 오랫동안 이것을 찾았습니다. 왜냐하면 다른 모든 대답들은 그 링크에 대한 기본 앱을 열었지만, 기본 브라우저는 열지 않았기 때문입니다. 그리고 그것이 제가 원했던 것입니다.
마침내 그렇게 할 수 있었습니다.
// gathering the default browser
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
final ResolveInfo resolveInfo = context.getPackageManager()
.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
String defaultBrowserPackageName = resolveInfo.activityInfo.packageName;
final Intent intent2 = new Intent(Intent.ACTION_VIEW);
intent2.setData(Uri.parse(url));
if (!defaultBrowserPackageName.equals("android")) {
// android = no default browser is set
// (android < 6 or fresh browser install or simply no default set)
// if it's the case (not in this block), it will just use normal way.
intent2.setPackage(defaultBrowserPackageName);
}
context.startActivity(intent2);
BTW, 당신은 알아차릴 수 있습니다.context 제가 하지 않습니다뭐니뭐니해도 정적인 util 메서드에 사용했기 때문에 활동에서 이 작업을 수행하는 경우에는 필요하지 않습니다.
웹 보기를 사용하여 응용 프로그램에 URL을 로드할 수 있습니다.텍스트 보기에서 사용자로부터 URL을 제공하거나 하드 코딩할 수 있습니다.
Android Manifest의 인터넷 사용 권한도 잊지 마십시오.
String url="http://developer.android.com/index.html"
WebView wv=(WebView)findViewById(R.id.webView);
wv.setWebViewClient(new MyBrowser());
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl(url);
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
시도 블록 내에 다음 코드를 붙여넣으십시오. Android Intent는 링크의 위치를 식별하기 위해 URI(Uniform Resource Identifier) 가새 내의 링크를 직접 사용합니다.
사용해 볼 수 있습니다.
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);
간단한 코드 버전...
if (!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
strUrl= "http://" + strUrl;
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));
단순 및 모범 사례
방법 1:
String intentUrl="www.google.com";
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(intentUrl));
if(webIntent.resolveActivity(getPackageManager())!=null){
startActivity(webIntent);
}else{
/*show Error Toast
or
Open play store to download browser*/
}
방법 2:.
try{
String intentUrl="www.google.com";
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(intentUrl));
startActivity(webIntent);
}catch (ActivityNotFoundException e){
/*show Error Toast
or
Open play store to download browser*/
}
짧고 달콤한 코틀린 도우미 기능:
private fun openUrl(link: String) =
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)))
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Android 11의 URL에서 링크를 여는 새롭고 더 나은 방법.
try {
val intent = Intent(ACTION_VIEW, Uri.parse(url)).apply {
// The URL should either launch directly in a non-browser app
// (if it’s the default), or in the disambiguation dialog
addCategory(CATEGORY_BROWSABLE)
flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_REQUIRE_NON_BROWSER or
FLAG_ACTIVITY_REQUIRE_DEFAULT
}
startActivity(intent)
} catch (e: ActivityNotFoundException) {
// Only browser apps are available, or a browser is the default app for this intent
// This code executes in one of the following cases:
// 1. Only browser apps can handle the intent.
// 2. The user has set a browser app as the default app.
// 3. The user hasn't set any app as the default for handling this URL.
openInCustomTabs(url)
}
참조:
https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9 및 https://developer.android.com/training/package-visibility/use-cases#avoid-a-disambiguation-dialog
Intent getWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(MyLink));
startActivity(getWebPage);
Mark B의 답변이 맞습니다.제 경우에는 Xamarin을 사용하고 있으며, C# 및 Xamarin과 함께 사용할 코드는 다음과 같습니다.
var uri = Android.Net.Uri.Parse ("http://www.xamarin.com");
var intent = new Intent (Intent.ActionView, uri);
StartActivity (intent);
이 정보는 다음에서 가져옵니다. https://developer.xamarin.com/recipes/android/fundamentals/intent/open_a_webpage_in_the_browser_application/
이제 Chrome 사용자 지정 탭을 사용할 수 있습니다.
첫 번째 단계는 사용자 지정 탭 지원 라이브러리를 build.gradle 파일에 추가하는 것입니다.
dependencies {
...
compile 'com.android.support:customtabs:24.2.0'
}
그런 다음 Chrome 사용자 지정 탭을 열려면 다음과 같이 하십시오.
String url = "https://www.google.pt/";
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));
자세한 내용은 https://developer.chrome.com/multidevice/android/customtabs 에서 확인하시기 바랍니다.
간단한, 의도를 통한 웹사이트 보기,
Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.yoursite.in"));
startActivity(viewIntent);
이 간단한 코드를 사용하여 안드로이드 앱에서 당신의 웹사이트를 봅니다.
매니페스트 파일에 인터넷 권한을 추가합니다.
<uses-permission android:name="android.permission.INTERNET" />
Mark B의 답변과 아래 의견을 기반으로 합니다.
protected void launchUrl(String url) {
Uri uri = Uri.parse(url);
if (uri.getScheme() == null || uri.getScheme().isEmpty()) {
uri = Uri.parse("http://" + url);
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
if (browserIntent.resolveActivity(getPackageManager()) != null) {
startActivity(browserIntent);
}
}
이 방법은 고정 입력 대신 문자열을 입력할 수 있는 메소드를 사용합니다.이렇게 하면 메서드를 호출하는 데 세 줄만 필요하기 때문에 반복적으로 사용할 경우 일부 줄의 코드가 저장됩니다.
public Intent getWebIntent(String url) {
//Make sure it is a valid URL before parsing the URL.
if(!url.contains("http://") && !url.contains("https://")){
//If it isn't, just add the HTTP protocol at the start of the URL.
url = "http://" + url;
}
//create the intent
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)/*And parse the valid URL. It doesn't need to be changed at this point, it we don't create an instance for it*/);
if (intent.resolveActivity(getPackageManager()) != null) {
//Make sure there is an app to handle this intent
return intent;
}
//If there is no app, return null.
return null;
}
이 방법을 사용하면 보편적으로 사용할 수 있습니다.IT는 다음과 같이 사용할 수 있으므로 특정 활동에 배치할 필요가 없습니다.
Intent i = getWebIntent("google.com");
if(i != null)
startActivity();
또는 활동 외부에서 시작하려면 활동 인스턴스에서 startActivity를 호출합니다.
Intent i = getWebIntent("google.com");
if(i != null)
activityInstance.startActivity(i);
이 두 코드 블록에서 볼 수 있듯이 null-check가 있습니다.이는 의도를 처리할 앱이 없는 경우 null을 반환하기 때문입니다.
이 방법은 정의된 프로토콜이 없는 경우 HTTP로 기본 설정됩니다. SSL 인증서(HTTPS 연결에 필요한 인증서)가 없는 웹 사이트가 있기 때문입니다. HTTPS를 사용하려고 하지만 인증서가 없는 웹 사이트는 작동을 중지됩니다.모든 웹 사이트는 여전히 HTTPS로 강제 전환될 수 있으므로, 어느 쪽이든 HTTPS에 도달할 수 있습니다.
이 방법은 외부 리소스를 사용하여 페이지를 표시하므로 인터넷 사용 권한을 선언할 필요가 없습니다.웹 페이지를 표시하는 앱이 그렇게 해야 합니다.
android.webkit.URLUtil방법이 완벽하게 잘 작동합니다(심지어는 를 사용하더라도).file://또는data://)이후Api level 1(Android 1.0).다음으로 사용:
String url = URLUtil.guessUrl(link);
// url.com -> http://url.com/ (adds http://)
// http://url -> http://url.com/ (adds .com)
// https://url -> https://url.com/ (adds .com)
// url -> http://www.url.com/ (adds http://www. and .com)
// http://www.url.com -> http://www.url.com/
// https://url.com -> https://url.com/
// file://dir/to/file -> file://dir/to/file
// data://dataline -> data://dataline
// content://test -> content://test
활동 전화:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(URLUtil.guessUrl(download_link)));
if (intent.resolveActivity(getPackageManager()) != null)
startActivity(intent);
자세한 내용은 전체 코드를 확인하십시오.
코틀린
startActivity(Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(your_link)
})
모든 답변을 확인했는데 사용자가 사용하고자 하는 동일한 URL과 딥링크가 있는 앱은 무엇입니까?
오늘 제가 이 케이스를 받았는데 대답은browserIntent.setPackage("browser_package_name");
예:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
browserIntent.setPackage("com.android.chrome"); // Whatever browser you are using
startActivity(browserIntent);
이게 제일 좋은 것 같아요.
openBrowser(context, "http://www.google.com")
아래 코드를 글로벌 클래스에 추가합니다.
public static void openBrowser(Context context, String url) {
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(browserIntent);
}
//온클릭 수신기
@Override
public void onClick(View v) {
String webUrl = news.getNewsURL();
if(webUrl!="")
Utils.intentWebURL(mContext, webUrl);
}
//사용자의 사용 방법
public static void intentWebURL(Context context, String url) {
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
boolean flag = isURL(url);
if (flag) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
context.startActivity(browserIntent);
}
}
브라우저에서 URL을 열려면 짧은 것으로 이동하기만 하면 됩니다.
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
startActivity(browserIntent);
언급URL : https://stackoverflow.com/questions/2201917/how-can-i-open-a-url-in-androids-web-browser-from-my-application
'programing' 카테고리의 다른 글
| mariadb: 바인딩을 c-연결하는 방법 (0) | 2023.06.16 |
|---|---|
| 문자열에 숫자만 포함되어 있는지 확인하는 방법은 무엇입니까? (0) | 2023.06.16 |
| Excel 시트에서 Firebase 데이터를 내보내는 방법 (0) | 2023.06.16 |
| 문자열 배열에서 문자열을 검색하는 방법 (0) | 2023.06.16 |
| Oracle SQL에서 'YYYY'와 'RRR'의 차이점은 무엇입니까? (0) | 2023.06.16 |