Android和JS交互

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/I123456789T/article/details/89351821

1、实现过程,这里用本地的HTML文件,如果用线上相比简单一些,这里先先在本地新建一个文件夹,存放HTML文件,文件夹名为:assets 位置如图:

可以看到这个文件夹中有一个index.html文件,

2、接着新建一个xml布局:

test_html.xml:

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

    <Button
        android:id="@+id/btn_js"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="调用js方法"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:imeOptions="actionDone"/>

    <WebView
        android:id="@+id/web_html"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></WebView>


</LinearLayout>

3、下面是activity代码:

package com.example.weiwenyi.androidtest;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.example.weiwenyi.androidtest.util.OnSupportWebViewInterface;

/**
 * Created by weiwenyi on 2018/3/16.
 */

public class TestHtmlActivity extends AppCompatActivity {

    private WebView mWebView,webView;
    private Button btn_js;

//    private WebAppInterface appInterface;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadMessageForAndroid5;
    private int FILECHOOSER_RESULTCODE = 111;
    private int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 115;
    private OnSupportWebViewInterface webViewInterface;


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

        webView = new WebView(getApplicationContext());
        WebSettings settings = webView.getSettings();
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        mWebView = findViewById(R.id.web_html);
        btn_js = findViewById(R.id.btn_js);

        mWebView.loadUrl("file:///android_asset/index.html");
        //
        // http://www.auseeonlien.com:8092/operation/school/view/login/login.html
        mWebView.getSettings().setJavaScriptEnabled(true);

//        appInterface = new WebAppInterface(this);
        webViewInterface = new OnSupportWebViewInterface(this);
        mWebView.addJavascriptInterface(webViewInterface,"android");
//        mWebView.addJavascriptInterface(appInterface,"app");

        btn_js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("appInterface","--------------> 点击了 ");
                webViewInterface.showName("js调用android",mWebView);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient(){
            //扩展支持alert事件
//            @Override
//            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
//                builder.setTitle("xxx提示").setMessage(message).setPositiveButton("确定", null);
//                builder.setCancelable(false);
//                builder.setIcon(R.drawable.forum_comment);
//                AlertDialog dialog = builder.create();
//                dialog.show();
//                result.confirm();
//                return true;
//            }

            // For Android 4.1
            //3.0--版本
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooserImpl(uploadMsg);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooserImpl(uploadMsg);
            }
            // For Android > 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, WebChromeClient.FileChooserParams fileChooserParams) {
                openFileChooserImplForAndroid5(uploadMsg);
                return true;
            }
        });
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

        });
    }

    class WebAppInterface{

        private Context context;

        public WebAppInterface(Context context){
            this.context = context;
        }
        @JavascriptInterface
        public void sayHello(String name){
            Toast.makeText(context,"name : " + name,Toast.LENGTH_LONG).show();
        }

        public void showName(final String name){
            Log.i("appInterface","--------------> 进入方法 ");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl("javascript:showName('" + name + "')");
                }
            });

        }
        @JavascriptInterface
        public void showEditText(){
            Log.i("appInterface","--------------> 点击了输入框 ");
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }

    }



    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
    }

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadMessageForAndroid5 = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");

        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
            Log.d("地址","---1----->  " + result);
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;

        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadMessageForAndroid5)
                return;
            Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData();
            Log.d("地址","---2----->  " + result);
            if (result != null) {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
            } else {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
            }
            mUploadMessageForAndroid5 = null;
        }
    }


}

好了,直接运行,就测试就能看到效果,布局中有原生和网页两部分,通过互调,能看到效果,

猜你喜欢

转载自blog.csdn.net/I123456789T/article/details/89351821