1600

How to open an URL from code in the built-in web browser rather than within my application?

I tried this:

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

but I got an Exception:

No activity found to handle Intent{action=android.intent.action.VIEW data =www.google.com
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Arutha
  • 26,088
  • 26
  • 67
  • 80

43 Answers43

2849

Try this:

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

That works fine for me.

As for the missing "http://" I'd just do something like this:

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

I would also probably pre-populate your EditText that the user is typing a URL in with "http://".



In Kotlin:

if (!url.startsWith("http://") && !url.startsWith("https://")) {
    url = "http://$url"
}

val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(browserIntent)
Mark B
  • 183,023
  • 24
  • 297
  • 295
  • 2
    Except that your code and mbaird's aren't the same, from what I can tell for what's posted. Ensure that your URL has the `http://` scheme -- the exception shown suggests that your URL is lacking the scheme. – CommonsWare Feb 04 '10 at 18:31
  • 5
    Yes ! It missed the http:// ! The URL is entered by the user, is there a way to automatically format? – Arutha Feb 04 '10 at 18:44
  • It needed another ')' after '("http://www.google.com")', but other than that it worked. Thanks :-) – Techboy Jul 01 '10 at 21:47
  • 5
    URLUtil is a great way to check on user entered "url" Strings – Dan Jun 21 '11 at 19:30
  • When use Linkfy it is not nessesary to normalize url. Does anybody know proccess of transformation in Linkfy? – Kostadin Jan 12 '12 at 13:49
  • 109
    `if (!url.startsWith("http://") && !url.startsWith("https://"))` is a common error which may lead you to urls like http://file:/// and break some good usecases. Try to parse uri with URI class and check is there a schema. If no, add "http://" ;) – tuxSlayer Apr 19 '13 at 14:22
  • 1
    Encode the Query String If any special characters or spaces. then It will work awesome.For Example : String query="For martin Luther King"; query=URLEncoder.encode(query); String url="http://en.wikipedia.org/wiki/Special:Search?search="+query; Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent); – Chaitu Sep 06 '13 at 04:51
  • great answer. i splecial like if (!url.startsWith("http://") && !url.startsWith("https://")) url = "http://" + url; – user1324936 Nov 17 '13 at 21:24
  • What about if(!url.contains("://") ? This wouldn't break file:// and others – Torsten Ojaperv Oct 16 '14 at 08:50
  • 1
    User Apache UrlValidator for such operations: `UrlValidator.getInstance().isValid(url)` – To Kra Mar 06 '15 at 14:46
  • 28
    You need null check with [`resolveCheck`](https://developer.android.com/intl/ja/reference/android/content/Intent.html#resolveActivity(android.content.pm.PackageManager)). See the [offical docs](https://developer.android.com/intl/ja/guide/components/intents-common.html) : **Caution: If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object.** – kenju Aug 24 '15 at 05:09
  • 1
    @MarthaJames If there is a better way to accomplish this now please post it as an answer. – Mark B May 21 '16 at 13:14
  • **com.android.chrome E/chromium: [ERROR:layer_tree_host_impl.cc(2206)] Forcing zero-copy tile initialization as worker context is missing** – Iman Marashi Oct 14 '17 at 18:58
  • how i can use it without deep links variants on my app? –  May 26 '18 at 12:02
  • @kenju or just use a try-catch block and avoid touching the package manager altogether. https://developer.android.com/training/package-visibility – vctls Oct 18 '21 at 17:24
  • @kenju - now you can use the newer chooser, which also handles the state when a user has no apps to handle an action. startActivity(Intent.createChooser(browserIntent, null)); – mr.kostua Jan 31 '23 at 13:14
  • It looks like a custom tab is a right way to open web page in android app in the modern android development: https://developer.chrome.com/docs/android/custom-tabs/. Here is more information how to do it with supported all versions: https://developer.chrome.com/blog/custom-tabs-android-11/ – Gleichmut Jun 27 '23 at 13:48
  • @Gleichmut that's the way to display a web page _inside_ your current application, which I feel is really a different thing from what is being asked. Feel free to provide that as a separate answer to this question though. – Mark B Jun 27 '23 at 13:50
  • @MarkB, you are right, my bad - haven't read question carefully enough. There is a similar answer back to 2016r, I just extended it with more recent information via comments. – Gleichmut Jun 27 '23 at 13:53
148

A common way to achieve this is with the next code:

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

that could be changed to a short code version ...

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

or :

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

the shortest! :

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
83

Simple Answer

You can see the official sample from 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);
    }
}

How it works

Please have a look at the constructor of Intent:

public Intent (String action, Uri uri)

You can pass android.net.Uri instance to the 2nd parameter, and a new Intent is created based on the given data url.

And then, simply call startActivity(Intent intent) to start a new Activity, which is bundled with the Intent with the given URL.

Do I need the if check statement?

Yes. The docs says:

If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity(). If the result is null, you should not use the intent and, if possible, you should disable the feature that invokes the intent.

Bonus

You can write in one line when creating the Intent instance like below:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
Flimm
  • 136,138
  • 45
  • 251
  • 267
kenju
  • 5,866
  • 1
  • 41
  • 41
  • 3
    This presumes that the supplied url has **http** in it. – IgorGanapolsky May 15 '17 at 18:06
  • Check this out for handle https links on API 30+ https://stackoverflow.com/questions/2201917/how-can-i-open-a-url-in-androids-web-browser-from-my-application – Alexander Zhukov Aug 25 '21 at 05:18
  • This may have been correct in 2015, but these days intent.resolveActivity returns null even on devices that would have no problem viewing the https:// URL passed in. So it's kind of useless. Better to wrap in a try/catch. – Al Ro Jul 10 '23 at 22:14
68

In 2.3, I had better luck with

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

The difference being the use of Intent.ACTION_VIEW rather than the String "android.intent.action.VIEW"

MikeNereson
  • 3,890
  • 6
  • 24
  • 28
  • 1
    waht is the different ? – user1324936 Nov 17 '13 at 21:24
  • 1
    This answer helped me immensely. I do not know what the difference was, but we had an issue with 2.3 that this solved. Does anyone know what the difference in the implementation is? – Innova Dec 05 '13 at 21:29
  • 2
    According to Android Developer: this answer - "Create an intent with a given action. All other fields (data, type, class) are null." and the accepted answer - "Create an intent with a given action and for a given data url." – Teo Inke May 21 '15 at 19:14
35

The Kotlin answer:

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

I have added an extension on Uri to make this even easier

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

As a bonus, here is a simple extension function to safely convert a String to Uri.

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

fun String?.asUri(): Uri? {
    return try {
        Uri.parse(this)
    } catch (e: Exception) {
        null
    }
}
Akito
  • 115
  • 2
  • 7
Gibolt
  • 42,564
  • 15
  • 187
  • 127
33

Try this:

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

or if you want then web browser open in your activity then do like this:

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

and if you want to use zoom control in your browser then you can use:

settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
madlymad
  • 6,367
  • 6
  • 37
  • 68
nikki
  • 3,248
  • 3
  • 24
  • 29
  • 4
    Note that plugins and such are disabled in WebView, and that the INTERNET permissions would be required. ([reference](http://developer.android.com/reference/android/webkit/WebView.html)) –  Jun 10 '13 at 20:30
23

If you want to show user a dialogue with all browser list, so he can choose preferred, here is sample code:

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

}
Milad Yarmohammadi
  • 1,253
  • 2
  • 22
  • 37
Dmytro Danylyk
  • 19,684
  • 11
  • 62
  • 68
21

Just like the solutions other have written (that work fine), I would like to answer the same thing, but with a tip that I think most would prefer to use.

In case you wish the app you start to open in a new task, indepandant of your own, instead of staying on the same stack, you can use this code:

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

There is also a way to open the URL in Chrome Custom Tabs . Example in 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)
}
android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • Will making a new task protect the source app from bugs and crashing, in case the web browser have problems? – The Original Android Aug 14 '15 at 00:47
  • @TheOriginalAndroid I don't understand what it has to do with crashes and web browser. Please explain what you are trying to do. – android developer Aug 14 '15 at 10:49
  • Thanks for your response. Your post is interesting. What is the benefit of opening a new task especially for a web launch? – The Original Android Aug 14 '15 at 17:27
  • 3
    @TheOriginalAndroid Just so that the user will be able to switch back to your app, and then back again to the web browser. If you open recent-tasks screen, you will see 2 tasks here instead of one. Also, instead of seeing a web browser thumbnail in the single task (that belongs to your app's task), you will see 2 : one of your app, and another of the web browser. I think it's less confusing this way. – android developer Aug 14 '15 at 20:32
  • `FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET` is deprecated – Pratik Butani Jul 30 '19 at 09:13
18

other option In Load Url in Same Application using Webview

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
madlymad
  • 6,367
  • 6
  • 37
  • 68
Sanket
  • 499
  • 6
  • 8
  • Note that plugins and such are disabled in WebView, and that the INTERNET permissions would be required. ([reference](http://developer.android.com/reference/android/webkit/WebView.html)) –  Jun 10 '13 at 20:30
  • Also note that `.setJavaScriptEnabled(true);` is dangerous. – dan1st Mar 07 '21 at 15:35
12

You can also go this way

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

In java code :

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

 }

}

In Manifest dont forget to add internet permission...

Aristo Michael
  • 2,166
  • 3
  • 35
  • 43
10

So I've looked for this for a long time because all the other answers were opening default app for that link, but not default browser and that's what I wanted.

I finally managed to do so:

// 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, you can notice context.whatever, because I've used this for a static util method, if you are doing this in an activity, it's not needed.

CoolMind
  • 26,736
  • 15
  • 188
  • 224
bopol
  • 121
  • 1
  • 4
  • Thanks! Your answer helped avoid an "Open with" dialog. A link is opened in a browser directly without asking what application should process it (especially for DeepLink). – CoolMind Dec 29 '22 at 22:48
9

Webview can be used to load Url in your applicaion. URL can be provided from user in text view or you can hardcode it.

Also don't forget internet permissions in 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;
    }
}
Gorav Sharma
  • 410
  • 5
  • 7
  • 1
    This fixed my video issue: https://github.com/CrandellWS/VideoEnabledWebView/blob/master/app/src/main/java/name/cpr/ExampleActivity.java#L85 – CrandellWS Feb 15 '16 at 06:36
7

Within in your try block,paste the following code,Android Intent uses directly the link within the URI(Uniform Resource Identifier) braces in order to identify the location of your link.

You can try this:

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);
iSS
  • 2,598
  • 2
  • 14
  • 17
Kanwar_Singh
  • 133
  • 1
  • 2
  • 6
6

A short code version...

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


 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
6

Simple and Best Practice

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

Method 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*/
    }
Umasankar
  • 495
  • 7
  • 6
5

Short & sweet Kotlin helper function:

private fun openUrl(link: String) =
    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)))
xjcl
  • 12,848
  • 6
  • 67
  • 89
4
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
benka
  • 4,732
  • 35
  • 47
  • 58
Pradeep Sodhi
  • 2,135
  • 1
  • 19
  • 19
4

Simple, website view via intent,

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

use this simple code toview your website in android app.

Add internet permission in manifest file,

<uses-permission android:name="android.permission.INTERNET" /> 
madlymad
  • 6,367
  • 6
  • 37
  • 68
stacktry
  • 324
  • 3
  • 24
4

Chrome custom tabs are now available:

The first step is adding the Custom Tabs Support Library to your build.gradle file:

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

And then, to open a chrome custom tab:

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

For more info: https://developer.chrome.com/multidevice/android/customtabs

madlymad
  • 6,367
  • 6
  • 37
  • 68
francisco_ssb
  • 2,890
  • 1
  • 17
  • 23
  • Instead of adding an extra answer, I will leave it as a comment. Seems it is an only recommended way to open web page within the app: https://developer.chrome.com/docs/android/custom-tabs/. https://developer.chrome.com/blog/custom-tabs-android-11/ – Gleichmut Jun 27 '23 at 13:50
4

A new and better way to open link from URL in Android 11.

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

References:

https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9 and https://developer.android.com/training/package-visibility/use-cases#avoid-a-disambiguation-dialog

chia yongkang
  • 786
  • 10
  • 20
3
Intent getWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(MyLink));          
startActivity(getWebPage);
Abhishek Balani
  • 3,827
  • 2
  • 24
  • 34
  • welcome, newbie. please make the answer more complete, declaring variables that do not exist in original code. – tony gil Jul 17 '14 at 13:30
3

The response of MarkB is right. In my case I'm using Xamarin, and the code to use with C# and Xamarin is:

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

This information is taked from: https://developer.xamarin.com/recipes/android/fundamentals/intent/open_a_webpage_in_the_browser_application/

Juan Carlos Velez
  • 2,840
  • 2
  • 34
  • 48
2

Based on the answer by Mark B and the comments bellow:

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);
    }
}
divonas
  • 992
  • 1
  • 10
  • 11
2

This way uses a method, to allow you to input any String instead of having a fixed input. This does save some lines of code if used a repeated amount of times, as you only need three lines to call the method.

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

Using this method makes it universally usable. IT doesn't have to be placed in a specific activity, as you can use it like this:

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

Or if you want to start it outside an activity, you simply call startActivity on the activity instance:

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

As seen in both of these code blocks there is a null-check. This is as it returns null if there is no app to handle the intent.

This method defaults to HTTP if there is no protocol defined, as there are websites who don't have an SSL certificate(what you need for an HTTPS connection) and those will stop working if you attempt to use HTTPS and it isn't there. Any website can still force over to HTTPS, so those sides lands you at HTTPS either way


Because this method uses outside resources to display the page, there is no need for you to declare the INternet permission. The app that displays the webpage has to do that

Zoe
  • 27,060
  • 21
  • 118
  • 148
2

android.webkit.URLUtil has the method guessUrl(String) working perfectly fine (even with file:// or data://) since Api level 1 (Android 1.0). Use as:

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

In the Activity call:

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

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

Check the complete guessUrl code for more info.

I.G. Pascual
  • 5,818
  • 5
  • 42
  • 58
2

I checked every answer but what app has deeplinking with same URL that user want to use?

Today I got this case and answer is browserIntent.setPackage("browser_package_name");

e.g. :

   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);
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Vaibhav Kadam
  • 699
  • 1
  • 5
  • 21
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();
}

That error occurred because of invalid URL, Android OS can't find action view for your data. So you have validate that the URL is valid or not.

Mayur Sojitra
  • 690
  • 7
  • 19
2

Kotlin

startActivity(Intent(Intent.ACTION_VIEW).apply {
            data = Uri.parse(your_link)
        })
Cube
  • 362
  • 4
  • 8
1

I think this is the best

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

Put below code into global class

    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);
    }
Denis Royz
  • 118
  • 3
1

//OnClick Listener

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

//Your Util Method

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

    }
Fakhar
  • 3,946
  • 39
  • 35
1

Simply go with short one to open your Url in Browser:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
startActivity(browserIntent);
Gaurav Lambole
  • 273
  • 3
  • 3
  • possible to open it in the APP only, like within webview or something. –  Sep 06 '20 at 18:26
1

From Anko library method

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
    }
}
Vlad
  • 7,997
  • 3
  • 56
  • 43
1

kolin extension function.

 fun Activity.openWebPage(url: String?) = url?.let {
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(it))
    if (intent.resolveActivity(packageManager) != null) startActivity(intent)
}
Shivanand Darur
  • 3,158
  • 1
  • 26
  • 32
0

Check whether your url is correct. For me there was an unwanted space before url.

António Paulo
  • 351
  • 3
  • 18
Sonia John Kavery
  • 2,099
  • 2
  • 20
  • 36
0

Basic Introduction:

https:// is using that one into the "code" so that no one in between can read them. This keeps your information safe from hackers.

http:// is using just sharing purpose, it's not secured.

About Your Problem:
XML designing:

<?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>

Activity Designing:

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

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

You face Problems when implementing this:

  1. getting The Manifest permissions
  2. excess space's between url
  3. Check your url's correct or not
madlymad
  • 6,367
  • 6
  • 37
  • 68
ballu
  • 49
  • 1
  • 12
0

If you want to do this with XML not programmatically you can use on your TextView:

android:autoLink="web"
android:linksClickable="true"
Salam El-Banna
  • 3,784
  • 1
  • 22
  • 34
0

Try this one OmegaIntentBuilder

OmegaIntentBuilder.from(context)
                .web("Your url here")
                .createIntentHandler()
                .failToast("You don't have app for open urls")
                .startActivity();
T. Roman
  • 322
  • 6
  • 14
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;
    }
}
Tuan Nguyen
  • 2,542
  • 19
  • 29
0

Kotlin Developers can use this

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)
    }
Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82
0

Kotlin Solution

All the answers were opening the url in default app for that url. I wanted to always open any url in the browser. I needed some solution in kotlin and implemented the code below.

fun getPackageNameForUrl(context: Context, url: String): String? {
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    val resolveInfo = context.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)
    return resolveInfo?.activityInfo?.packageName
}

fun openInBrowser(context: Context, url: String) {
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    val packageName = getPackageNameForUrl(context, "http://")
    packageName?.takeIf { 
        it == "android" 
    }?.let { intent.setPackage(defaultBrowserPackageName); }
    startActivity(context, intent, null)
}
abhiarora
  • 9,743
  • 5
  • 32
  • 57
0

If you want to open a web browser, instead of your own application (applinks generate this issue), try this (Kotlin):

val emptyBrowserIntent = Intent()
emptyBrowserIntent.action = Intent.ACTION_VIEW
emptyBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE)
emptyBrowserIntent.data = Uri.fromParts("http", "", null)
val targetIntent = Intent()
targetIntent.action = Intent.ACTION_VIEW
targetIntent.addCategory(Intent.CATEGORY_BROWSABLE)
targetIntent.data = Uri.parse(urlLink)
targetIntent.selector = emptyBrowserIntent
activity?.startActivity(targetIntent)

The targetIntent.selector prevents your app from opening the link...Now the web browser will open it.

Thanks to the author of answer #16: https://issuetracker.google.com/issues/243678703?pli=1

Ramiro G.M.
  • 357
  • 4
  • 7
0

Jetpack Compose

If you are using jetpack compose, you need to get the context of your composable function first

val localContext = LocalContext.current
val browseIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com"))
startActivity(localContext, browseIntent, null)
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
-1

try this code

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>
pankaj
  • 1
  • 17
  • 36