Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
104
rated 0 times [  110] [ 6]  / answers: 1 / hits: 21475  / 13 Years ago, thu, march 10, 2011, 12:00:00

I want to let my android app call a function written in javascript and expect a return value from that.



I understand that WebView.loadUrl works asynchronously, so what I am doing now is to let javascript notify my android app when it is done and pass in the return value by calling a java function using javascriptinterface.



I wonder if there are better ways of doing this and whether anyone has noticed any message loss between javascript and android.


More From » android

 Answers
6

I just got your problem.



Have a JS function like this.



function androidResponse() {
window.cpjs.sendToAndroid(I am being sent to Android.);
}


Set up Android (Java).



Have a final class like this



final class IJavascriptHandler {
IJavascriptHandler() {
}

// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public void sendToAndroid(String text) {
// this is called from JS with passed value
Toast t = Toast.makeText(getApplicationContext(), text, 2000);
t.show();
}
}


Then on your WebView load have.



webView.addJavascriptInterface(new IJavascriptHandler(), cpjs);


Call JS function



webView.loadUrl(javascript:androidResponse();void(0));


UPDATED






Also I had a very bad time experiencing problems while passing hundreds of lines of string to JS from Java and I have subsequent post on StackOverflow with no good answers but finally resolved it knowing problme was of special characters inside string so take of special characters when you use string passing to and fro.



Passing Data From Javascript To Android WebView



HTML String Inside Nested String



HTML TextArea Characters Limit Inside Android WebView


[#93337] Wednesday, March 9, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calicinthias

Total Points: 447
Total Questions: 101
Total Answers: 118

Location: Botswana
Member since Sat, Dec 31, 2022
1 Year ago
calicinthias questions
Sun, Jan 2, 22, 00:00, 2 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Mon, Aug 10, 20, 00:00, 4 Years ago
;