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 :: javascript channel flutter inappWebview 
Javascript :: Return Early Pattern for Functions 
Javascript :: javascript interview quetions 
Javascript :: reactrouter 
Javascript :: Wikibreak enforcer 
Javascript :: concat not working javascript 
Javascript :: how to print message in nodjs 
Javascript :: vanilla javascript event when reach bottom of element no jquery 
Javascript :: utility javascript function list 
Javascript :: forEach ActiveLink 
Javascript :: accessing state in nuxt vuex 
Javascript :: JavaScript code to convert amount in words 
Javascript :: es6 syntax 
Javascript :: creating theme.json fullsiteediting 
Javascript :: javascript get hours and minutes from date 
Javascript :: How to Compare Strings Using localeCompare 
Javascript :: odoo owl usestate 
Javascript :: finding the smallest number other than 0 in an array javascript 
Javascript :: converting jsObject to JSON 
Javascript :: js template literal avoid white spaces 
Javascript :: generate qr codes js 
Javascript :: get file name with extension netsuite suitescript 
Javascript :: hsv to rgb js 
Javascript :: add item or nothing array js 
Javascript :: javascript convert color string to rgb 
Javascript :: modalInstance.result.then when execute 
Javascript :: if spreeding the properties on an input how to nnot include the invalid props that the input is not receiving 
Javascript :: kth smallest element in an array js 
Javascript :: javascript to typescript converter 
Javascript :: express check request type 
ADD CONTENT
Topic
Content
Source link
Name
9+9 =