背景
最近在自学Android, 看到WebView这里, 打算做一个简陋的自定义微端(其实就是Activity + WebView),并实现点击入口按钮谈出系统提示框,让用户选择程序打开网页功能。刚开始一直都是直接调用系统微端打开,无比郁闷,直到……
折腾过程
activity_browse.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
xmlns: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 = "";
}
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("")
intent = new Intent(Intent.ACTION_VIEW, uri)
intent.addCategory(Intent.CATEGORY_DEFAULT)
intent.putExtra("url", "")
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>
|