作者:郭健曲 | 来源:互联网 | 2023-06-24 12:13
publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);se
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cOntentWebView= (WebView) findViewById(R.id.webview);
msgView = (TextView) findViewById(R.id.msg);
// 启用Javascript
contentWebView.getSettings().setJavascriptEnabled(true);
// 从assets目录下面的加载html
contentWebView.loadUrl("http://60.29.255.184/api/android/setCOOKIE");
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(btnClickListener);
contentWebView.addJavascriptInterface(this, "wst");
OnClickListener btnClickListener = new Button.OnClickListener() {
public void onClick(View v) {
// 无参数调用
// contentWebView.loadUrl("Javascript:javacalljs()");
// // 传递参数调用
// contentWebView.loadUrl("Javascript:javacalljswithargs(" + "'hello world'" + ")");
COOKIESyncManager.createInstance(MainActivity.this);
COOKIEManager COOKIEManager = COOKIEManager.getInstance();
COOKIEManager.setAcceptCOOKIE(true);
COOKIEManager.getCOOKIE("http://60.29.255.184");
System.out.println("--------------- 1 ----------------------"+COOKIEManager.getCOOKIE("http://60.29.255.184"));
//第一次往COOKIE中新增值;
COOKIEManager.setCOOKIE("http://60.29.255.184", "VodKeySid=f9d8d0cb5badcfb2f7803b64100574dd.120");
//替换COOKIE中的值;
COOKIEManager.setCOOKIE("http://60.29.255.184", "VodKeySid=f9d8d0cb5badcfb2f7803b64100574dd.110");
System.out.println("--------------- 3 ----------------------");
System.out.println("----------------- 4 --------------------"+COOKIEManager.getCOOKIE("http://60.29.255.184"));
COOKIESyncManager.getInstance().sync();
contentWebView.loadUrl("http://60.29.255.184/api/android/getCOOKIE");
}
public void startFunction() {
Toast.makeText(this, "js调用了java函数", Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
@Override
public void run() {
msgView.setText(msgView.getText() + "\njs调用了java函数");
}
});
public void startFunction(final String str) {
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
@Override
public void run() {
msgView.setText(msgView.getText() + "\njs调用了java函数传递参数:" + str);
}
});
}
}
此代码测试无误,通过查看Sqlite中的记录 ,确实COOKIE已经新增,而且能够完成修改;
adb shell
包下面的文件目录
由于COOKIE存放在数据库中
打开webview的数据库
查看COOKIE中的值
测试机:android虚拟机,2.3.3版本;
测试机:HTC G14,4.0.3版本;
均测试无误。
代码连接:http://pan.baidu.com/share/link?shareid=122483160 uk=3909095065