Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Perform native operation by javascript in Android

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

//HTML Content
/*
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web View Script</title>
</head>
<body>
<button id="success">Simulate Success</button>
<button id="failed">Simulate Failed</button>
<button id="sample">Simulate Sample Event</button>
<script>
    var success = document.getElementById('success');
    var failed = document.getElementById('failed');
    var sample = document.getElementById('sample');
    success.addEventListener('click', function () {
      var message = {
        "Status": "SUCCESS",
        "transactionId": "#PAY123133"
      };
      paymentResponse.postMessage(JSON.stringify(message));
    });
    failed.addEventListener('click', function () {
      var message = {
        "Status": "FAILED",
        "transactionId": "#PAY123133"
      };
      paymentResponse.postMessage(JSON.stringify(message));
    });
    sample.addEventListener('click', function () {
      var message = {
        "Status": "FAILED",
        "transactionId": "#PAY123133"
      };
      sampleMessage.postMessage(JSON.stringify(message));
    });
  </script>
</body>
</html>
*/
public class WebViewActivity extends AppCompatActivity {
    public static final String INTENT_EXTRA_URL = "INTENT_EXTRA_URL";
    private static final String TAG = "WebViewActivity";
    private final Handler myHandler = new Handler();


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        WebView paymentWebView = findViewById(R.id.paymentWebView);

        JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(this);

        paymentWebView.getSettings().setLightTouchEnabled(true);
        paymentWebView.getSettings().setJavaScriptEnabled(true);
        paymentWebView.addJavascriptInterface(myJavaScriptInterface, "paymentResponse");
        paymentWebView.addJavascriptInterface(myJavaScriptInterface, "sampleMessage");


        paymentWebView.setWebViewClient(new WebViewClient() {

            //If you will not use this method url links are opeen in new brower not in webview
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            //Show loader on url load
            public void onLoadResource(final WebView view, String url) {
                // TODO: 01/04/21 Show Waiting Indicator
            }

            public void onPageFinished(WebView view, String url) {
                // TODO: 01/04/21 Hide Waiting Indicator
            }

        });


        // TODO: 01/04/21 Change URL Base on your requirement
        String url = "file:///android_asset/index.html";
        paymentWebView.loadUrl(url);

    }

    private void showAlert(String title, String message) {
        AlertDialog alertDialog = new AlertDialog.Builder(WebViewActivity.this).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                (dialog, which) -> dialog.dismiss());
        alertDialog.show();
    }

    public class JavaScriptInterface {
        Context mContext;

        JavaScriptInterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void postMessage(String webMessage) {
            myHandler.post(() -> {
                try {
                    Log.d(TAG, "postMessage: " + webMessage);
                    JSONObject obj = new JSONObject(webMessage);
                    String status = obj.getString("Status");

                    switch (status) {
                        case "FAILED":

                            showAlert("Payment Declined", "Please try again");

                            break;

                        case "SUCCESS":
                            showAlert("Payment Success", obj.getString("transactionId"));
                            break;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            });

        }
    }
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: replace html encodings node.js 
Javascript :: react clikc with ref 
Javascript :: exitBeforeEnter not working 
Javascript :: responsive varient in material ui 
Javascript :: top 50 mcq que in javascript 
Javascript :: convert json results 
Javascript :: js deconstruct rename 
Javascript :: delete head array js 
Javascript :: $(document).ready(function () { $(".inputs").click(function () { alert($(this).id); }); }); 
Javascript :: inherit mdn 
Javascript :: javascript synchronous and asynchronous list 
Javascript :: add link in react table to specific column 
Javascript :: how to render req.session.name to ejs 
Javascript :: Alternative Syntax For Backbone Simple Template 
Javascript :: styling font awesome icons next js 
Javascript :: How to Compare Strings Using Mathematical Operators 
Javascript :: element non empty jquer y check 
Javascript :: Backbone Model Vs Backbone Collection 
Javascript :: Both This Have The Same Value 
Javascript :: Example Of _.extend 
Javascript :: using condition how to disable radio button in angular 
Javascript :: react native tinder 
Javascript :: without the filter() method 
Javascript :: convert javascript to java 
Javascript :: firebase database TIMESTAMP 
Javascript :: regex from 5 to 30 1 number 1 lower case and 1 upper case letter 
Javascript :: left join in javascript 
Javascript :: how to square number in javascript 
Javascript :: style mapbox paint data driven 
Javascript :: configuring styled component to support ssr and hydration 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =