[Android] Simple implementation of using the WebView component to open the web in the App

About the WebView component

For details, please refer to: Android: This is a comprehensive & detailed Webview usage guide

How to embed web in App

In the newly created android project, if you want to implement the embedded Web, you must set the access network permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>

After that, directly modify the layout file and activity:
main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

  <!--显示网页区域-->
    <WebView
        android:id="@+id/webView"
        android:layout_below="@+id/text_endLoading"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="10dp" />
</LinearLayout>

activity:

import android.app.Activity;
import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ForbiddenCityActivity extends Activity {
   private WebView webView;
     @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);             
    init();
  }

  private void init(){
    webView = (WebView) findViewById(R.id.webView);
 //需要加载的网页的url
    webView.loadUrl("....");
    WebSettings settings = webView.getSettings();
 // 如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript
    settings.setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient(){
       public boolean shouldOverrideUrlLoading(WebView view, String url){
         view.loadUrl(url);
         return true;
       }
  });

    webView.setWebViewClient(new WebViewClient() {
         @Override 
      public void onReceivedSslError(WebView view,SslErrorHandler handler, SslError error) {
       //等待证书响应
         handler.proceed(); 
      } 
   });
 }
} 

Use HTTPS

Since webView does not handle HTTPS requests by default, if the link used is HTTPS, add the following:

webView.setWebViewClient(new WebViewClient() {
         @Override 
      public void onReceivedSslError(WebView view,SslErrorHandler handler, SslError error) {
         handler.proceed();
      } 
   });

Reference: WebAPP Simple
Android: This is a comprehensive & detailed Webview usage guide

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325875248&siteId=291194637