人人人人人人人人人人人人

Android JS interaction

WebView web;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web=(WebView) findViewById(R.id.web);
web.getSettings().setDefaultTextEncodingName("UTF-8") ;
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setAllowFileAccess(true);
web.addJavascriptInterface(new JsOperator(MainActivity.this),"JsInteraction");
web.loadData("test<script type="text/javascript">function showMsg(){JsInteraction.showDialog("Login start...");}", "text/html", "UTF-8");
//shareMsg("active ttt","ttttttt","test http://www.qq.com/ 测试","/assets/1.jpg");

}

package com.wgscd.gwang.myapplication;

/**

  • Created by gwang on 2017/3/14.
    */

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.webkit.JavascriptInterface;
import org.json.JSONObject;

public class JsOperator {

private Context context;

public JsOperator(Context context) {
    this.context = context;
}

/**
 * 弹出消息对话框
 */
@JavascriptInterface
public void showDialog(String message) {

    AlertDialog.Builder builder = new Builder(context);
    builder.setMessage(message);
    builder.setTitle("提示");
    builder.setPositiveButton("确认", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    builder.setNegativeButton("取消", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    builder.create().show();
}

/**
 * 获取登录的用户名和密码
 * @return JSON格式的字符串
 */
@JavascriptInterface
public String getLoginInfo(){
    try{
        JSONObject login = new JSONObject();
        login.put("Username", "YLD");
        login.put("Password", "111");

        return login.toString();
    }catch(Exception e){
        e.printStackTrace();
    }

    return null;
}

}

posted @ 2017-03-28 17:07  wgscd  阅读(375)  评论(0编辑  收藏  举报