Android中的WebView实战详解(二)

时间:2022-07-20 15:11:56

四、如何用WebView下载软件?

四、如何用WebView下载软件?

public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private Button mBack;
private TextView mTitleView;
private Button mRefresh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mBack = (Button) findViewById(R.id.back);
mTitleView = (TextView) findViewById(R.id.titleView);
mRefresh = (Button) findViewById(R.id.refresh);
mBack.setOnClickListener(new MyListener());
mRefresh.setOnClickListener(new MyListener()); mWebView = (WebView) findViewById(R.id.webView);
mWebView.loadUrl("http://shouji.baidu.com/");
//该方法作用为当一个网页跳转另一个网页时,仍然在当前webview中显示
mWebView.setWebViewClient(new WebViewClient());
//该方法是接收标题
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public void onReceivedTitle(WebView view, String title) {
mTitleView.setText(title);
super.onReceivedTitle(view, title);
}
}); mWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String s, String s1, String s2, String s3, long l) {
Uri uri = Uri.parse(s);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
}); }
class MyListener implements View.OnClickListener { @Override
public void onClick(View view) {
switch (view.getId()){
case R.id.back:
finish();
break;
case R.id.refresh:
mWebView.reload();
break;
default:
break;
}
}
}
}