Introduction to android and H5 interaction methods, mobile terminal hybrid development

3.1 Demo project preparation


(1) Create an Android project to demonstrate the interactive effect

(2) Modify the main interface layout file

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:app=“http://schemas.android.com/apk/res-auto”

xmlns:tools=“http://schemas.android.com/tools”

android:id=”@+id/root”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:background=”#ffffff”

tools:context=”.MainActivity”>

<TextView

android:id=”@+id/tv”

android:layout_width=“0dp”

android:layout_height=“wrap_content”

android:layout_marginTop=“50dp”

android:gravity=“center”

android:text=”I am testing”

android:textColor=”#000000″

app:layout_constraintEnd_toEndOf=“parent”

app:layout_constraintStart_toStartOf=“parent”

app:layout_constraintTop_toTopOf=“parent” />

<Button

android:id=”@+id/btn”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:layout_marginTop=“30dp”

android:gravity=“center”

android:text=”Test”

app:layout_constraintEnd_toEndOf=“parent”

app:layout_constraintStart_toStartOf=“parent”

app:layout_constraintTop_toBottomOf=”@+id/tv” />

<WebView

android:id=”@+id/web_view”

android:layout_width=“0dp”

android:layout_height=“0dp”

android:layout_marginTop=“30dp”

app:layout_constraintEnd_toEndOf=“parent”

app:layout_constraintStart_toStartOf=“parent”

app:layout_constraintTop_toBottomOf=”@+id/btn”

app:layout_constraintBottom_toBottomOf=“parent”/>

</androidx.constraintlayout.widget.ConstraintLayout>

(3) test_java_call_js.html content

(4) test_js_call_java.html content

(5) MainActivity content

public class MainActivity extends AppCompatActivity {

//webView

private WebView webView;

//”JAVA calls JS parameterless method”

private Button btnJavaCallJSNoParamFunc;

//”JAVA calls JS parameterized method”

private Button btnJavaCallJSHaveParamFunc;

//”JAVA calls JS and gets the return result”

private Button btnJavaCallJSHaveReturnFunc;

//”Jump to html interface to test JS calling JAVA method”

private Button btnToJSCallJavaFuncWebView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTitle(“demo”);

setActivityMainToContentView();

}

/***

  • Override return key response method

*/

@Override

public void onBackPressed() {

//Find the elements in the original activity_main.xml

View v = findViewById(R.id.btn_to_js_call_java_func_webView);

//If not found, set ContentView to activity_main

if(v == null){

setActivityMainToContentView();

} else {

super.onBackPressed();

}

}

/***

  • A series of initializations required to set ContentView to activity_main

*/

private void setActivityMainToContentView() {

setContentView(R.layout.activity_main);

//Initial webView

initWebView();

btnJavaCallJSNoParamFunc = findViewById(R.id.btn_java_call_js_no_param_func);

btnJavaCallJSNoParamFunc.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

callJs(“javascript:javaCallJsNoParam()”);

//webView.loadUrl(“javascript:java

“Summary of Android study notes + latest mobile architecture video + real Android interview questions from major manufacturers + actual project source code handouts”

[docs.qq.com/doc/DSkNLaERkbnFoS0ZF] Full content open source sharing

CallJsNoParam()”);

}

});

btnJavaCallJSHaveParamFunc = findViewById(R.id.btn_java_call_js_have_param_func);

btnJavaCallJSHaveParamFunc.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

callJs(“javascript:javaCallJsHaveParam(’”+ +Math.random() +”’)”);

}

});

btnJavaCallJSHaveReturnFunc = findViewById(R.id.btn_java_call_js_have_param_return_func_);

btnJavaCallJSHaveReturnFunc.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

callJs(“javascript:javaCallJsHaveReturn()”);

}

});

btnToJSCallJavaFuncWebView = findViewById(R.id.btn_to_js_call_java_func_webView);

btnToJSCallJavaFuncWebView.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

//Load test_js_call_java.html

webView.loadUrl(“file:///android_asset/test_js_call_java.html”);

//Set ContentView to webView;

setContentView(webView);

}

});

}

private void initWebView() {

webView = new WebView(this);

WebSettings webSettings = webView.getSettings();

//Set support for javaScript script language

webSettings.setJavaScriptEnabled(true);

//Restrict opening web pages in WebView instead of the default browser

//Here I override the shouldOverrideUrlLoading method in WebViewClient to verify the Android interception url

//webView.setWebViewClient(new WebViewClient());

webView.setWebViewClient(new WebViewClient(){

@Override

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

Uri uri = request.getUrl();

Toast.makeText(MainActivity.this, “Intercepted URL:” +uri.toString(), Toast.LENGTH_SHORT).show();

//Return true to cancel the current loading, otherwise return false.

return true;

}

}

);

//Set to allow the interface to pop up alert and other prompt boxes

//webView.setWebChromeClient(new WebChromeClient());

webView.setWebChromeClient(new WebChromeClient(){

//Rewrite the onJsAlert method to make a simple response

@Override

public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

//Only respond to special information to avoid affecting other warning boxes

if(message.equals(“Test onJsAlert”)){

Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();

}

return super.onJsAlert(view, url, message, result);

}

//Rewrite the onJsConfirm method to make a simple response

@Override

public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {

Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();

return super.onJsConfirm(view, url, message, result);

}

//Rewrite the onJsPrompt method to make a simple response

@Override

public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {

Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();

return super.onJsPrompt(view, url, message, defaultValue, result);

}

});

//Set up to support js calling java

webView.addJavascriptInterface(new JsObject(),“injectedObject”);

//Load network resources

webView.loadUrl(“file:///android_asset/test_java_call_js.html”);

}

/***

  • injected object

*/

class JsObject {

//parameterless method that can be called by JS

@JavascriptInterface

public void jsCallJavaNoParam() {

Toast.makeText(MainActivity.this, “JS successfully called JAVA!”, Toast.LENGTH_SHORT).show();

}

//Parametered method that can be called by JS

@JavascriptInterface

public void jsCallJavaHaveParam(String param) {

Toast.makeText(MainActivity.this, “JS successfully called JAVA parameterized method! The parameters are: “+param, Toast.LENGTH_SHORT).show();

}

//Methods with return values ​​that can be called by JS

@JavascriptInterface

public String jsCallJavaHaveReturn() {

Double num = Math.random();

return “”+num;

}

}

/***

  • Call JS

*/

private void callJs(String javascript){

//Call JS

webView.evaluateJavascript(javascript, new ValueCallback() {

@Override

public void onReceiveValue(String response) {

//If there is a return value, make a simple response (if the JS function has no return value, the response is not null, but the string “null”)

if(!response.equals(“null”)) {

Toast.makeText(MainActivity.this, “The value of the random number returned by JS is” + response, Toast.LENGTH_SHORT).show();

}

}

});

//Set ContentView to webView;

setContentView(webView);

}

}

3.2.Java calls JS code


3.2.1 loadUrl() method

If there is such a method in the page loaded by webView

function javaCallJsNoParam(){

document.getElementById(“result”).innerHTML= ‘JAVA calls JS successfully! ‘;

}

Then you can call it like this in JAVA code

webView.loadUrl(“javascript:javaCallJsNoParam()”);

3.2.2 evaluateJavascript() method

WebView.evaluateJavascript() method introduction

Added in API level 19

public void evaluateJavascript(String script, ValueCallback resultCallback)

Asynchronously evaluates JavaScript in the context of the currently displayed page. If not NULL,ResultCallbackWill be called with any results returned by this execution. This method must be called on the UI thread and the callback made on the UI thread.

| Parameters | Description |

| — | — |

| script | String:JavaScript to execute. Can not be empty. |

| resultCallback | ValueCallback:.Callback called when script execution is complete. If no notification result is required, NULL is assumed. |

Example:

//javascript example

//(1)“javascript:javaCallJsNoParam()”

//(2)“javascript:javaCallJs(” + “’” + numebr + “’” + “)”

webView.evaluateJavascript(javascript, new ValueCallback() {

@Override

public void onReceiveValue(String response) {

//response is the response data

}

}

});

The calling method is encapsulated in the demo project. Click the corresponding button to generate a response event, call the method and pass in different javascript values.

Effect (animation):

3.3.JS calls Java code


3.3.1addJavascriptInterface() method

Introduction to WebView.addJavascriptInterface() method

public void addJavascriptInterface (Object object, String name)

Inject the provided Java object into this WebView. Injects the object into all frames of the web page, including all iframes, using the provided name. This allows accessing methods of Java objects from JavaScript. For APIBuild.VERSION_CODES.JELLY_bean_MR1and higher, only withJavascriptInterfaceAnnotated public methods can only be accessed from JavaScript. For APIBuild.VERSION_CODES.JELLY_beanor lower applications, have access to all public methods (including inherited methods), note that the injected object will appear in JavaScript until the next page is loaded (Re). JavaScript should be enabled before injecting objects. For example:

class JsObject {

@JavascriptInterface

public String toString() { return “injectedObject”; }

}

webview.getSettings().setJavaScriptEnabled(true);

webView.addJavascriptInterface(new JsObject(), “injectedObject”);

webView.loadData(“”, “text/html”, null);

webView.loadUrl(“javascript:alert(injectedObject.toString())”);

| Parameters | Description |

| — | — |

Related Posts

Android studio implements app login registration page

AR gesture recognition interaction makes applications more “handy”

Mac download and install adb environment

Why is it the most popular Linux? Ubuntu ranks sixth.

AR Engine motion tracking capability enables immersive AR experience with high accuracy

Flutter configuration

Android App event interaction event imitates Jingdong App to implement pull-down refresh function (source code attached for direct use)

Play with Android adb commands (adb downgrade)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*