1 Web page Calls background Java code, background processing
A click event on a webpage
<a href= "javascript:;" onclick= "window. Jsnativemethod.showpropdetailpage (${item.id}) "class=" A-link ">
</a>
<a class= "Txt-link txtof" href= "javascript:;" onclick= "window. Jsnativemethod.showpropdetailpage (${item.id}) ">
${item.goodsname}
</a>
Two backend code, define Javascriptinterface
Private Class jsnativemethod{
@android. Webkit.javascriptinterface
public void showpropdetailpage (int propid) {
Message msg = Message.obtain ();
Msg.what = msg_showpropdetial;
MSG.ARG1 = propid;
Muihandler.sendmessage (msg);
}
}
Three mwebview.setwebviewclient (New Exwebviewclient ());
Mwebview.getsettings (). Setjavascriptenabled (True);
Mwebview.addjavascriptinterface (New Jsnativemethod (), "Jsnativemethod");
Mwebview.loadurl ("http://app.ujux.com/index.jsp");
2 Monitoring Events
Private class Exwebviewclient extends webviewclient{//main monitoring URL jump, intercept, request
@Override
public boolean shouldoverrideurlloading (WebView view, String URL) {
1 Instantiation webview 2 Settings Setting Configuration 3 Specify WebClient method, listen for click links and URL jump
return false to jump inside the current WebView, and return true to the current program to decide what to do with
Default return: Return super.shouldoverrideurlloading (view, URL); That is, jump to the phone browser.
Open the current URL in your phone browser
Intent Ints=new Intent (Intent.action_view);
Ints.setdata (uri.parse (URL))
StartActivity (INTs);
return true;
}
Mwebview.setwebchromeclient (New Webchromeclient () {///main monitor JS, alert,confirm,prompt; dialog box for JavaScript, Web site icon, Site title, loading progress, etc.
@Override
Public boolean onjsalert (WebView view, string URL, string message, jsresult result) {
log.e (TAG, "Onjsalert" + message);
Toast.maketext (Getapplicationcontext (), message, Toast.length_short). Show ();
Result.confirm ();
return true;
}
@Override
Public boolean onjsconfirm (WebView view, string URL, string message, jsresult result) {
LOG.E (TAG, "onjsconfirm" + message);
Return super.onjsconfirm (view, URL, message, result);
}
@Override
Public boolean onjsprompt (WebView view, string URL, String message, string defaultvalue, J Spromptresult result) {
log.e (TAG, "onjsprompt" + URL);
Return super.onjsprompt (view, URL, message, defaultvalue, result);
}
});
Mwebview.loadurl (URL);
}
and shouldoverrideurlloading () difference, click the connection will be executed, return to the previous page will only execute onpagestarted ()
That is, onpagestarted () executes at any time, the former executes first/
@Override
public void onpagestarted{}
@Override
public void onpagefinished (WebView view, String URL) {
if (Url.contains ("Prodlist")) {//contains this string, it is considered that WebView has jumped to level two page
Mbackbtn.setvisibility (view.visible);
}else{
Mbackbtn.setvisibility (View.gone);
}
}
}
3 Webviewclient Common Event description
An event before the link is opened
public boolean shouldoverrideurlloading (WebView view, String URL) {view.loadurl (URL); return true;}
This function we can do a lot of things, such as we read to some special URL, so we can not open the address, cancel the operation, for the pre-defined other operations, which is very necessary for a program.
Two onloadresource: response when loading resources
Three loading page completed events
public void onpagefinished (WebView view, String URL) {}
Similarly, we know that a page loading is complete, so we can close the loading bar, switch the program action.
Four-load page start events
public void onpagestarted (WebView view, String URL, Bitmap favicon) {}
This event is the start of loading the page call, usually we can set a loading in this page, tell the user program is waiting for the network response.
Five
Onreceiveerror: Response on Load Error
Onreceivedhttpauthrequest: An event that receives an HTTP request
Attention:
1 if you write in onpagestarted, it is best not to appear view.loadurl (URL), because if there is this, the page will continue to beat here, at least I have commented out and found no error ...
There is a lot of logic in the inside, then must think good how to put how to write, not shouldoverrideurlloading how to write onpagestarted inside must write ...
2 JS of several writing will cause shouldoverrideurlloading invalid Ah, posted out for everyone to see OH, attention can not be made like this ....
Following this URL open action, the custom WebView cannot intercept:
A. After settime in JS, the custom webview cannot intercept
B. In Ajax, as callback processing, assign values to Location.href
C. URL migration in form submission
http://tanghaibo001.blog.163.com/blog/static/9068612020121023113646644/
3 Set Wevview to display the page:
Internet use: Webview.loadurl ("http://www.google.com");
For local files: Webview.loadurl ("file:///android_asset/XX.html"); Local files are stored in the: Assets file
http://www.oschina.net/question/157182_46137
4 Java objects and methods to be bound in the Addjavascriptinterface method are to be run in another thread and cannot be run in a thread that constructs him. Otherwise it is easy to lead to Onpagestart method and Addjavascriptinterface in Webviewclient
The method in the conflict, the execution order of two people often interchange, change to handlder implementation, solve the problem, the correct order is onpagestart in Addjavascriptinterface handlder event processing before execution).
Java background calls the function in JS//
Four ((weblayout) _vcurcenterbodyview). M_vcurwebview.loadurl ("Javascript:hot ();");
Summarize:
Java calls JS inside the function, the speed is not satisfactory, about one hundred or two hundred milliseconds at a time, if you want to do a very interactive thing, this speed can be crazy. And the reverse is not the same, JS to tune the Java method, fast, the base
Ben 40-50 milliseconds at a time. So try to use JS to call the Java method, rather than Java to invoke the JS function.
In the page with JS callback to the Java method in Android cannot pass an integer, the Java method parameter type is changed to string
Five web fallback using the GoBack () method
If you do not do any processing, browse the Web page, click the System "back" button, the entire browser will call finish () and end itself, if you want to browse the page fallback rather than launch the browser, you need to process and consume the back in the current activity
Thing
public boolean onKeyDown (int keycode, keyevent event) {
if ((keycode = = keyevent.keycode_back) && mwebview.cangoback ()) {
Mwebview.goback ();
return true;
}
Return Super.onkeydown (KeyCode, event);
}
Six WebView cache, database API
1 when we load HTML, the database and cache two folders are generated under our data/app package:
The URL record we requested is saved in webviewcache.db, and the content of the URL is saved in the Webviewcache folder.
There are two kinds of caches in WebView: Web data cache (storing open pages and resources), H5 cache (i.e. AppCache);
http://blog.csdn.net/top_code/article/details/17024745
2 Web Cache
1. Cache composition
/data/data/package_name/cache/webviewcache
/data/data/package_name/database/webview.db
/data/data/package_name/database/webviewcache.db
2 To set the cache configuration:
private void Initwebview () {
Mwebview.getsettings (). Setjavascriptenabled (True);
Mwebview.getsettings (). setrenderpriority (Renderpriority.high);
Mwebview.getsettings (). Setcachemode (Websettings.load_default);//Set Cache mode
//Turn on DOM storage API feature
Mwebview. GetSettings (). Setdomstorageenabled (True);
//Open Database storage API function
Mwebview.getsettings (). Setdatabaseenabled (True);
String Cachedirpath = Getfilesdir (). GetAbsolutePath () +app_cacahe_dirname;
//String Cachedirpath = Getcachedir (). GetAbsolutePath () +constant.app_db_dirname;
Log.i (TAG, "cachedirpath=" +cachedirpath);
//Set Database Cache path
Mwebview.getsettings (). SetDatabasePath (Cachedirpath);
//Set Application Caches cache directory
Mwebview.getsettings (). Setappcachepath (Cachedirpath);
//Turn on application Caches function
Mwebview.getsettings (). Setappcacheenabled (True);
}
/**
* Clear WebView Cache
*/
public void Clearwebviewcache () {
Clean up the WebView cache database
try {
DeleteDatabase ("webview.db");
DeleteDatabase ("webviewcache.db");
} catch (Exception e) {
E.printstacktrace ();
}
WebView Cache files
File Appcachedir = new file (Getfilesdir (). GetAbsolutePath () +app_cacahe_dirname);
LOG.E (TAG, "Appcachedir path=" +appcachedir.getabsolutepath ());
File Webviewcachedir = new file (Getcachedir (). GetAbsolutePath () + "/webviewcache");
LOG.E (TAG, "Webviewcachedir path=" +webviewcachedir.getabsolutepath ());
Delete WebView Cache Directory
if (webviewcachedir.exists ()) {
DeleteFile (Webviewcachedir);
}
Delete WebView Cache Cache Directory
if (appcachedir.exists ()) {
DeleteFile (Appcachedir);
}
}
Seven WebView optimization
1 can directly set up the network proxy, directly download the entire Web page data to the local, loading
2 Pre-load pictures
3 Enabling caching and databases
4 smaller pages to load the volume of resources, JS,CSS, image compression
Eight WebView Web page execution order
Webview loading page order is like this: first load HTML, and then parse from the inside CSS, JS files and pages on the page to write dead image resources to load, if the WebKit cache inside, do not load. After you have loaded these resources,
Make CSS rendering and JS execution.
Nine Downloadlistener Interface!!
There is a method in the interface, Ondownloadstart () to download the listening interface, if the customer code implementation of the interface, the download start, failure, suspend, complete, and so on, the Downloadmanagercore object will be called in the customer code implemented in the
Downloadlistener method.
Nine experiences and questions
1 Android WebView is based on the WebKit kernel, but his running effect and Firefox on the same, so write the time is the first with the Firefox test, Test OK and then put in the program to see the effect, basically no problem
。
2 WebView has the event Ontouchstart, Ontouchmove, Ontouchend designed for the touchscreen, and the response to these events is real-time, which solves the problem of drag.
3 Webview inside of the page, if there is input, need to enter, but point up but did not respond, input method does not come out. This is because WebView does not get the focus. Need to set Requestfocus () in Java for WebView
On the line.
4 Android on the webview and iphone webview differences. So far, I've found a few differences:
1. On Android, WebView does not support multi-touch, no Ongesture series events, and there are on iphone.
2. The WebView on Android does not support transparency, which can be on the iphone.
WebView Usage Summary and Precautions