Android与H5互调

2018-10-02  本文已影响2人  GeekGray

阅读原文

1. 案例主页面

1.创建工程名AndroidAndH5

2_布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.atguigu.androidandh5.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@android:color/holo_blue_light"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Android和H5互动"
            android:textColor="@android:color/black"
            android:textSize="20sp" />
    </LinearLayout>

    <Button
        android:id="@+id/btn_java_and_js"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="1.Java代码和H5代码互动"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

    <Button
        android:id="@+id/btn_js_call_java"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="2.H5调用Android播放视频"
        android:textColor="@android:color/black"
        android:textSize="20sp" />
    <Button
        android:id="@+id/btn_js_call_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="3.H5调用Android拨打电话"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

</LinearLayout>

3_初始化布局

public class MainActivity extends Activity implements View.OnClickListener {

    private Button btnJavaAndJs;
    private Button btnJsCallJava;
    private Button btnJsCallPhone;

    /**
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2016-07-28 10:58:01 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void findViews() {
        btnJavaAndJs = (Button)findViewById( R.id.btn_java_and_js );
        btnJsCallJava = (Button)findViewById( R.id.btn_js_call_java );
        btnJsCallPhone = (Button)findViewById( R.id.btn_js_call_phone );

        btnJavaAndJs.setOnClickListener( this );
        btnJsCallJava.setOnClickListener( this );
        btnJsCallPhone.setOnClickListener( this );
    }
    /**
     * Handle button click events<br />
     * <br />
     * Auto-created on 2016-07-28 10:58:01 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    @Override
    public void onClick(View v) {
        if ( v == btnJavaAndJs ) {
            // Handle clicks for btnJavaAndJs
        } else if ( v == btnJsCallJava ) {
            // Handle clicks for btnJsCallJava
        } else if ( v == btnJsCallPhone ) {
            // Handle clicks for btnJsCallPhone
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
    }
}

2_Android和H5互调案例-java调用js

1_AndroidAndJSActivity布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@android:color/holo_blue_light"
        android:gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="登录页面"
            android:textColor="@android:color/black"
            android:textSize="20sp" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/bg_shap"
            android:orientation="vertical"
            android:padding="5dp">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="账号:"
                android:textColor="#000000" />
            <EditText
                android:id="@+id/et_number"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="请输入账号..."
                android:textColor="#000000" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="密码:"
                android:textColor="#000000" />

            <EditText
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="请输入密码..."
                android:password="true"
                android:textColor="#000000" />

            <Button
                android:id="@+id/btn_login"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="登录"
                android:textColor="#000000"
                android:textSize="25sp" />

        </LinearLayout>
    </LinearLayout>

</LinearLayout>

2_布局初始化

public class JavaAndJSActivity  extends Activity implements View.OnClickListener {
    private EditText etNumber;
    private EditText etPassword;
    private Button btnLogin;
    /**
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2016-07-28 11:43:37 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void findViews() {
        setContentView(R.layout.activity_java_and_js);
        etNumber = (EditText)findViewById( R.id.et_number );
        etPassword = (EditText)findViewById( R.id.et_password );
        btnLogin = (Button)findViewById( R.id.btn_login );

        btnLogin.setOnClickListener( this );
    }
    /**
     * Handle button click events<br />
     * <br />
     * Auto-created on 2016-07-28 11:43:37 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    @Override
    public void onClick(View v) {
        if ( v == btnLogin ) {
            // Handle clicks for btnLogin
            login();
        }
    }
    private void login() {
        String numebr = etNumber.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        if (TextUtils.isEmpty(numebr)||TextUtils.isEmpty(password)){
            Toast.makeText(JavaAndJSActivity.this, "账号或者密码为空", Toast.LENGTH_SHORT).show();
        }else{
            //登录
          }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        findViews();
       initWebView()//初始化
    }
}

3_初始化WebView并且加载网络页面

private void initWebView() {
        webView = new WebView(this);
        WebSettings webSettings = webView.getSettings();
        //设置支持javaScript脚步语言
        webSettings.setJavaScriptEnabled(true);

        //支持双击-前提是页面要支持才显示
        webSettings.setUseWideViewPort(true);

        //支持缩放按钮-前提是页面要支持才显示
        webSettings.setBuiltInZoomControls(true);

        //设置客户端-不跳转到默认浏览器中
        webView.setWebViewClient(new WebViewClient());

        //加载网络资源
        webView.loadUrl("http://atguigu.com/teacher.shtml");
//        webView.loadUrl("file:///android_asset/JavaAndJavaScriptCall.html");

        //显示页面
        setContentView(webView);
    }

4_在工程main目录下创建assets目录且加载本地资源

webView.loadUrl("file:///android_asset/JavaAndJavaScriptCall.html");

5_Java调用javaScript

/**
 * Java调用javaScript
 * @param numebr
 */
private void login(String numebr) {
    webView.loadUrl("javascript:javaCallJs("+"'"+numebr+"'"+")");
    setContentView(webView);
}

3_JavaScript调java

1_配置Javascript接口

//设置支持js调用java
webView.addJavascriptInterface(new AndroidAndJSInterface(),"Android");

2_实现Javascript接口类

/**
 * js可以调用该类的方法
 */
class AndroidAndJSInterface{
        public void showToast(){
        Toast.makeText(JavaAndJSActivity.this, "我被js调用了",  Toast.LENGTH_SHORT).show();
    }
}

3_解决该WebView.addJavascriptInterface接口不起作用的两种办法

1_针对版本改成16

apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
    defaultConfig {
        applicationId "com.atguigu.androidandh5"
        minSdkVersion 14
        targetSdkVersion 16
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
}

2_在JavaScript接口类的方法加上

@JavascriptInterface注解
/**
 * js可以调用该类的方法
 */
class AndroidAndJSInterface{
    @JavascriptInterface
    public void showToast(){
        Toast.makeText(JavaAndJSActivity.this, "我被js调用了", Toast.LENGTH_SHORT).show();
    }
}

4_H5页面调用Android播放视频

1_JsCallJavaVideoActivity的布局和实例化控件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.atguigu.androidandh5.JsCallJavaVideoActivity">

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

</RelativeLayout>

实例化控件并且配置

public class JsCallJavaVideoActivity extends Activity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_js_call_java_video);
        webView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = webView.getSettings();
        //设置支持javaScript脚步语言
        webSettings.setJavaScriptEnabled(true);

        //支持双击-前提是页面要支持才显示
//        webSettings.setUseWideViewPort(true);

        //支持缩放按钮-前提是页面要支持才显示
        webSettings.setBuiltInZoomControls(true);

        //设置客户端-不跳转到默认浏览器中
        webView.setWebViewClient(new WebViewClient());
      
        //加载网络资源
//        webView.loadUrl("http://atguigu.com/teacher.shtml");
         webView.loadUrl("file:///android_asset/RealNetJSCallJavaActivity.htm");

    }

 }

2_加载页面

//加载本地资源        webView.loadUrl("file:///android_asset/RealNetJSCallJavaActivity.htm");

3_参照js代码写Java被调用代码

url = "/mobiles/interActive/65411";
var videourl = "http://10.0.2.2:8080/yellow.mp4";
var itemid = "65411";
var itemdesc = "1级单杀小龙,5级单杀峡谷先锋!";    
var itempic = "http://avatar.anzogame.com/pic_v1/lol/news/20160507/spic65411h572d6eaf.jpg";
var itemtitle = "6.9玛尔扎哈OP套路教程";
var obj_play = document.getElementById('play');
var obj_download = document.getElementById('download');
if(obj_play != null) {
    obj_play.ontouchstart = function() {
        this.className = 'inter_click';
        javascript:android.playVideo(itemid, videourl, itemtitle);
        ajaxrequest('/stat/item', "POST", true, {type:'play', id:itemid});
    }
    obj_play.ontouchend = function() {
        this.className = 'inter';
    }
}

3_配置Javascript接口

//设置支持js调用java
webView.addJavascriptInterface(new AndroidAndJSInterface(),"android");

4_Javascript接口类

class AndroidAndJSInterface {
    /**
     * 该方法将被js调用
     * @param id
     * @param videoUrl
     * @param tile
     */
    @JavascriptInterface
    public void playVideo(int id,String videoUrl,String tile){
        //调起系统所有播放器
        Intent intent = new Intent();
        intent.setDataAndType(Uri.parse(videoUrl),"video/*");
        startActivity(intent);
    }
}

5_H5页面调用Android拨打电话

1_JsCallJavaCallPhoneActivity布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.atguigu.androidandh5.JsCallJavaVideoActivity">

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

</RelativeLayout>

2_初始化WebView并且配置

  private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_js_call_java_video);
        webView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = webView.getSettings();
        //设置支持javaScript脚步语言
        webSettings.setJavaScriptEnabled(true);

        //支持双击-前提是页面要支持才显示
//        webSettings.setUseWideViewPort(true);

        //支持缩放按钮-前提是页面要支持才显示
        webSettings.setBuiltInZoomControls(true);

        //设置客户端-不跳转到默认浏览器中
        webView.setWebViewClient(new WebViewClient());

        //设置支持js调用java
        webView.addJavascriptInterface(new AndroidAndJSInterface(), "Android");

        //加载本地资源
//        webView.loadUrl("http://atguigu.com/teacher.shtml");
        webView.loadUrl("file:///android_asset/JsCallJavaCallPhone.html");

    }

3_加载JsCallJavaCallPhone.html页面

//加载本地资源
//    webView.loadUrl("http://atguigu.com/teacher.shtml");
     webView.loadUrl("file:///android_asset/JsCallJavaCallPhone.html");

4_从java代码传递json数据给javascript

class AndroidAndJSInterface {
    /**
     * 该方法将被js调用,用于加载数据
     */
    @JavascriptInterface
    public void showcontacts() {
        // 下面的代码建议在子线程中调用
        String json = "[{\"name\":\"阿福\", \"phone\":\"18600012345\"}]";
        // 调用JS中的方法
        webView.loadUrl("javascript:show('" + json + "')");
    }

 }

5_拨打电话代码

 class AndroidAndJSInterface {
        /**
         * 该方法将被js调用,用于加载数据
         */
        @JavascriptInterface
        public void showcontacts() {
            // 下面的代码建议在子线程中调用
            String json = "[{\"name\":\"阿福\", \"phone\":\"18600012345\"}]";
            // 调用JS中的方法
            webView.loadUrl("javascript:show('" + json + "')");
        }
        /**
         * 拨打电话
         * @param phone
         */
        public void call(String phone) {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
//           startActivity(intent);
        }
    }

6_添加拨打电话权限

<uses-permission android:name="android.permission.CALL_PHONE"/>

7_解决无法播放电话的两种方法

1_针对的版本改为底版本例如16

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.atguigu.androidandh5"
        minSdkVersion 14
        targetSdkVersion 16
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
}

2_使用新方式

class AndroidAndJSInterface {
    /**
     * 该方法将被js调用,用于加载数据
     */
    @JavascriptInterface
    public void showcontacts() {
        // 下面的代码建议在子线程中调用
        String json = "[{\"name\":\"阿福\", \"phone\":\"18600012345\"}]";
        // 调用JS中的方法
        webView.loadUrl("javascript:show('" + json + "')");
    }

    /**
     * 拨打电话
     * @param phone
     */
    @JavascriptInterface
    public void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
        if (ActivityCompat.checkSelfPermission(JsCallJavaCallPhoneActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        startActivity(intent);

    }
}

6_加网络的H5页面

1_把整个assets目录资源拷贝到tomcat服务器上

2_加载网络资源

JavaAndJavaScriptCall页面
//加载网络资源
webView.loadUrl("http://10.0.2.2:8080/assets/JavaAndJavaScriptCall.html");


JsCallJavaVideoActivity页面
webView.loadUrl("http://10.0.2.2:8080/assets/RealNetJSCallJavaActivity.htm");


JsCallJavaCallPhoneActivity
webView.loadUrl("http://10.0.2.2:8080/assets/JsCallJavaCallPhone.html");
上一篇下一篇

猜你喜欢

热点阅读