1

I have a simple game developed in PHP. I have loaded the remote site in Android WebView. I want to find out that if user clicks on a FREE life button which is on my remote PHP site, I want to start a reward video on my Android app.

But how can I know whether the user clicked on the FREE life button in my WebView and start the video instantly in my android app?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Sam
  • 2,972
  • 6
  • 34
  • 62

1 Answers1

1

There is an Android mechanism that alows you to run Android function from javascript:

        <input class="button" type="button" value="FREE life" onclick="startRewardVideo('some parameters can be passed to Android from here')">
            <script type="text/javascript">
                function startRewardVideo(paramFromJS) {
                    Android.startRewardVideoAndroidFunction(paramFromJS);
                }
            </script>

now you need class that knows what to do with your javascript:

public class MyJavaScriptInterface {

   @JavascriptInterface // this annotation is importatn
   public void startRewardVideoAndroidFunction(String paramFromJS) {

      //here you need to start showing reward movie 
      //because this function will be called after webView button click.
   }
}

last step is to connect webView with your javascript interface:

webView.addJavascriptInterface(new MyJavaScriptInterface(), "Android");

and of course don't forget to enable javascript for your webView:

webView.getSettings().setJavaScriptEnabled(true);

Hope it helps :) Ask if you have any questions on this.

Here you have full tutorial

Karol Żygłowicz
  • 2,442
  • 2
  • 26
  • 35
  • Thanks for your answer! What I doubt is, as I am importing remote PHP website in my webview, will the function executed on my Android app? Also the same will fail if someone uses the PHP site directly from browser. But I am not worrying about it. – Sam Jan 24 '18 at 13:43
  • JS executed on remote site is crucial so you need to add this. This solution won't work if you cant execute this JS on button click. – Karol Żygłowicz Jan 25 '18 at 09:08