Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView push notification?

I need to send a notification (not necessarily a push notification) through an android webview. I saw that the Notification API was not compatible with Android Webview on MDN. The other APIs I saw seemed to be based off of window.notification.

Does anyone know of any API or JS that sends a notification through an android webview?

I saw this post from 6 months ago with essentially no activity except a vague mention of firebase. Would that be helpful?

Thanks for your answers!

like image 996
CtrlAltF2 Avatar asked Dec 31 '18 22:12

CtrlAltF2


1 Answers

Read the documentation entry for Binding JavaScript code to Android code.

This allows you to use javascript to trigger the execution of android code.

First you have to register the Javascript Interface on android, so that you can trigger android code from javascript.

JAVA

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");

And define a method which does your action if the javascript is called. In this example show a toast.

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

↑ You need to change that part to show your push notification instead. ↑

Then you can trigger the android code from javascript like this:

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
</script>

I did not tried it myself. But I would try to create a javascript method which makes an ajax request to a server in certain intervals and checks if there are new notifications to send and if true then call the android code to show the message.

However, you will have to make sure to only show the notification once somehow... maybe set a cookie containing the notification ID and set it to true, so that the android code is not getting triggered again.

You would need to provide the notifications for example as a .json file in JSON format. You can upload that .json file to your webserver somewhere. Then pass the content to android and parse it accordingly.

like image 58
Black Avatar answered Sep 29 '22 13:09

Black