Practical WebView skills for Android Development

Source: Internet
Author: User
Tags set cookie webhost

Practical WebView skills for Android Development

 

Some time ago, when I was working on a project, I used the WebView component in the project and encountered some problems. So I found some materials and learned how to solve them, now we will organize the learning content into a blog record here, so that you can quickly view and solve the problem when you encounter it again. We know that WebView in Android is a large component. In fact, WebView is a framework integrated with the famous browser engine webkit, which is mainly used to load and render webpages in Android applications. Well, before taking this study note, I also learned the Official Google documentation, introduced the basic usage of WebView, and translated it. The address is: Success.

 

Obtain the Title information of a webpage

When we open some applications, such as toutiao news client, some pages are loaded using WebView. However, there are often title bars at the top of the interface, in addition, the content of the title bar is not written to the program, but dynamically obtained from the webpage. How can we get it? As we all know, in Html, a complete web page will inevitably contain

Tags, tags are the title content, so we only need to get the content of the title tag in Html. To obtain the Title content, you must set the setWebChromeClient (WebChromeClient client) method of WebView to pass a WebChromeClient object and override the shouldOverrideUrlLoading (WebView view, String url) method under it, in this method, the title is called back TAG content. For example:

 

... MWebView = (WebView) findViewById (R. id. webview); // enables JavaScript to support mWebView. getSettings (). setJavaScriptEnabled (true); // load the webpage mWebView. loadUrl (http://www.baidu.com); // Force web pages to be opened in webview to prevent web pages from being opened in the default browser of the system. setWebViewClient (new WebViewClient () {@ Overridepublic boolean shouldOverrideUrlLoading (WebView view, String url) {view. loadUrl (url); return super. shouldOverrideUrlLoading (view, url) ;}}); mWebView. setWebChromeClient (new WebChromeClient () {@ Overridepublic void onReceivedTitle (WebView view, String title) {// onReceivedTitle can call back titletv_title.setText (title); super. onReceivedTitle (view, title );}});...

 

As shown in, the web page is opened in webview, and the title is now on the TextView title.
 

Download files with WebView

Similarly, when using a browser, we often need to download files. The browser is a very powerful application that can help us download online files, so if our applications integrate the WebView component, and the rendered webpage also has files for download, how should we download them? Similarly, since the browser is so powerful, our WebView components are not bad. Next, let's take a look at how WebView downloads files.

 

Public class DownloadActivity extends Activity {private WebView mWebView; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_NO_TITLE); setContentView (R. layout. activity_download); mWebView = (WebView) findViewById (R. id. webview); // enables JavaScript to support mWebView. getSettings (). setJavaScriptEnabled (true); mWebView. loadUrl (http: // img. Mukewang.com/down/54eec5f10001b17600000000.zip); mWebView. setWebViewClient (new WebViewClient () {@ Overridepublic boolean shouldOverrideUrlLoading (WebView view, String url) {view. loadUrl (url); return super. shouldOverrideUrlLoading (view, url) ;}}); // listens to download mWebView. setDownloadListener (new DownloadListener () {@ Overridepublic void onDownloadStart (String url, String userAgent, String contentDisposition, Stri Ng mimetype, long contentLength) {System. out. println (url: + url); if (url.endsWith(.zip) {// if the url contains a. ZIP file, the download thread System is enabled. out. println (download start ...); new DownloadThread (url ). start () ;}}) ;}/ *** download execution Thread */class DownloadThread extends Thread {private String mUrl; public DownloadThread (String url) {this. mUrl = url ;}@ Overridepublic void run () {try {URL httpUrl = new URL (mUrl); HttpURLConnection c Onn = (HttpURLConnection) httpUrl. openConnection (); conn. setDoInput (true); conn. setDoOutput (true); conn. setConnectTimeout (5000); conn. setReadTimeout (5000); InputStream in = conn. getInputStream (); FileOutputStream out = null; // obtain the download path File downloadFile; File sdFile; if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {downloadFile = Environment. getExternalStorageDirectory (); sdFile = New File (downloadFile, download.zip); out = new FileOutputStream (sdFile);} byte [] B = new byte [8*1024]; int len; while (len = in. read (B ))! =-1) {if (out! = Null) {out. write (B, 0, len) ;}} if (out! = Null) {out. close () ;}if (in! = Null) {in. close ();} System. out. println (download success ...);} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}}

 

In fact, WebView provides us with an interface for downloading and callback. This interface is android. webkit. downloadListener: first, call the setDownloadListener (DownloadListener listener) method of WebView, input the DownloadListener object in the method parameters, override the onDownloadStart method, and enable the download thread in this method, let the thread help us download files from the server.

 

Handling WebView error codes

What does WebView error code processing mean? When we use Android devices, the network may be poor or there is no network. In this case, the devices cannot access the server and cannot load Html pages. Generally, when an Html file is loaded without a network connection, the default error page of Android is displayed, for example:

Okay, this is the default page for us in the Android system. Is it worth a try? Similarly, if we present this page to users, they will be scolded. How can we deal with this situation? The method is also very simple. There are two main methods for implementation. One is to load a local Html page to inform the network of exceptions, and the other is to customize an error prompt interface through layout, load to the main interface. Well, the above two implementation methods are not the focus. We will not discuss how to create a nice Html Error page or a nice XML layout.

An error occurred while listening to WebView loading was handled in the onReceivedError () method under the WebViewClient object passed by setWebViewClient (). The following is a simple method:

 

MWebView. setWebViewClient (new WebViewClient (){... @ Overridepublic void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {// network exception, WebView loads the custom page super. onReceivedError (view, errorCode, description, failingUrl); view. loadUrl (file: // android_asset/error.html );}});
Okay, the code above is simple: Reload the html static page of the local assets directory.

 

 

 

What is synchronous cookiecookie in WebView? Here we need some knowledge on the Java Server. In short, Cookie is a cache mechanism on the server. For example, we entered the login username and password for the first time during login, the password is saved, so the next time we open this page again, the cookie will be automatically read to complete automatic login. If this page containing cookies is loaded using WebView, how can we achieve the same function? We only need to set WebView and Cookie synchronization.

 

 

Public class CookieTestActivity extends Activity {private WebView mWebView; private Handler mHandler = new Handler () {public void handleMessage (Message msg) {// synchronize CookieCookieSyncManager. createInstance (CookieTestActivity. this); CookieManager cookieManager = CookieManager. getInstance (); cookieManager. setAcceptCookie (true); cookieManager. setCookie (http: // 192.168.1.105: 8080/webs, msg. obj. toString (); CookieSyncManager. getInstance (). sync (); mWebView. loadUrl (http: // 192.168.1.105: 8080/webs/index. jsp) ;}};@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_NO_TITLE); setContentView (R. layout. activity_download); mWebView = (WebView) findViewById (R. id. webview); // enables JavaScript to support mWebView. getSettings (). setJavaScriptEnabled (true); String url = http: // 192.168.1.105: 8080/webs/login. jsp; new HttpCookie (mHandler, url ). start ();}/*** Access Server, read Cookie information */class HttpCookie extends Thread {private Handler handler; private String url; public HttpCookie (Handler handler, String url) {this. handler = handler; this. url = url ;}@ Overridepublic void run () {// use httpClient to send a POST request to the server: HttpClient client = new DefaultHttpClient (); HttpPost post = new HttpPost (url); List
 
  
List = new ArrayList
  
   
(); List. add (new BasicNameValuePair (name, zhangsan); list. add (new BasicNameValuePair (age, 22); try {post. setEntity (new UrlEncodedFormEntity (list); HttpResponse response = client.exe cute (post); if (response. getStatusLine (). getStatusCode () = 200) {// the server is successfully accessed. The server reads the Cookie information AbstractHttpClient absClient = (AbstractHttpClient) client; List
   
    
Cookies = absClient. getCookieStore (). getCookies (); for (Cookie cookie: cookies) {// send the Cookie to the UI thread Log. d (TAG, name = + cookie. getName () +, age = + cookie. getValue (); Message message = Message. obtain (); message. obj = cookie; handler. sendMessage (message); return ;}} catch (UnsupportedEncodingException e) {e. printStackTrace ();} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}}
   
  
 

Okay. Through the sample code above, we will soon know how to set Cookie synchronization. The main code is in Handler.

 

Obfuscation between WebView and JS calls

The keystore file. After installing the apk on the device and calling JS again, you will find that the calling method is invalid. This is an annoying time. To solve this problem, we need to do some protection for the code called by JS, And the protection measures are also very simple, you only need to ignore the Java-Layer Code called by JS In the obfuscation file.

This is Activity:

 

public class MainActivity extends Activity {private WebView mWebView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mWebView = (WebView) findViewById(R.id.webview);mWebView.loadUrl(file:///android_asset/index.html);mWebView.setWebViewClient(new WebViewClient() {@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {view.loadUrl(file:///android_asset/index.html);return true;}});mWebView.getSettings().setJavaScriptEnabled(true);mWebView.addJavascriptInterface(new WebHost(this), js);}}
Then we need to write a JS class called:

 

 

public class WebHost {private Context mContext;public WebHost(Context context) {this.mContext = context;}public void callJS() {Toast.makeText(mContext, call from js, Toast.LENGTH_SHORT).show();}}
The JS Code is as follows:

 

 

 Java and JS callback 

CallJava:

<Script type = text/javascript> function call () {js. callJS () ;}</script> at this time, the code to be written is normal in the test phase. After obfuscation and packaging, it is possible that the JS call fails. solution: in the obfuscation configuration file proguard. methods In WebHost are ignored in cfg.

 

 

-keep public class com.example.webview_02.WebHost{public 
 
  }
 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.