已解决 - 从Java调用javascript函数 [英] Resolved - Call javascript function from Java
问题描述
我开发使用PhoneGap的应用程序。我有一个服务,这是在背景为codeD本身(服务和手机应用的差距是在同一个项目)。不幸的是,我想打电话从这项服务中一个JavaScript函数。所以,我在网上搜索并成立一些有趣的事情:创建扩展插件类,并在其中做一些治疗。然后我发现这一点:
I develop an app using PhoneGap. I got a service which is in background and is coded natively (the service and the phone gap app is in the same project). Unfortunatly, I want to call a javascript function from this service. So I searched on the Web and founded something interesting : create a class extending Plugin and do some treatment in it. Then I found this :
this.ctx.sendJavascript("myJavascriptFunction");
我这个code测试,但蹊跷的事情发生了:
I tested with this code, but something wrong happened :
java.lang.NullPointerException
下面是我的测试:
class c = new class();
c.execute("myFunction",null,null);
在C类,执行方法是这样的:
In the class c, the execute method is like this :
public PluginResult execute(String action, JSONArray args, String callbackId) {
if (action.equals("myFunction")){
Log.d(TAG,"start actions to do");
this.ctx.sendJavascript("nameOfFunctionToLaunch");
Log.d(TAG,"end actions to do");
return new PluginResult(PluginResult.Status.OK);
}
}
在应用程序启动,我第一个
When the app start, I have the first
Log.d(TAG,"start actions to do");
我该如何解决这个问题呢?
How can I solve this problem ?
推荐答案
我终于找到了解决办法:其实在 NullPointerException异常是在 CTX 。
为了解决这个问题,我安装在上下文我对象的值 C 是这样的:
Finally I found the solution : in fact the NullPointerException was on ctx. To fix it, I setup the Context value of my object c like this :
c.setContext(use_An_Object_Of_Type_PhonegapActivity);
要获得对象,我抓住它从AppActivity在此方法:
To get the object, I grab it from the AppActivity in this method :
public class CloudPhoneAppActivity extends DroidGap {
private class NoScaleWebViewClient extends GapViewClient {
public NoScaleWebViewClient(DroidGap ctx) {
super(ctx);
myApp.ctx = ctx;
}
public void onScaleChanged(WebView view, float oldScale, float newScale) {
Log.d("NoScaleWebViewClient", "Scale changed: " + String.valueOf(oldScale) + " => " + String.valueOf(newScale));
}
}
/** other stuff after**/
}
所以,终于在这里是解决方案:
So finally here is the solution :
class c = new class();
c.setContext(myApp.ctx);
c.execute("myFunction",null,null);
有没有变化在执行方式是之前描述的事情。但要小心你是如何调用JavaScript函数。
There is no change to do in the execute method which is describe before. But be careful of how you call the javascript function.
二万
这篇关于已解决 - 从Java调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!