Today's app,android and H5 hybrid development is common. When Android loads the H5 page through WebView and needs to be passed to it, it can be done with loaclstorage. The code is as follows:
WebView first set the following properties:
Webview.getsettings (). Setdomstorageenabled (true);
Webview.getsettings (). Setappcachemaxsize (1024*1024*8);
String Appcachepath = Getapplicationcontext (). Getcachedir (). GetAbsolutePath ();
Webview.getsettings (). Setappcachepath (Appcachepath);
Webview.getsettings (). Setallowfileaccess (true);
Webview.getsettings (). Setappcacheenabled (true);
Javascriptinterface jsinterface = new Javascriptinterface (this);
Webview.getsettings (). Setjavascriptenabled (true);
Webview.addjavascriptinterface (Jsinterface, "jsinterface");
Then, pass the parameter:
Webview.setwebviewclient (New Webviewclient () {
@Override public
void onpagefinished (webview view, String URL) {
String key = ' Hello ';
String val = "World";
if (Android.os.Build.VERSION.SDK_INT >= Android.os.Build.VERSION_CODES. KitKat) {
webview.evaluatejavascript ("Localstorage.setitem (' + key +" ', ' "+ val +"); ", null);
} else {
Webview.loadurl ("Javascript:localStorage.setItem (' + key +" ', ' "+ val +" '); ");}
}
);
The code for the Javascriptinterface section is as follows:
public class Javascriptinterface {
private activity activity;
Public Javascriptinterface (activity Activiy) {
this.activity = Activiy;
}
public string GetData (string someparameter) {
//also/can return JSON data as string and in client side do JSON. Parse
if (Someparameter = = "Transmitdata" && this.activity.data) {return
this.activity.data;
} else{return
null;}}
The code for the Js section is as follows:
<script>
function Ready () {
var data = window. Jsinterface.getdata ("Transmitdata");
Localstorage.put ("Transmitdata", data)
};
Document.addeventlistener ("domcontentloaded", ready);
</script>