Android让用户选择打开自定义浏览器

来源:互联网 发布:淘宝 自带 库存管理 编辑:程序博客网 时间:2024/06/05 07:59

背景

最近在自学Android, 看到WebView这里, 打算做一个简陋的自定义浏览器(其实就是Activity + WebView),并实现点击入口按钮谈出系统提示框,让用户选择程序打开网页功能。刚开始一直都是直接调用系统浏览器打开,无比郁闷,直到……

折腾过程

activity_browse.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"    tools:context="com.john.mydemo.BrowseActivity">    <WebView        android:id="@+id/my_webview"        android:layout_width="match_parent"        android:layout_height="match_parent">    </WebView></RelativeLayout>

BrowseActivity

@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_browse);        initView();    }    private void initView() {        Intent intent = getIntent();        String url = intent.getStringExtra("url");        if(TextUtils.isEmpty(url)) {            url = "http://www.baidu.com";        }        WebView webView = (WebView) findViewById(R.id.my_webview);        webView.setWebViewClient(new WebViewClient(){            @Override            public boolean shouldOverrideUrlLoading(WebView view, String url) {                view.loadUrl(url);                return true;            }        });        webView.loadUrl(url);    }

Minifest.xml

<activity android:name=".BrowseActivity" android:label="自定义浏览器" android:exported="true">            <intent-filter>                <action android:name="android.intent.action.VIEW" />                <category android:name="android.intent.category.DEFAULT" />            </intent-filter>        </activity>

MainActivity, 实现让用户选择浏览器打开功能

Uri uri = Uri.parse("http://www.baidu.com");intent = new Intent(Intent.ACTION_VIEW, uri);intent.addCategory(Intent.CATEGORY_DEFAULT);intent.putExtra("url", "http://www.baidu.com");PackageManager pm = getPackageManager();List<ResolveInfo> resolveList = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL);Log.i("MainActivity", "resolveList size:"+resolveList.size());if(resolveList.size() > 0) {    String title = "choose application";    Intent intentChooser = Intent.createChooser(intent, title);    startActivity(intentChooser);}else {    Toast.makeText(MainActivity.this, "no match activity to start!", Toast.LENGTH_SHORT).show();}

运行之后发现预期中系统谈出让用记选择程序的对话框并没有出现,而是直接调用系统浏览器打开网页了。 百思不得其解, 后来查看系统浏览器源码, 通过对比intent-filter的区别,加上自己实验。 发现只要加上scheme配置就可以了:

<intent-filter>    <action android:name="android.intent.action.VIEW" />    <category android:name="android.intent.category.DEFAULT" />    <data android:scheme="http" />    <data android:scheme="https" /></intent-filter>
1 0
原创粉丝点击