Jak mogę otworzyć adres URL w przeglądarce internetowej Androida z mojej aplikacji?

Jak otworzyć adres URL z kodu we wbudowanej przeglądarce internetowej, a nie w mojej aplikacji?

Próbowałem tego:

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

Ale mam wyjątek:

No activity found to handle Intent{action=android.intent.action.VIEW data =www.google.com
Author: Sufian, 2010-02-04

30 answers

Spróbuj tego:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
To mi pasuje.

Co do brakującego" http:// " zrobiłbym coś takiego:

if (!url.startsWith("http://") && !url.startsWith("https://"))
   url = "http://" + url;

Prawdopodobnie również wstępnie wypełniłbym Twój EditText, że użytkownik wpisuje adres URL za pomocą " http://".

 2606
Author: Mark B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-01 09:59:14

Powszechnym sposobem na osiągnięcie tego celu jest użycie następnego kodu:

String url = "http://www.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url)); 
startActivity(i); 

Można to zmienić na krótką wersję kodu ...

Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.stackoverflow.com"));      
startActivity(intent); 

Lub:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")); 
startActivity(intent);
Najkrótsza! :
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));

Szczęśliwego kodowania!

 106
Author: Jorgesys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-17 13:59:35

Prosta Odpowiedź

Możesz zobaczyć oficjalną próbkę od dewelopera Androida.

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

Jak to działa

Proszę spojrzeć na konstruktor Intent:

public Intent (String action, Uri uri)

Możesz przekazać instancję android.net.Uri do 2. parametru, a na podstawie podanego adresu URL zostanie utworzona nowa Intencja.

A następnie po prostu zadzwoń startActivity(Intent intent), aby rozpocząć nową aktywność, która jest powiązana z intencją z podanym adresem URL.

Czy muszę sprawdzić if oświadczenie?

Tak. docs says:

Jeśli na urządzeniu nie ma aplikacji, które mogłyby otrzymać ukrytą intencję, aplikacja ulegnie awarii po wywołaniu funkcji startActivity (). Aby najpierw sprawdzić, czy aplikacja istnieje, aby otrzymać intencję, wywołaj resolveActivity () w obiekcie intencji. Jeśli wynik jest inny niż null, istnieje co najmniej jedna aplikacja, która może obsłużyć intencję i można bezpiecznie wywołać metodę startActivity(). Jeśli wynik jest null, nie należy używać intencji i, jeśli to możliwe, można powinien wyłączyć funkcję wywołującą intencję.

Bonus

Możesz pisać w jednej linii podczas tworzenia instancji Intent jak poniżej:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
 63
Author: kenju,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-21 14:37:23

W 2.3 miałem więcej szczęścia z

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

Różnica polega na użyciu Intent.ACTION_VIEW zamiast ciągu "android.intent.action.VIEW"

 62
Author: MikeNereson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-16 15:35:22

Spróbuj tego:

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

Lub jeśli chcesz, aby przeglądarka internetowa otworzyła się w Twojej aktywności, zrób tak:

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

I jeśli chcesz użyć sterowania zoomem w swojej przeglądarce, możesz użyć:

settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
 31
Author: nikki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-26 10:46:48

Jeśli chcesz pokazać użytkownikowi dialog z całą listą przeglądarek, aby mógł wybrać preferowany, oto przykładowy kod:

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

}
 22
Author: Dmytro Danylyk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-19 14:09:03

Tak jak inne rozwiązania napisali (że działa dobrze), chciałbym odpowiedzieć na to samo, ale z końcówką, że myślę, że większość wolałaby użyć.

Jeśli chcesz, aby aplikacja zaczęła się otwierać w nowym zadaniu, niezależnie od siebie, zamiast pozostać na tym samym stosie, możesz użyć tego kodu:

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

Istnieje również sposób otwarcia adresu URL w Chrome Custom Tabs . Przykład w Kotlinie:

@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)
}
 20
Author: android developer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-20 12:11:36

Inna opcja w załaduj adres Url w tej samej aplikacji przy użyciu Webview

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
 17
Author: Sanket,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-26 10:47:02

Możesz też iść tą drogą

W 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" />

W kodzie Javy:

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

 }

}

W manifeście nie zapomnij dodać uprawnień internetowych...

 12
Author: Aristo Michael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-28 11:02:58

Webview może być używany do ładowania adresu Url w aplikacji. Adres URL może być dostarczony przez użytkownika w widoku tekstowym lub można go kodować na twardo.

Nie zapomnij również o uprawnieniach internetowych w 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;
    }
}
 9
Author: Gorav Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-12 21:41:16

Wewnątrz w bloku try wklej poniższy kod,Android Intent używa bezpośrednio łącza w szelkach URI (Uniform Resource Identifier) w celu zidentyfikowania lokalizacji łącza.

Możesz spróbować tego:

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);
 7
Author: Kanwar_Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-21 14:34:55

Odpowiedź Kotlina:

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

Dodałem rozszerzenie na Uri aby to jeszcze ułatwić

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

Jako bonus, oto prosta funkcja rozszerzenia, aby bezpiecznie przekonwertować ciąg znaków na Uri.

"https://stackoverflow.com".asUri()?.openInBrowser(context)

fun String?.asUri(): Uri? {
    try {
        return Uri.parse(this)
    } catch (e: Exception) {}
    return null
}
 7
Author: Gibolt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-30 21:04:23

Krótka wersja kodu...

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


 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));
 6
Author: Jorgesys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-03 16:24:32

Proste i najlepsze praktyki

Metoda 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*/
            }

Metoda 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*/
    }
 5
Author: Umasankar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-11 07:34:16
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
 4
Author: Pradeep Sodhi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-04 08:03:06
Intent getWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(MyLink));          
startActivity(getWebPage);
 3
Author: Abhishek Balani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-17 12:40:53

ODPOWIEDŹ MarkB jest słuszna. W moim przypadku używam Xamarin, a kod do użycia z C# i Xamarin to:

var uri = Android.Net.Uri.Parse ("http://www.xamarin.com");
var intent = new Intent (Intent.ActionView, uri);
StartActivity (intent);

Ta informacja pochodzi z: https://developer.xamarin.com/recipes/android/fundamentals/intent/open_a_webpage_in_the_browser_application/

 3
Author: Juan Carlos Velez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-11 13:02:53

Chrome custom tabs są teraz dostępne:

Pierwszym krokiem jest dodanie biblioteki obsługi niestandardowych kart do Twojej kompilacji.plik gradle:

dependencies {
    ...
    compile 'com.android.support:customtabs:24.2.0'
}

A następnie, aby otworzyć niestandardową kartę chrome:

String url = "https://www.google.pt/";
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));

Aby uzyskać więcej informacji: https://developer.chrome.com/multidevice/android/customtabs

 3
Author: francisco_ssb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-26 10:47:35

Prosty, widok strony przez intent,

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

Użyj tego prostego kodu, aby wyświetlić swoją stronę w aplikacji na Androida.

Dodaj uprawnienia internetowe w pliku manifestu,

<uses-permission android:name="android.permission.INTERNET" /> 
 3
Author: stacktry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-26 10:48:03

Więc Szukałem tego przez długi czas, ponieważ wszystkie inne odpowiedzi otwierały domyślną aplikację dla tego linku, ale nie domyślna przeglądarka i tego chciałem.

W końcu udało mi się to zrobić:

// 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, można zauważyć context.cokolwiek, ponieważ użyłem tego do statycznej metody util, jeśli robisz to w działaniu, nie jest to potrzebne.

 3
Author: bopol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-01 09:19:36

Na podstawie odpowiedzi Marka B i komentarzy poniżej:

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);
    }
}
 2
Author: divonas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-16 06:35:33

android.webkit.URLUtil ma metodę guessUrl(String) działa doskonale (nawet z file:// lub data://) od Api level 1 (Android 1.0). Użyj jako:

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

W wywołaniu aktywności:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(URLUtil.guessUrl(download_link)));

if (intent.resolveActivity(getPackageManager()) != null)
    startActivity(intent);

Sprawdź całość guessUrl kod aby uzyskać więcej informacji.

 2
Author: I.G. Pascual,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-23 02:26:24

Dobra, sprawdziłem każdą odpowiedź, ale jaka aplikacja ma deeplinking z tym samym adresem URL, którego użytkownik chce użyć?

Dzisiaj dostałem tę sprawę i odpowiedź brzmi browserIntent.setPackage("browser_package_name");

Np.:

   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);
Dziękuję!
 2
Author: Vaibhav Kadam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-10 03:03:30

Wystarczy użyć krótkiego, aby otworzyć adres Url w przeglądarce:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
startActivity(browserIntent);
 2
Author: Gaurav Lambole,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-02 12:55:55
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();
}

Ten błąd wystąpił z powodu nieprawidłowego adresu URL, System Operacyjny Android nie może znaleźć widoku akcji dla Twoich danych. Musisz więc zweryfikować, czy adres URL jest poprawny, czy nie.

 2
Author: Mayur Sojitra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-22 02:38:41

Myślę, że to jest najlepsze

openBrowser(context, "http://www.google.com")

Wstaw poniższy kod do klasy globalnej

    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);
    }
 1
Author: Karthik Sridharan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-16 14:53:55

Ten sposób używa metody, aby umożliwić wprowadzanie dowolnego ciągu znaków zamiast stałego wejścia. Zapisuje to niektóre linie kodu, jeśli są używane wielokrotnie, ponieważ do wywołania metody potrzebne są tylko trzy linie.

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

Użycie tej metody sprawia, że jest ona uniwersalna. Nie musi być umieszczony w konkretnym ćwiczeniu, ponieważ można go używać w następujący sposób:

Intent i = getWebIntent("google.com");
if(i != null)
    startActivity();

Lub jeśli chcesz rozpocząć działanie poza aktywnością, po prostu wywołaj startActivity na aktywności instancja:

Intent i = getWebIntent("google.com");
if(i != null)
    activityInstance.startActivity(i);

Jak widać w obu tych blokach kodu jest null-check. Jest tak, ponieważ zwraca null, jeśli nie ma aplikacji do obsługi intencji.

Ta metoda domyślnie jest ustawiona na HTTP, jeśli nie ma zdefiniowanego protokołu, ponieważ istnieją strony internetowe, które nie mają certyfikatu SSL (czego potrzebujesz do połączenia HTTPS), a te przestaną działać, jeśli spróbujesz użyć HTTPS i go nie ma. Każda witryna może nadal wymuszać https, więc te strony lądują na HTTPS albo sposób


Ponieważ ta metoda wykorzystuje zewnętrzne zasoby do wyświetlania strony, nie ma potrzeby deklarowania uprawnień internetowych. Aplikacja, która wyświetla stronę internetową, musi to zrobić

 1
Author: Zoe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-02 16:01:39

/ / Onclick Listener

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

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

    }
 1
Author: Faakhir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-22 10:28:41

Kotlin

startActivity(Intent(Intent.ACTION_VIEW).apply {
            data = Uri.parse(your_link)
        })
 1
Author: Cube,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-04 09:02:13

Z Anko metoda biblioteczna

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
    }
}
 1
Author: Vlad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-13 08:08:48