Android open browser from service avoiding multiple tabs
I am trying to open the browser window from my service with a link that opens in the current tab of the browser. when I use
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.google.com"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
If the browser was 开发者_C百科opened and in the foreground before my service starts the intent and the browser opens the link in the same window/tab. If the Browser was minimized and the service starts the intent, the browser opens the webpage in a new window/tab.
I cannot use a web-view as it needs to be in the web browser and it will only be dealing with the default browser. I have checked out the thread at Open an url in android browser, avoid multiple tabs but it did not have an answer. I also have tried force closing the browser but that is also does not work.
Thank you for any help!
If you want to use your app to fire that intent .. so call your app directly through package name check the following code:
Intent in = getPackageManager().getLaunchIntentForPackage("com.package.myappweb");
in.putExtra("myURL","http://www.google.com");
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity( in );
you can pass the URL through intent and get it in your app by:
String url=getIntent().getStringExtra("myURL");
if(url!=null){
/// launch app and use one tab for showing the webpage
}else{
//launch app normally.
}
the code you mentioned used for using app as web-app ..that will show popup window to use to pick up any browser to deal with the link .. not that would be for any app wanna open link
good luck,
The way to avoid multiple tabs is as follows:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
startActivity(intent);
The EXTRA_APPLICATION_ID will contain an ID of your app, and the browser will recycle a tab that was opened by your application, rather than opening a new tab. In this way, all the pages opened by your application will share the same tab, and you will not have "tab inflation" in the browser.
None of the solutions above involving Browser.EXTRA_APPLICATION_ID
work.
However, Google's Custom Tabs which is now the standard for opening URL's was easy to implement and works like a charm. Here's all you need to open a tab:
implementation "androidx.browser:browser:1.4.0"
String url = "https://google.com/";
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));
More can be found here.
精彩评论