Xamarin Android two way communication between Javascript and C #

I am developing an application using Xamarin Android, which has a WebView displaying a web page. I want to implement two-way communication between Javascript from WebView to C #. I could call C # from Javascript using the link. However, I could not find a way to send data from C # to Javascript. Is there a way to send data back and forth in this approach. I thought writing a callback in Javascript would work, but how to run it from C # code.

Now my problem is how to call a WebView from a javascript interface class. I have a Javascript interface class, as indicated by https://developer.xamarin.com/recipes/android/controls/webview/call_csharp_from_javascript/ ScannerAndroid namespace {JSInterface public class: Java.Lang.Object {Context context; WebView webView;

public JSInterface (Context context, WebView webView1) { this.context = context; this.webView = webView1; } [Export] [JavascriptInterface] public void ShowToast() { Toast.MakeText (context, "Hello from C#", ToastLength.Short).Show (); this.webView.LoadUrl ("javascript:callback('Hello from Android Native');"); } } } 

The code throws an exception on the line LoadUrl. java.lang.Throwable: the WebView method is called in the thread "Thread-891". All WebView methods must be called in a single thread. (Expected Looper Looper (main, tid 1) {42ce58a0} caused by zero, FYI main Looper - Looper (main, tid 1) {42ce58a0})

Now I'm struggling on how to pass a WebView from this class of Java script interface

+5
source share
1 answer

Yes. It is possible. If you are targeting KitKat or higher, you can use:

 webView.EvaluateJavascript("enable();", null); 

Where in this case enable(); - JS function.

If you use lower API levels, you can use LoadUrl(); :

 webView.LoadUrl("javascript:enable();"); 

EDIT:

The error you get where it complains about LoadUrl is due to the fact that for some reason it occurs in a thread other than the UI.

Since you've already passed through Context to your JavascriptInterface class, you can simply wrap the contents of ShowToast in:

 context.RunOnUiThread(() => { // stuff here }); 

Just change the signature from Context to Activity , and it will help you redirect you to the UI thread.

+2
source

Source: https://habr.com/ru/post/1233385/


All Articles