Why encapsulate an HTML5 (mobile) URL as an APP?

More and more developers are developing mobile Web pages using HTML5 +JavaScript. For now, it’s unclear whether HTML5 will replace mobile apps in the future. On the one hand, users do not like to input complex web addresses in the browser. On the other hand, Html5 is stored on the server side, which requires data transfer every time it is used, resulting in traffic waste. Some developers don’t want to deal with complex JAVA code, so is there a way to develop web applications in HTMl5 and simply package them as APK files? Of course there is, that is to use the Android Webview control.

I. Packaging steps:

1. Open Android Studio → Create a new project

Add a WebView control to activity_main. XML as follows:


      
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Copy the code

Mainactivity. Java = mainactivity. Java = mainactivity. Java

package net.zy13.html5;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebView;


public class MainActivity extends AppCompatActivity {
    private WebView webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // This is a BUG that causes the application to open directly after installation, and then press the home button to exit and open the application again
        if((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) ! =0) {
            // End your activity
            return;
        }
        // Hide title bar, set before loading layout (compatible with Android2.3.3 version)
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getSupportActionBar().hide();

        // Load the WebView control
        loadWebview();

        // Hide the active window
        //setContentView(R.layout.activity_main);
    }

    private void loadWebview(a) {
       Instantiate the WebView object
        webview = new WebView(this);
        // Set the WebView properties
        WebSettings ws = webview.getSettings();
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// Setting the layout causes the WebView to rearrange (relayout), default NARROW_COLUMNS
        ws.setLoadsImagesAutomatically(true);// Automatically load image resources
        ws.setUseWideViewPort(true);// Support HTML "viewPort" tags or use wide viewport
        ws.setLoadWithOverviewMode(true);// Shrink the content to fit the screen width
        ws.setJavaScriptEnabled(true);// Execute the javascript script
        ws.setGeolocationEnabled(true);// Enable location
        ws.setDomStorageEnabled(true);// Enable DOM storage API
        webview.requestFocus();
        webview.canGoForward();
        webview.canGoBack();
        webview.setScrollBarStyle(0);
        // Load the page to display
        webview.loadUrl("http://37.zy13.net/");
        // Set up the Web view
        setContentView(webview);
    }

    /** * Override the Activity class onKeyDown(int keyCoder,KeyEvent event) method@param keyCode
     * @param event
     * @return* /
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack(); //goBack() returns the previous WebView page
            return true;
        }
        return false; }}Copy the code

4. In the androidmanifest.xml manifest file, add network access permissions

<uses-permission android:name="android.permission.INTERNET"/>
Copy the code

5. Refer to the following article for the method of generating APK files using signature packaging

Blog.csdn.net/qq15577969/…

2, WebView WebSettings related Settings

WebSettings webSettings=webView.getSettings();
Copy the code

SetAllowContentAccess (Boolean allow) Specifies whether Content urls are allowed to be accessed in a WebView. Content Url access allows WebView to load content from content providers installed on the system.

SetAllowFileAccess (Boolean allow) Specifies whether file access is allowed. Note that only file:///android_asset and file:///android_res allow or disable access to the file system. Assets and resources files are still accessible using file:///android_res.

SetAllowFileAccessFromFileURLs (Boolean flag) is allowed to run in the environment of a URL (the context of a file scheme URL), should not be allowed to access content from other URL environments for security reasons. Also note that this setting only affects JavaScript access to file Schema resources; other forms of access, such as access from image HTML units, are not affected. To prevent the same domain policy from infringing ICE_CREAM_SANDWICH and older models, you should explicitly set this value to false.

SetAllowUniversalAccessFromFileURLs (Boolean flag) is allowed to run in a file schema of JavaScript URL environment access content from any other source, Including other file Schema URLs. See setAllowFileAccessFromFileURLs (Boolean), in order to ensure safety, should be set to not allow, note that this setting only affect the file schema JavaScript to access resources, other forms of access, For example, access from the image HTML unit is not affected. To prevent the same domain policy from infringing ICE_CREAM_SANDWICH and older models, you should explicitly set this value to false. The default value is true for ICE_CREAM_SANDWICH_MR1 and older versions, and false for JELLY_BEAN and newer versions

SetAppCacheEnabled (Boolean Flag) Whether the application cache API is available. The default value is false. This parameter is used in conjunction with setAppCachePath(String).

SetAppCachePath (String) Sets the path of the application cache file. In order for the application caching API to be available, this method must pass in an application writable path. This method is executed only once, and repeated calls are ignored.

SetAppCacheMaxSize (Long appCacheMaxSize) is not used. Set the maximum value of the application cache. The passed value is approximated to the best approximation supported by the database, so this is an indicator value rather than a fixed value. If the value passed is smaller than the database size, the database will not resize. The default value is MAX_VALUE. You are advised to set the default value to the maximum value.

SetBlockNetworkImage (Boolean flag) Whether to forbid image resources from the network (resources accessed through HTTP and HTTPS URI schemes). The default value is false. Note that unless getLoadsImagesAutomatically () returns true, otherwise, the method is invalid. Also note that even if this is set to false, using setBlockNetworkLoads(Boolean) to block all network loads will prevent network images from loading. When this setting changes from true to false, the web image resource referenced by the current WebView display is automatically retrieved.

SetBlockNetworkLoads (Boolean flag) Whether downloading data from the network is prohibited. The default value is false if the app has INTERNET access, and true otherwise. Using setBlockNetworkImage(Boolean) will only prevent image resources from loading. Note that this value changes from true to false. Network resources referenced by the current WebView presentation are not automatically loaded until an overload is invoked. If the APP does not have INTERNET permissions, setting this value to false throws a SecurityException.

SetBuiltInZoomControls (Boolean Enabled) Whether to use the built-in zooming mechanism. The built-in zooming mechanism includes on-screen zooming controls that float above WebView content and the use of zooming gestures. SetDisplayZoomControls (Boolean) controls whether to display these controls. The default is false.

SetCacheMode (int mode) overrides the use of caching, default LOAD_DEFAULT. The way the cache is used is based on the navigation type, normal page loading, detection of the cache, and reoccurrence of cached content as needed. When the navigation returns, the content does not reappear, only from the cache disk. This method allows a client to override its behavior by specifying one of LOAD_DEFAULT, LOAD_CACHE_ELSE_NETWORK, LOAD_NO_CACHE, or LOAD_CACHE_ONLY.

SetCursiveFontFamily (String font) setCursiveFontFamily (String font) setCursiveFontFamily (String font)

SetDatabaseEnabled (Boolean Flag) Whether the database storage API is available. The default value is false. See setDatabasePath(String) for how to set the data store API correctly. This setting is valid for all WebView instances in the same process. Note that this can only be changed before any WebView of the current process loads the page, because the WebView implementation class may ignore this change after this node.

SetDatabasePath (String databasePath) is deprecated. The databasePath is managed by implementation. Calling this method is invalid. Set the storage path of the database. To ensure that the database runs correctly, this method must use a path that can be written to the application. This method can only be executed once, and repeated calls are ignored.

SetDefaultFixedFontSize (int size) Sets the default fixed font size. The default is 16. The value can be 1 to 72

SetDefaultFontSize (int size) Sets the default font size. The default font size is 16. The value can be 1 to 72

SetDefaultTextEncodingName (String encoding) to set the default character encoding set, the default “utf-8”.

SetDefaultZoom (webSettings. ZoomDensity Zoom) is not used. Set the default zoom density, which must be called in the UI thread. The default is MEDIUM. This setting is not recommended for new applications. If the WebView is used to display mobile pages, you can adjust the ‘width’ and ‘initial-scale’ attributes in the ‘meta ViewPort’ tag of the page to achieve the desired effect. You can use setInitialScale(int) and setUseWideViewPort(Boolean).

SetDisplayZoomControls (Boolean Enabled) Specifies whether to display zooming controls when using the built-in zooming mechanism. The default is true. See setBuiltInZoomControls (Boolean).

SetDomStorageEnabled (Boolean Flag) Whether the DOM storage API is available. The default value is false.

SetEnableSmoothTransition (Boolean enable) has been abandoned, the future will become empty (no – op) operation, or keep the current Settings when panning or zooming WebView window is not on whether to allow the smooth transition, if it is true, WebView chooses a solution that maximizes performance. For example, the content of the WebView may not be updated during transitions. If false, the WebView remains fidelity. The default is false.

SetFantasyFontFamily (String font) Sets the name of the fantasy font set to “fantasy” by default

SetFixedFontFamily (String font) Sets the name of the fixed font set. The default is “monospace”.

SetGeolocationDatabasePath (String databasePath) positioning database save path, in order to ensure the position the permissions and cache persistence, this method should be introduced into the path of an application can write.

SetGeolocationEnabled (Boolean Flag) Determines whether it is available. The default value is true. Please note that in order to ensure that the location API is available in WebView pages, the following conventions must be followed: (1) The app must have location permissions, see ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION; (2) the app must provide onGeolocationPermissionsShowPrompt (String, GeolocationPermissions. Callback) Callback methods of implementation, Receive notifications when a page is located via a JavaScript location API request. As an option, can be stored in the database history position and Web initial permissions, see setGeolocationDatabasePath (String).

SetJavaScriptCanOpenWindowsAutomatically (Boolean flag) for JavaScript to automatically open the window, the default is false. Applies to the JavaScript method window.open().

SetJavaScriptEnabled (Boolean flag) Sets whether the WebView allows JavaScript to be executed. The default value is false.

SetLayoutAlgorithm (WebSettings LayoutAlgorithm l) set up the layout, will cause the WebView to layout (relayout), the default value NARROW_COLUMNS

SetLightTouchEnabled (Boolean Enabled) Deprecated. Starting with JELLY_BEAN, this setting is invalid. Allows selection and cursor hover using a touch.

SetLoadWithOverviewMode (Boolean Overview) Specifies whether a WebView is allowed to load a page in an overview manner. The default is false. Shrink content to fit the screen width. This setting takes effect when the content width exceeds the width of the WebView control, such as when getUseWideViewPort() returns true.

SetLoadsImagesAutomatically (Boolean flag) whether the WebView download image resources, the default is true. Note that this method controls the download of all images, including those embedded with URIs (use setBlockNetworkImage(Boolean) to control only the download of images using network URIs). If the value of this setting changes from false to true, all image resources referenced by the WebView display will be automatically downloaded.

SetMediaPlaybackRequiresUserGesture (Boolean) require the WebView whether media player need the user’s gestures, the default value is true.

SetMinimumFontSize (int size) Sets the minimum font size. Default is 8

SetMinimumLogicalFontSize (int size) set minimum local shop name, the default is 8.

SetMixedContentMode (int Mode) Configures the behavior of a WebView when a secure source (Origin) tries to load a resource from an insecure source. By default, KITKAT and lower versions default to MIXED_CONTENT_ALWAYS_ALLOW, LOLLIPOP version default to MIXED_CONTENT_NEVER_ALLOW, The safest operation mode preferred by WebView is MIXED_CONTENT_NEVER_ALLOW. MIXED_CONTENT_ALWAYS_ALLOW is discouraged.

SetNeedInitialFocus (Boolean flag) Specifies whether to set the node to get focus when requestFocus(int, android.graphics.rect) is called. The default value is true.

SetOffscreenPreRaster (Boolean Enabled) Raster Tiles when the WebView is switched to background but still associated with the window. Turning it on avoids redrawing when the WebView is switched from background to foreground. Default: false. In this mode, the background WebView takes up more memory. Please display memory usage according to the following criteria:

The WebView cannot be larger than the screen size of the device; Limit this pattern to a few WebViews; Use on visible webViews and upcoming WebViews; SetPluginState (webSettings.pluginState) is deprecated above API18. Plugins will not be supported in the future, do not use them. Tells WebView to enable, disable, or have a plug-in on demand. Out-of-the-box mode means that if a plug-in exists that can process embedded content, a placeholder icon is displayed and turned on when clicked. The default value is OFF.

SetRenderPriority (WebSettings RenderPriority priority) above API18 has been abandoned. Adjusting thread priority is not recommended and will not be supported in future releases. Set the priority of the Render thread. Unlike other Settings, only one call is required in the same process, the default is NORMAL.

SetSansSerifFontFamily (String font) Sets the name of the Sans-Serif font family. The default value “sans-serif”.

SetSaveFormData (Boolean save) Specifies whether the WebView saves form data. The default value is true.

SetSavePassword (Boolean save) API18 earlier versions are obsolete. Saving passwords in webViews will not be supported in future versions. Sets whether the WebView saves the password. The default is true.

SetSerifFontFamily (String font) Sets the name of the Serif font family, which defaults to “sans-serif”.

SetStandardFontFamily (String font) Sets the name of the standard font set, default “sans-serif”.

SetSupportMultipleWindows (Boolean support) sets whether the WebView supports multiple Windows. If set to true, the main program implements onCreateWindow(WebView, Boolean, Boolean, Message), which is false by default.

SetSupportZoom (Boolean support) Whether WebView supports zooming using on-screen zoom controls and gestures. The default value is true. Set setBuiltInZoomControls(Boolean) to use a special scaling mechanism. This setting does not affect zoomIn() and zoomOut() zooming operations.

SetTextSize (WebSettings.TextSize t) API version 14 is deprecated. Use setTextZoom(int) instead. Set the size of the page text, NORMAL by default.

SetTextZoom (int textZoom) Sets the percentage zoom of text on the page. Default is 100.

SetUseWideViewPort (Boolean use) Whether the WebView supports the HTML “ViewPort” tag or uses a wide Viewport. When set to true, the width of the layout is always the same as the device-dependent Pixels width on the WebView control. When true and the page contains the ViewPort tag, the width specified by the tag will be used. If the page does not contain a label or the label does not provide a width, use a Wide ViewPort.

SetUserAgentString (String UA) Sets the WebView user agent String. If the string is null or empty, the system default value is used. Note that starting with the KITKAT version, changing the user agent when loading a web page causes the WebView to be initialized again.

SupportMultipleWindows () gets the value of whether the WebView supports multiple Windows.

SupportZoom () Gets the value of whether the WebView supports zooming

3. Bug solution

Net ::ERR_CLEARTEXT_NOT_PERMITTED net::

2. Cause analysis:

Since Android 9.0 (API level 28), plaintext support is disabled by default, so HTTP urls cannot load properly in webViews!

3. Solutions:

In the androidmanifest.xml manifest file, add the following configuration to the application node

android:usesCleartextTraffic="true"
Copy the code
<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
Copy the code