How to use custom javascript For callback based on Webview in Android

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:

Copy codeThe Code is as follows: 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:

Copy codeThe Code is as follows: 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 js availability

WebSetting. setJavaScriptEnabled (true );

// Add a js call interface

MWebView. addJavascriptInterface (this, "android ");

// Load the specific web address

MWebView. loadUrl ("http://jb51.net ");

MWebView. setVisibility (View. VISIBLE );

MWebView. requestFocus ();

}

Public void user (String id ){

// Jump to activity

Intent intent = new Intent (this, UserDetailActivity. class );

Intent. putExtra ("id", id );

StartActivity (intent );

}

}

Resource file:

Copy codeThe Code is as follows: <? 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:

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.