对人关怀一次,比说千百句恭维话更能打动其心。——海涛法师

之前也说过了android使用闲置线程执行

今天上实战:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.ruben.simple_webview;

import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.os.MessageQueue;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private RelativeLayout mainLayout;
private WebView myWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
Button addWebViewButton = (Button) findViewById(R.id.addWebViewButton);

// 在主线程空闲时预加载 WebView
prepareWebView();

addWebViewButton.setOnClickListener(v -> {
if (myWebView.getParent() == null) {
// 设置WebView布局参数
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
myWebView.setLayoutParams(params);
mainLayout.addView(myWebView);
}
});
}

private void prepareWebView() {
myWebView = new WebView(new android.view.ContextThemeWrapper(this, null));
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

// 使用 IdleHandler 来初始化和加载 WebView
MessageQueue.IdleHandler idleHandler = () -> {
myWebView.loadUrl("https://gitee.com/VampireAchao");
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
return false; // 返回 false 表示不再调用此 IdleHandler
};
Looper.myQueue().addIdleHandler(idleHandler);
}

public class WebAppInterface {
Context mContext;

WebAppInterface(Context c) {
mContext = c;
}

@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
}

对应的activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/main_layout"
android:layout_height="match_parent">

<Button
android:id="@+id/addWebViewButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load WebView"
android:layout_centerInParent="true" />
</RelativeLayout>