1522

アプリケーション内ではなく、組み込みのWebブラウザーでコードから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
4

40 に答える 40

2757

これを試して:

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;

また、ユーザーがURLを「http://」で入力していることをEditTextに事前入力することもできます。

于 2010-02-04T18:01:42.133 に答える
119

これを実現する一般的な方法は、次のコードを使用することです。

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")));
于 2014-05-27T14:20:57.910 に答える
70

簡単な答え

AndroidDeveloperの公式サンプルをご覧いただけます。

/**
 * 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);
    }
}

使い方

のコンストラクターを見てくださいIntent

public Intent (String action, Uri uri)

インスタンスを2番目のパラメーターに渡すことができandroid.net.Uri、指定されたデータURLに基​​づいて新しいインテントが作成されます。

次に、呼び出しstartActivity(Intent intent)て新しいアクティビティを開始します。このアクティビティは、指定されたURLのインテントにバンドルされています。

ifチェックステートメントが必要ですか?

はい。ドキュメントによると:

暗黙的なインテントを受信できるアプリがデバイス上にない場合、startActivity()を呼び出すとアプリがクラッシュします。インテントを受信するアプリが存在することを最初に確認するには、インテントオブジェクトでresolveActivity()を呼び出します。結果がnullでない場合、インテントを処理できるアプリが少なくとも1つあり、startActivity()を安全に呼び出すことができます。結果がnullの場合は、インテントを使用しないでください。可能であれば、インテントを呼び出す機能を無効にする必要があります。

ボーナス

以下のようにIntentインスタンスを作成するときに、1行で書き込むことができます。

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
于 2015-08-24T05:06:00.643 に答える
63

2.3では、運が良かった

final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url));
activity.startActivity(intent);

違いはIntent.ACTION_VIEW、文字列ではなくの使用です"android.intent.action.VIEW"

于 2011-03-16T15:35:22.953 に答える
31

これを試して:

Uri uri = Uri.parse("https://www.google.com");
startActivity(new Intent(Intent.ACTION_VIEW, uri));

または、必要に応じて、アクティビティでWebブラウザを開き、次のようにします。

WebView webView = (WebView) findViewById(R.id.webView1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl(URL);

ブラウザでズームコントロールを使用する場合は、次を使用できます。

settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
于 2012-08-31T10:10:25.303 に答える
23

すべてのブラウザリストとのダイアログをユーザーに表示して、ユーザーが優先を選択できるようにする場合は、サンプルコードを次に示します。

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 :)

}
于 2013-01-09T08:55:14.240 に答える
21

他の人が書いた(うまくいく)解決策と同じように、私は同じことを答えたいと思いますが、私が最も使いたいと思うヒントを持っています。

同じスタックにとどまる代わりに、独自の独立した新しいタスクでアプリを開き始めたい場合は、次のコードを使用できます。

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)
}
于 2014-04-08T09:19:51.580 に答える
20

Kotlinの回答:

val browserIntent = Intent(Intent.ACTION_VIEW, uri)
ContextCompat.startActivity(context, browserIntent, null)

Uriこれをさらに簡単にするために拡張機能を追加しました

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
    }
}
于 2020-01-03T03:55:29.807 に答える
17

Webviewを使用して同じアプリケーションにURLをロードする他のオプション

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
于 2012-06-25T08:01:43.597 に答える
12

この方法で行くこともできます

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");

 }

}

マニフェストでは、インターネットの許可を追加することを忘れないでください...

于 2013-12-19T06:04:08.470 に答える
9

Webviewを使用して、アプリケーションにUrlをロードできます。URLは、テキストビューでユーザーから提供することも、ハードコーディングすることもできます。

また、AndroidManifestのインターネット権限も忘れないでください。

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;
    }
}
于 2015-11-12T21:41:16.963 に答える
7

tryブロック内に、次のコードを貼り付けます。AndroidIntentは、リンクの場所を識別するために、URI(Uniform Resource Identifier)中括弧内のリンクを直接使用します。

あなたはこれを試すことができます:

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);
于 2014-01-09T12:37:03.183 に答える
6

ショートコードバージョン...

 if (!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
     strUrl= "http://" + strUrl;
 }


 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));
于 2013-12-03T16:24:32.013 に答える
6

シンプルでベストプラクティス

方法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*/
    }
于 2019-03-11T07:34:16.803 に答える
4
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
于 2014-09-04T07:19:37.133 に答える
4

他のすべての答えがそのリンクのデフォルトのアプリを開いていたので、私は長い間これを探していましたが、デフォルトのブラウザではなく、それが私が望んでいたことです。

私はついにそうすることができました:

// 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);

ところで、context静的なutilメソッドにこれを使用したので、アクティビティでこれを実行している場合は、必要ありません。

于 2020-04-28T19:11:10.623 に答える
3
Intent getWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(MyLink));          
startActivity(getWebPage);
于 2014-07-17T12:40:53.017 に答える
3

インテントによるシンプルなウェブサイトビュー、

Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.yoursite.in"));
startActivity(viewIntent);  

この単純なコードを使用して、AndroidアプリでWebサイトを表示します。

マニフェストファイルにインターネット許可を追加し、

<uses-permission android:name="android.permission.INTERNET" /> 
于 2014-11-08T09:34:49.537 に答える
3

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をご覧ください。

于 2016-08-19T13:01:06.140 に答える
3

MarkBの反応は正しいです。私の場合、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/から取得されます。

于 2017-07-11T13:02:53.043 に答える
3

すべての回答を確認しましたが、ユーザーが使用したい同じ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);
于 2018-01-10T03:03:30.067 に答える
3

短くて甘いKotlinヘルパー関数:

private fun openUrl(link: String) =
    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)))
于 2021-03-20T19:21:36.790 に答える
3

Android11で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

于 2021-06-10T02:36:44.437 に答える
2

マーク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);
    }
}
于 2016-12-16T06:35:33.833 に答える
2

android.webkit.URLUtil(Android 1.0)以降、メソッドは(またはを使用guessUrl(String)しても)完全に正常に機能します。使用:file://data://Api level 1

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);

詳細については、完全なguessUrlコードを確認してください。

于 2017-06-21T10:57:50.253 に答える
2

短いものを使用して、ブラウザでURLを開きます。

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
startActivity(browserIntent);
于 2019-04-02T12:55:55.517 に答える
2
String url = "https://www.thandroid-mania.com/";
if (url.startsWith("https://") || url.startsWith("http://")) {
    Uri uri = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}else{
    Toast.makeText(mContext, "Invalid Url", Toast.LENGTH_SHORT).show();
}

このエラーは無効なURLが原因で発生し、AndroidOSはデータのアクションビューを見つけることができません。したがって、URLが有効かどうかを検証しました。

于 2019-08-22T02:38:41.127 に答える
2

Kotlin

startActivity(Intent(Intent.ACTION_VIEW).apply {
            data = Uri.parse(your_link)
        })
于 2020-02-04T09:02:13.423 に答える
1

これが最高だと思います

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);
    }
于 2016-10-05T06:30:59.330 に答える
1

この方法では、メソッドを使用して、固定入力ではなく任意の文字列を入力できるようにします。メソッドを呼び出すのに必要なのは3行だけなので、これを繰り返し使用すると、コードの数行が節約されます。

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を返すためです。

プロトコルが定義されていない場合、このメソッドはデフォルトでHTTPになります。これは、SSL証明書(HTTPS接続に必要なもの)を持たないWebサイトがあり、HTTPSを使用しようとして、そこにない場合は機能しなくなるためです。 。どのWebサイトでもHTTPSに強制的に移行できるため、どちらの方法でもHTTPSにアクセスできます。


このメソッドは外部リソースを使用してページを表示するため、インターネット権限を宣言する必要はありません。ウェブページを表示するアプリはそれをしなければなりません

于 2017-05-01T18:47:23.757 に答える
1

//OnClickリスナー

  @Override
      public void onClick(View v) {
        String webUrl = news.getNewsURL();
        if(webUrl!="")
        Utils.intentWebURL(mContext, webUrl);
      }

//Utilメソッド

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);
        }

    }
于 2018-01-22T09:17:51.253 に答える
1

アンコライブラリー方式より

fun Context.browse(url: String, newTask: Boolean = false): Boolean {
    try {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = Uri.parse(url)
        if (newTask) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        startActivity(intent)
        return true
    } catch (e: ActivityNotFoundException) {
        e.printStackTrace()
        return false
    }
}
于 2020-10-13T08:08:48.057 に答える
0

URLが正しいかどうかを確認してください。私にとって、URLの前に不要なスペースがありました。

于 2015-10-12T10:46:13.637 に答える
0

基本的な紹介:

https://はそれを「コード」に使用しているので、間に誰もそれらを読むことができません。これにより、ハッカーから情報を安全に保つことができます。

http://は共有目的のみを使用しており、セキュリティで保護されていません。

あなたの問題について:
XML設計:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.sridhar.sharedpreferencesstackoverflow.MainActivity">
   <LinearLayout
       android:orientation="horizontal"
       android:background="#228b22"
       android:layout_weight="1"
       android:layout_width="match_parent"
       android:layout_height="0dp">
      <Button
          android:id="@+id/normal_search"
          android:text="secure Search"
          android:onClick="secure"
          android:layout_weight="1"
          android:layout_width="0dp"
          android:layout_height="wrap_content" />
      <Button
          android:id="@+id/secure_search"
          android:text="Normal Search"
          android:onClick="normal"
          android:layout_weight="1"
          android:layout_width="0dp"
          android:layout_height="wrap_content" />
   </LinearLayout>

   <LinearLayout
       android:layout_weight="9"
       android:id="@+id/button_container"
       android:layout_width="match_parent"
       android:layout_height="0dp"
       android:orientation="horizontal">

      <WebView
          android:id="@+id/webView1"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />

   </LinearLayout>
</LinearLayout>

アクティビティデザイン:

public class MainActivity extends Activity {
    //securely open the browser
    public String Url_secure="https://www.stackoverflow.com";
    //normal purpouse
    public String Url_normal="https://www.stackoverflow.com";

    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView=(WebView)findViewById(R.id.webView1);

    }
    public void secure(View view){
        webView.setWebViewClient(new SecureSearch());
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.loadUrl(Url_secure);
    }
    public void normal(View view){
        webView.setWebViewClient(new NormalSearch());
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.loadUrl(Url_normal);

    }
    public class SecureSearch extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String Url_secure) {
            view.loadUrl(Url_secure);
            return true;
        }
    }
    public class NormalSearch extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String Url_normal) {
            view.loadUrl(Url_normal);
            return true;
        }
    }
}

Android Manifest.Xml権限:

<uses-permission android:name="android.permission.INTERNET"/>

これを実装すると、問題が発生します。

  1. マニフェストの権限 を取得する
  2. URL間の余分なスペース
  3. URLが正しいかどうかを 確認してください
于 2016-07-29T02:07:14.393 に答える
0

プログラムではなくXMLでこれを実行したい場合は、TextViewで使用できます。

android:autoLink="web"
android:linksClickable="true"
于 2017-01-19T07:58:13.967 に答える
0

これを試してみてくださいOmegaIntentBuilder

OmegaIntentBuilder.from(context)
                .web("Your url here")
                .createIntentHandler()
                .failToast("You don't have app for open urls")
                .startActivity();
于 2018-01-23T14:07:21.370 に答える
0
dataWebView.setWebViewClient(new VbLinksWebClient() {
     @Override
     public void onPageFinished(WebView webView, String url) {
           super.onPageFinished(webView, url);
     }
});




public class VbLinksWebClient extends WebViewClient
{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url)
    {
        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url.trim())));
        return true;
    }
}
于 2018-11-21T09:37:47.850 に答える
0

このコードを試してください

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
   package="com.example.myapplication5">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
    android:usesCleartextTraffic="true"
    android:allowBackup="true"
    .....
     />
     <activity android:name=".MainActivity"
        android:screenOrientation="portrait"
        tools:ignore="LockedOrientationActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
 </manifest>

MainActivity.java

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends Activity {
    private WebView mWebview;
    String link = "";// global variable
    Resources res;// global variable

    @Override


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.home);

        loadWebPage();
    }

    public void loadWebPage()
    {
        mWebview = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = mWebview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        final Activity activity = this;
        mWebview.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }
        });
        mWebview.loadUrl("http://www.google.com");

    }

    public void reLoad(View v)
    {
        loadWebPage();
    }
}

Layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="335dp"
        android:layout_height="47dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="9dp"
        android:layout_marginTop="8dp"
        android:paddingLeft="10dp"
        android:paddingTop="5dp"
        android:text="URL : https://ktmmovie.co/"
        android:textSize="18dp"
        android:layout_marginLeft="9dp"
        android:layout_alignParentLeft="true" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="7dp"
        android:layout_marginLeft="7dp"
        android:layout_marginEnd="8dp"
        android:layout_toEndOf="@+id/textView"
        android:layout_toRightOf="@+id/textView"
        android:clickable="true"
        android:src="@android:drawable/ic_popup_sync"
        android:layout_marginRight="8dp"
        android:layout_alignParentRight="true"
        android:onClick="reLoad"/>

    <WebView
        android:id="@+id/webView"
        android:layout_width="401dp"
        android:layout_height="665dp"
        android:layout_below="@+id/textView"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="3dp"
        android:layout_marginLeft="3dp"
        android:layout_marginTop="3dp"
        android:layout_marginBottom="7dp" />


</RelativeLayout>
于 2020-04-03T20:37:03.640 に答える
0

Kotlin開発者はこれを使用できます

var webpage = Uri.parse(url)
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        webpage = Uri.parse("http://$url")
    }
    val intent = Intent(Intent.ACTION_VIEW, webpage)
    if (intent.resolveActivity(packageManager) != null) {
        startActivity(intent)
    }
于 2020-10-02T15:16:50.633 に答える
-1

これを試してみてください..私のために働いた!

    public void webLaunch(View view) {
            WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.setVisibility(View.VISIBLE);
            View view1=findViewById(R.id.recharge);
            view1.setVisibility(View.GONE);
            myWebView.getSettings().setJavaScriptEnabled(true);
            myWebView.loadUrl("<your link>");

        }

xmlコード:-

 <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

- - - - - また - - - - - - - - -

String url = "";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
于 2017-03-30T11:35:26.037 に答える