Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR 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();
                }

            });

        }
    }
}
Source by gist.github.com #
 
PREVIOUS NEXT
Tagged: #Perform #native #operation #javascript #Android
ADD COMMENT
Topic
Name
4+5 =