I have created a cordova application. I am running an background service to perform some native task in the application. I need to trigger a java-script event once the background service complete its task. Is it possible to trigger js events from android?. Not able to find any solid answers for this. I need events because the application wound wait for the task in background service to complete. I want to event to notify the application that the task is complete. Is there any better way to implement this logic?.
Cordova itself doesn't expose its webview properties publicly for use by other Java classes, but you can do this with a minimal Cordova plugin which would allow your background service to access the Cordova webview in order to execute javascript in it from the Java layer. Then it's just a question of injecting the JS to trigger an event.
First you'd create a Cordova plugin to expose the necessary elements of Cordova to your background service:
public class MyPlugin extends CordovaPlugin{
private static final String TAG = "MyPlugin";
static MyPlugin instance = null;
static CordovaWebView cordovaWebView;
static CordovaInterface cordovaInterface;
#Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
instance = this;
cordovaWebView = webView;
cordovaInterface = cordova;
}
#Override
public void onDestroy() {
instance = null;
}
private static void executeGlobalJavascript(final String jsString) {
if (instance == null) {return;}
instance.cordovaInterface.getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
instance.cordovaWebView.loadUrl("javascript:" + jsString);
} catch (Exception e) {
Log.e(TAG, "Error executing javascript: "+ e.toString());
}
}
});
}
public static void triggerJavascriptEvent(final String eventName){
executeGlobalJavascript(String.format("document.dispatchEvent(new Event('%s'));", eventName));
}
}
Then your background service can call the public method exposed by that plugin class:
public class MyService {
public static void myMethod(){
MyPlugin.triggerJavascriptEvent("myserviceevent");
}
}
And finally, in your Cordova app's JS layer, you'd listen for your custom event:
document.addEventListener('myserviceevent', function(){
console.log("myserviceevent received");
}, false);
I've created an example Cordova project which contains the minimal custom plugins required to achieve this which you can download here: http://ge.tt/8UeL6lu2
Once downloaded, unzip then:
cd cordova-test
cordova platform add android
cordova run android
I am currently working on a GWT project and it now needs to used by an external JavaScript file. I am creating a test prototype right now to ensure both sides are working properly.
When I run and compile, I see the console logs in the browser from the events being called. However, the GWT java methods are not being called.
After trying many scenarios, I also noticed that if I remove the $entry wrapper from the exportStaticMethods(), the opposite occurs. I see the System.outs being called in my java code, however the console logs from the JavaScript in the browser are not being called.
I am trying to figure what is causing the behavior and if there is a small missing piece I overlooked.
I have already reviewed the GWT JSNI documentation for calling a Java method from js and tried to find a solution from other related questions on StackOverflow.
GWT and Java side
I have gone into the onModuleLoad() method of my EntryPoint class and added a static method called exportStaticMethods(). I also created the PokePingClass.java file listed below.
EntryPointClass.java
public class EntryPointClass implements EntryPoint {
#Override public void onModuleLoad() {
exportStaticMethods();
// load application here.
}
public static native void exportStaticMethods() /*-{
$wnd.pingApp = $entry((function) {
#com.application.PokePingClass::pingApp()();
});
$wnd.pokeApp = $entry((function) {
#com.application.PokePingClass::pokeApp()();
});
}-*/
}
PokePingClass.java
public class PokePingClass {
public static void pokeApp() {
System.out.println("pokeApp() called");
}
public static void pingApp() {
System.out.println("pingApp() called");
}
}
HTML and js
In the .html file of the project, I added a hidden div element of id 'pokePing', as well as the pokeping.js file.
<html>
<head>
.
. <!-- other stuff -->
.
<script type='text/javascript' src='pokeping.js</script>
</head>
<body>
.
. <!-- other stuff -->
.
<div id="pokePing" style="visibility: hidden;"></div>
</body>
</html>
pokeping.js
$(document).ready(function) {
var $pp = $('#pokePing');
var pokeApp = function() {
console.log("app handling poke event");
window.parent.pokeApp();
}
var pingApp = function() {
console.log("app handling ping event");
window.parent.pingApp();
}
$pp.trigger('pokeApp');
$pp.trigger('pingApp');
}
public static native void exportStaticMethods() /*-{
$wnd.pingApp = $entry(function) {
#com.application.PokePingClass.pingApp()();
}
$wnd.pokeApp = $entry(function) {
#com.application.PokePingClass.pokeApp()();
}
}-*/
This isn't valid JS, and doesn't make sense as JSNI. Try this instead:
$wnd.pingApp = $entry(function() {
#com.application.PokePingClass::pingApp()();
});
$wnd.pokeApp = $entry(function() {
#com.application.PokePingClass::pokeApp()();
});
Edit because I still had it wrong, forgot the :: operator for members.
I found a similar post but the key was to actually return the method calls in the JSNI functions. After that, all works well.
public static native void exportStaticMethods() /*-{
$wnd.pingApp = $entry((function) {
return #com.application.PokePingClass::pingApp()();
});
$wnd.pokeApp = $entry((function) {
return #com.application.PokePingClass::pokeApp()();
});
}-*/
In worklight, I am using WL.NativePage.show for android native call. As I am doing so much process in activity(native), It throws me error "The application may be doing too much work on its main thread".
As resolution I used threading for calculation(so much process) and It is working OK. But In this case, Native page showed up.
But I just want some calculation on input (From JS) in native and output(At JS) without rendering activity.
...
public class EmbeddedCalculator extends Activity {
public static Boolean isSuccessful = false;
private Calculation calculation = new Calculation();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Runnable runnable = new Runnable() {
#Override
public void run() {
// .. calculation - Higher process ..
}
};
Thread t= new Thread(runnable);
t.start();
}
}
Then why use WL.NativePage at all?
Since you did not mention the actual version of Worklight that you are using, I will just list possible alternatives:
Create a Cordova plug-in that will invoke native code and return the result: https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-1/foundation/adding-native-functionality/ - tutorials and samples are available
Use the SendAction APIs to invoke native code (MobileFirst Platform Foundatin 6.3 and above): http://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.dev.doc/devref/c_action_sender.html
I don't understand how it is possible to do this, since there are no WebActivities with PhoneGap, only your Activity classes and your index.html page. I have a MainActivity that looks like this...
public class MastersProjectActivity extends DroidGap
{
#JavascriptInterface
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
//super.loadUrl(Config.getStartUrl());
super.loadUrl("file:///android_asset/www/index.html");
Context myCntxt = getApplicationContext();
TelephonyManager tMgr = (TelephonyManager)myCntxt.getSystemService(Context.TELEPHONY_SERVICE);
String curPhoneNumber = tMgr.getLine1Number();
Log.d("PhoneNumber", curPhoneNumber);
}
}
...and I want to be able to use curPhoneNumber in the index.html page, which in PhoneGap contains the entirety of the UI. Any ideas on how I can do this? I'm completely new to Android development in general, and certainly with PhoneGap. To be honest I still don't really understand how the index.html page is rendered as an Android UI. Do I need to wrap the index.html page in a WebActivity or something? I'm not sure if this would create any issues in the way PhoneGap creates the .apk.
EDIT - I tried to implement but it didn't work for me, all I got was an alert literally saying "interface.getPhoneNumber()". I may have implemented the 'MyInterface' class incorrectly? Here's the class I made....
public class MyInterface extends DroidGap {
private MastersProjectActivity _activity;
private CordovaWebView _view;
public MyInterface(MastersProjectActivity activity, CordovaWebView view) {
this._activity = activity;
this._view = view;
}
#JavascriptInterface
public String getPhoneNumber() {
Context myCtxt = getApplicationContext();
return ((TelephonyManager)myCtxt.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
}
}
...and I exposed the javascript interface in my main activity like so...
#Override
public void onCreate(Bundle savedInstanceState)
{
.
.
.
super.appView.addJavascriptInterface(new MyInterface(this, appView), "interface");
}
...and then I call alert("interface.getPhoneNumber()") in the index.html file, but all I get is that string alerted, it doesn't actually call getPhoneNumber().
You can expose methods in an interface object, called MyInterface, which will be called from the Javascript running inside index.html. For example, you can have a method in MyInterface like:
#JavascriptInterface
public String getPhoneNumber(){
return (TelephonyManager)myCntxt.getSystemService(Context.TELEPHONY_SERVICE).getLine1Number();
}
Then, in your onCreate(), you will expose an instance of MyInterface, like this:
public void onCreate(Bundle savedInstanceState){
//...
super.appView.addJavascriptInterface(new MyInterface(this,appView), "interface");
}
Then, in your index.html, you will have some Javascript that calls this method.
For example,
<script type="text/javascript">
alert("interface.getPhoneNumber()");
</script>
Check out this question for details on how to do it.
EDIT: First, MyInterface does not need to extend DroidGap, e.g., it is a siple POJO.
Second, I made a small mistake in the JS: you don't need the double quotes.
<script type="text/javascript">
alert(window.interface.getPhoneNumber());
</script>
Third, as noted here, you will need to add this line after your super.onCreate():
super.init(); // Calling this is necessary to make this work
One small little think: You can use this._activity as your context, instead of calling getApplicationContext() in getPhoneNumber().
I'm currently displaying a bunch of data to the user as HTML in a webview. I have some links below each entry that should call a method in my app when clicked. The Android WebView's javascript interface seems to be the best (only?) way of handling these things. However, whenever I click the link, I get this error message: ERROR/Web Console(6112): Uncaught TypeError: Object [my namespace]#4075ff10 has no method 'edit' at [base URL]:55
I have the following interface declared:
public class JavaScriptInterface {
Context context;
JavaScriptInterface(Context c) {
context = c;
}
public void edit(String postid) {
Log.d("myApp", "EDIT!");
//do stuff
}
}
I then add it to my WebView:
final WebView threadView = (WebView) findViewById(R.id.webViewThread);
threadView.getSettings().setJavaScriptEnabled(true);
threadView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
And, finally, I call this within my HTML as follows:
<div class="post-actions">
<div class="right">
<a onClick="Android.edit('4312244');">Edit</a>
</div>
</div>
The real kicker is this all works when I'm debugging my app via the emulator or adb connection to my phone. When I build and publish the app, it breaks.
I'm at my wits end. Any help or advice would be greatly appreciated!
Same problem for my 2.3.3 mobile phone.
But as I knew one app that worked and another not, I was not happy with this workaround.
And I find out the differnce of my two apps.
The one with the broken JavaScriptInterface uses Proguard.
After a little search, I find a solution.
Short summary: interface JavascriptCallback, which is implemented by JavaScriptInterface and added rules for Proguard in proguard.conf:
public interface JavascriptCallback {
}
public class JavaScriptInterface implements JavascriptCallback {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
proguard.cfg:
-keep public class YOURPACKAGENAMEHERE.JavascriptCallback
-keep public class * implements YOURPACKAGENAMEHERE.JavascriptCallback
-keepclassmembers class * implements YOURPACKAGENAMEHERE.JavascriptCallback {
<methods>;
}
So, I'm pleased to say that my problem has been solved. Basically, it's a known bug in Gingerbread, and is present on my 2.3.4 device. After some head scratching, I found this workaround concocted by Jason Shah at PhoneGap. The real kudos for this goes to him as my solution is a slightly modified version of the code in that post.
The WebView
In my onLoad method, I call the following function.
private void configureWebView() {
try {
if (Build.VERSION.RELEASE.startsWith("2.3")) {
javascriptInterfaceBroken = true;
}
} catch (Exception e) {
// Ignore, and assume user javascript interface is working correctly.
}
threadView = (WebView) findViewById(R.id.webViewThread);
threadView.setWebViewClient(new ThreadViewClient());
Log.d(APP_NAME, "Interface Broken? " + javascriptInterfaceBroken.toString());
// Add javascript interface only if it's not broken
iface = new JavaScriptInterface(this);
if (!javascriptInterfaceBroken) {
threadView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
}
}
There are several things going on here.
In contrast with the PhoneGap method, I'm using a startsWith comparison against the version string. This is because Build.VERSION.RELEASE is 2.3.4 on my reference device. Rather than test against all releases in the 2.3 series, I'm comfortable painting all devices with one brushstroke.
javascriptInterface is a bool initialized to false. JavaScriptInterface, instantiated as iface, is the class that normally handles JS events in my WebView.
ThreadViewClient is the meat and potatoes of my implementation. It's where all the logic for handling the workaround occurs.
The WebViewClient
In the class ThreadViewClient (which extends WebViewClient), I first account for the fact that the js handler that Android normally attaches isn't here. This means that, if I want to use the same javascript calls from within my WebView, I need to duplicate the interface. This is accomplished by inserting custom handlers into the content of your website once it has loaded...
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (javascriptInterfaceBroken) {
final String handleGingerbreadStupidity =
"javascript:function shortSignature(id) { window.location='http://MyHandler:shortSignature:'+id; }; "
+ "javascript: function longSignature(text, username, forumnumber,threadnumber,pagenumber,postid) { var sep='[MyHandler]';"
+ "window.location='http://MyHandler:longSignature:' + encodeURIComponent(text + sep + username + sep + forumnumber + sep + threadnumber + sep + pagenumber + sep + postid);};"
+ "javascript: function handler() { this.shortSignature = shortSignature; this.longSignature = longSignature;}; "
+ "javascript: var Android = new handler();";
view.loadUrl(handleGingerbreadStupidity);
}
}
There's a lot to process there. In the javascript, I define an object handler that contains the functions that map to my js interface. An instance of it is then bound to "Android", which is the same interface name as that used by non-2.3 implementation. This allows for re-use of the code rendered within your webview content.
The functions take advantage of the fact that Android allows one to intercept all navigation that occurs within a WebView. In order to communicate with the outside program, they alter the window location to one with a special signature. I'll get into this in a bit.
Another thing I'm doing is concatenating the parameters of functions with more than one parameter. This allows me to reduce the code complexity within the location handler.
The location handler is also placed in ThreadViewClient...
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Method sMethod = null;
Log.d(APP_NAME, "URL LOADING");
if (javascriptInterfaceBroken) {
if (url.contains("MyHandler")) {
StringTokenizer st = new StringTokenizer(url, ":");
st.nextToken(); // remove the 'http:' portion
st.nextToken(); // remove the '//jshandler' portion
String function = st.nextToken();
String parameter = st.nextToken();
Log.d(APP_NAME, "Handler: " + function + " " + parameter);
try {
if (function.equals("shortSignature")) {
iface.shortSignature(parameter);
} else if (function.equals("longSignature")) {
iface.longSignature(parameter);
} else {
if (sMethod == null) {
sMethod = iface.getClass().getMethod(function, new Class[] { String.class });
}
sMethod.invoke(iface, parameter);
}
}
//Catch & handle SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
return true;
}
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
Here I am intercepting all URL load events that occur in the WebView. If the destination URL contains a magic string, the app attempts to parse it to extract out the method call. Rather than using the tokenizer to extract the individual parameters, I'm passing it to version of my longSignature method that can parse and handle it. This is detailed in the final part of this post.
If, by the time it has exited the "javascriptInterfaceBroken" block, execution has not be returned to the caller, this method treats the URL loading action as a normal link clicked event. In the case of my application I don't want to use the WebView for that, so I pass it off to the operating system via the ACTION_VIEW intent.
This is very similar to the implementation on Jason's blog. However I am bypassing reflection for the most part. I was attempting to use the method in the block with reflection to handle all of my bound functions, but due to my JavaScriptInterface being a nested class I was unable to look into it from another. However, since I defined the interface within the main Activity scope, its methods can be called directly.
Handling Concatenated Parameters
Finally, in my JavaScriptInterface, I created a handler to deal with the case of a concatenated parameter...
public void longSignature(String everything) {
try {
everything = URLDecoder.decode(everything, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e(APP_NAME, e);
}
final String[] elements = everything.split("\\[MyHandler\\]");
if (elements.length != 6) {
Toast.makeText(getApplicationContext(), "[" + elements.length + "] wrong number of parameters!", Toast.LENGTH_SHORT).show();
}
else {
longSignature(elements[0], elements[1], elements[2], elements[3], elements[4], elements[5]);
}
}
Hooray polymorphism!
And that's my solution! There's a lot of room for improvement, but, for now, this is sufficient. Sorry if some of my conventions have raised your hackles - this is my first Android app and I am unfamiliar with some of the best practices and conventions. Good luck!
You have to annotate (#JavascriptInterface) methods in Java class that you want to make available to JavaScript.
public class JavaScriptInterface {
Context context;
#JavascriptInterface
JavaScriptInterface(Context c) {
context = c;
}
#JavascriptInterface
public void edit(String postid) {
Log.d("myApp", "EDIT!");
//do stuff
} }
Its worked for me. Try out this.
I've taken Jason Shah's and Mr S's implementation as the building block for my fix and improved upon it greatly.
There's just far too much code to put into this comment I'll just link to it.
Details: http://twigstechtips.blogspot.com/2013/09/android-webviewaddjavascriptinterface.html
Source: https://github.com/twig/twigstechtips-snippets/blob/master/GingerbreadJSFixExample.java
Key points are:
Applies to all versions of Gingerbread (2.3.x)
Calls from JS to Android are now synchronous
No longer have to map out interface methods manually
Fixed possibility of string separators breaking code
Much easier to change JS signature and interface names