您的位置:首页 > 编程语言 > Java开发

java和js交互1

2016-09-14 15:27 393 查看

java和js交互

安卓端的代码:

public class MainActivity extends Activity {

private WebView wb;
private ProgressBar pb;
private EditText uname;
private EditText pwd;
private Dialog dialog;
private SharedPreferences sp;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = getSharedPreferences("login", 0);
boolean b = sp.getBoolean("isrem", false);
if (b == true) {
System.out.println("aaa");
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
return;
}
init();
initWebView();
wb.addJavascriptInterface(new Object() {
//在Android4.0以后版本需要添加
@JavascriptInterface
public void yz(String name, String pwd) {
Intent intent = new Intent(MainActivity.this,
Main2Activity.class);
startActivity(intent);
SharedPreferences sp = getSharedPreferences("login", 0);
Editor edit = sp.edit();
edit.putBoolean("isrem", true);
edit.putString("name", name);
edit.putString("pwd", pwd);
edit.commit();
}
@JavascriptInterface
public void user(String ts) {
tc(ts);
}
@JavascriptInterface
public void pwd(String pwd) {
tc(pwd);
}
}, "javacode");
//加载assets下的文件
wb.loadUrl("file:///android_asset/form.html");

}
// 初始化控件
private void init() {
wb = (WebView) findViewById(R.id.wb);
pb = (ProgressBar) findViewById(R.id.pb);
//设置网页不跳到其他位置
wb.setWebViewClient(new WebViewClient());
wb.setWebChromeClient(new WebChromeClient() {

@Override
public void onProgressChanged(WebView view, int newProgress) {
// 显示进度条
pb.setVisibility(View.VISIBLE);
pb.setProgress(newProgress);
//当进度条等于100是 进度条消失
if (pb.getProgress() == newProgress) {
pb.setVisibility(View.GONE);
}
super.onProgressChanged(view, newProgress);
}

});

}
//初始化webview
private void initWebView() {
WebSettings set = wb.getSettings();
// 设置支持javascript
set.setJavaScriptEnabled(true);
}
public void tc(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("我是警示框");
builder.setMessage(msg);
builder.show();
}

}


html代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>

<script language="javascript">
function test(){

if(document.login.uname.value==""){

//alert("用户名不能为空!");
window.javacode.user("用户名不能为空");
}else if(document.login.upass.value==""){

//alert("密码不能为空!");
window.javacode.pwd("密码不能为空不能为空");
}else{

//alert("成功登录跳转Activity!");
window.javacode.yz(document.login.uname.value,document.login.upass.value);
}
}
</script>
</head>

<body>

<form  action="" name="login">

姓名: <input type="text" name="uname"/> <br/>
密码: <input type="password" name="upass"  /> <br/>
<input type="button" onClick="test()" value="登录"/>
</form>

</form>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: