Home Web Front-end JS Tutorial Simple interaction between android and js

Simple interaction between android and js

Apr 10, 2018 pm 01:39 PM
android javascript Simple

This article introduces the code about the simple interaction between android and js. Now I share it with everyone. Friends in need can refer to it

Permissions:



##MainActivity:

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

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

import android.content.DialogInterface;

import android.os.Bundle;

import android.support.v7.app.AlertDialog;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.view.ViewGroup;

import android.webkit.JsResult;

import android.webkit.WebChromeClient;

import android.webkit.WebSettings;

import android.webkit.WebView;

import android.webkit.WebViewClient;

import android.widget.Button;

 

 

/**

 * 注意事项:如何避免WebView内存泄露?

 * 不在xml中定义 Webview ,而是在需要的时候在Activity中创建,并且Context使用 getApplicationgContext()

 * <p>

 * 在 Activity 销毁( WebView )的时候,

 * 先让 WebView 加载null内容,然后移除 WebView,再销毁 WebView,最后置空

 */

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

 

 

    private WebView web;

    private Button but;

    private Button but2;

    private WebSettings settings;

    private Button but3;

 

 

 

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        but = findViewById(R.id.but);

        but2 = findViewById(R.id.but2);

        but3 = findViewById(R.id.but3);

        web = findViewById(R.id.web);

 

 

 

 

        but.setOnClickListener(this);

        but2.setOnClickListener(this);

        but3.setOnClickListener(this);

 

 

        //声明WebSettings子类

        settings = web.getSettings();

        //如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript

        settings.setJavaScriptEnabled(true);

        //设置自适应屏幕,两者合用

        settings.setUseWideViewPort(true); //将图片调整到适合webview的大小

        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        // 设置与Js交互的权限

        settings.setJavaScriptEnabled(true);

        // 设置允许JS弹窗

        settings.setJavaScriptCanOpenWindowsAutomatically(true);

        // 先载入JS代码

 

        // 复写shouldOverrideUrlLoading()方法,使得打开网页时不调用系统浏览器, 而是在本WebView中显示

        web.setWebViewClient(new WebViewClient() {

            @Override

            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                view.loadUrl(url);

                return true;

            }

        });

 

 

 

 

        // 由于设置了弹窗检验调用结果,所以需要支持js对话框

        // webview只是载体,内容的渲染需要使用webviewChromClient类去实现

        // 通过设置WebChromeClient对象处理JavaScript的对话框

        //设置响应js 的Alert()函数(回调方法)

        web.setWebChromeClient(new WebChromeClient() {

            @Override

            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

                AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);

                b.setTitle("Alter");

                b.setMessage(message);

                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        result.confirm();

                    }

                });

                b.setCancelable(false);

                b.create().show();

                return true;

            }

        });

 

 

 

 

 

 

 

 

 

 

    }

 

 

    @Override

    public void onClick(View view) {

        switch (view.getId()) {

            //获取本地html文件

            case R.id.but:

                web.loadUrl("file:///android_asset/index.html");

                break;

            //与js交互

            case R.id.but2:

 

 

                web.post(new Runnable() {

                        @Override

                        public void run() {

                            // 格式规定为:file:///android_asset/文件名.html

                            web.loadUrl("file:///android_asset/webview.html");

                            web.loadUrl("javascript:callJs()");

 

 

                        }

                    });

 

 

 

 

                break;

            case R.id.but3:

                web.loadUrl("http://www.baidu.com/");

 

 

                break;

 

 

        }

 

 

 

 

    }

 

 

 

 

    //销毁

    @Override

    protected void onDestroy() {

        if (web != null) {

            web.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);

            web.clearHistory();

 

 

            ((ViewGroup) web.getParent()).removeView(web);

            web.destroy();

            web = null;

        }

 

 

        super.onDestroy();

    }

}

 

 

xml:

<LinearLayout 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"

    android:orientation="vertical"

    tools:context="com.example.webview_js.MainActivity">

 

 

    <Button

        android:id="@+id/but"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="点我调用本地html文件" />

 

 

    <Button

        android:text="点我调用网站"

        android:id="@+id/but3"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" />

 

 

    <Button

        android:id="@+id/but2"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="点我与Js交互" />

 

 

    <WebView

        android:id="@+id/web"

        android:layout_width="match_parent"

        android:layout_height="match_parent"></WebView>

 

 

 

 

</LinearLayout>

 

 

html文件(js):

<!DOCTYPE html>

<html>

    <head>

        <meta charset="UTF-8">

        <title></title>

        <script>

             

            function callJs(){

                alert("android调用了JS的call方法")

            }

             

        </script>

    </head>

    <body>

         

         

    </body>

</html>

Copy after login

Related recommendations:

Detailed explanation of the steps of interaction between Ajax() and the background

##The use of jsbridge for the interaction between android and js

Ajax PHP data interaction implementation

The above is the detailed content of Simple interaction between android and js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship Sep 10, 2024 am 06:45 AM

OnePlus'sister brand iQOO has a 2023-4 product cycle that might be nearlyover; nevertheless, the brand has declared that it is not done with itsZ9series just yet. Its final, and possibly highest-end,Turbo+variant has just beenannouncedas predicted. T

See all articles