In Android, webview uses custom JavaScript For callback.

Source: Internet
Author: User

 

Let's explain why we need to discuss this issue.

 

Nowadays, many mobile apps may embed a Web page directly. Benefits: one is convenient feature updates and easy maintenance. You only need to maintain the page of the server without updating the client. The other is universal functionality, not only available for Android, IOS can also be used, and Symbian can also be used directly.

 

So why are many mobile apps not web-based? There are many reasons. One is that the current Web display capability is relatively weak. If the aesthetic requirements of applications are relatively high, the web method cannot be used. The other is that the web method is relatively slow, user experience may be affected. One is the current traffic or relatively valuable, and the Web traffic is relatively large. The other is that some features cannot be implemented using the web method (for this purpose, currently, many open-source projects can implement some mobile phone hardware functions, such as taking photos and getting address books. If you are interested, you can search for phonegap. However, the feedback is slow and the experience is poor ).

 

For the above reasons, many projects now make some functions web-based, and some functions are written using other controls. This requires web pages to interact with other controls. How to interact is to use custom JavaScript.

 

The following is a virtual scenario.

 

Now there is a function to display the current user's friend list. The friend list page is web-based. Click a friend's avatar to go to the friend's details page. What about this page, for some reason, the web method is not implemented.

 

Assume that the friend list page is userlistactivity and contains a webview. The friend details page is userdetailactivity, which contains many controls and business logic.

 

We use ID to uniquely identify the user. On the friends list page, clicking a friend profile will call:

Onclick = "javascript: Android. User ('1 ')"

JS statements like this. Because this article mainly introduces Android, rather than web development content, it is not detailed in detail, so it is easy for people familiar with web development to understand.

 

What we need to do now is to display the user list page. After the user clicks the Avatar, it responds to the specific JS request and jumps to the friend details page.

 

The following describes the implementation methods.

 

By default, JavaScript cannot be used in webview. You can use the following code:

WebView myWebView = (WebView) findViewById(R.id.webview);WebSettings webSettings = myWebView.getSettings();webSettings.setJavaScriptEnabled(true);

 

Make JavaScript Functions available. This part of the code is stored in the oncreate () method in userlistactivity.

 

Then register the JS interface. First, let's look at a webview method.

 

Public void addjavascriptinterface (Object OBJ, string interfacename)

Since: API Level 1

Use this function to bind an object to JavaScript so that the methods can be accessed from JavaScript.

Important:

· Using addjavascriptinterface () allows JavaScript to control your application. this can be a very useful feature or a dangerous security issue. when the HTML in the webview is untrustworthy (for example, part or all of the HTML is provided
By some person or process), then an attacker cocould inject HTML that will execute your code and possibly any code of the attacker's choosing.
Do not use addjavascriptinterface () unless all of the HTML in this webview was written by you.

· The Java object that is bound runs in another thread and not in the thread that it was constructed in.

Parameters

OBJ

The class instance to bind to Javascript, null instances are ignored.

Interfacename

The name to used to expose the instance in JavaScript.

 

The following statement is added to the oncreate () method of the userlistactivity class:

Mwebview. addjavascriptinterface (this, "android ");

Add the following method to the userlistactivity class:

Public voidUser (string ID ){

// Get the ID and jump to the activity.

}

 

In this way, when the page calls the onclick = "javascript: Android. User ('1')" statement, you can map it to the user () method of the userlistactivity object.

Here, the user method has a parameter that corresponds to the user ('1') of the JS statement ').

 

All codes are attached below.

 

Android code:

 

Package COM. arui. framework. android. JS; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; import android. webKit. websettings; import android. webKit. webview; import COM. arui. framework. r; import COM. arui. framework. android. JS. userdetailactivity; public class userlistactivity extends activity {private webview mwebview; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. id. userlist); mwebview = (webview) findviewbyid (R. id. mywebview); websettings websetting = mwebview. getsettings (); // set the websetting available for Js. setjavascriptenabled (true); // Add the JS call interface mwebview. addjavascriptinterface (this, "android"); // load the specific web address mwebview. loadurl ("http://blog.csdn.net/arui319"); mwebview. setvisibility (view. visible); mwebview. requestfocus ();} public void user (string ID) {// jump to activity intent = new intent (this, userdetailactivity. class); intent. putextra ("ID", ID); startactivity (intent );}}

 

Resource file:

<?xml version="1.0" encoding="utf-8"?><LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <WebView       android:id="@+id/mywebview"       android:layout_width="fill_parent"       android:layout_height="fill_parent"        android:visibility="gone"/></LinearLayout>

 

Local code on the web page:

 

---------------------------------------------------------------------------

GL (arui319)

Http://blog.csdn.net/arui319

<This article can be reproduced, but please keep the above author information. Thank you.>

---------------------------------------------------------------------------

 

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.