从CordovaActivity调用JavaScript [英] Call JavaScript from CordovaActivity
问题描述
我正在使用Cordova开发一个Android应用程序。我有一个自定义BroadcastReceiver,我想打开主(和唯一一个)CordovaActivity在 onReceive
方法。它工作正常。
I'm developing an Android app with Cordova. I have a custom BroadcastReceiver and I want to open the main (and the only one) CordovaActivity in onReceive
method. It works properly.
现在,我需要执行一个Javascript函数,根据意图的额外值来决定显示哪个屏幕(html)。
Now, I need execute a Javascript function to decide which screen (html) show, based on the value of an intent's extra.
MyBroadcastReceiver.java
public void onReceive(Context context, Intent intent) {
String myExtra = intent.getStringExtra("myExtra");
Intent toActivity = new Intent(context, MainCordovaActivity.class);
toActivity.putExtra("myExtra", myExtra);
context.startActivity(newActivity);
}
MainCordovaActivity.java
public class MainCordovaActivity extends CordovaActivity {
public void onCreate(Bundle s) {
super.onCreate(s);
super.init();
loadUrl(launchUrl);
String myExtra = getIntent().getExtras().getString("myExtra");
//Execute Javascript here
}
}
是我做的?我是以正确的方式吗?
How can I do that? Am I in the correct way?
感谢。
推荐答案
需要保持回调,以便能够调用成功/错误回调函数在你的插件中过了一段时间后,如这:
You need to keep the callback to be able to invoke success/error callback functions after some time has passed within your plugin like this:
在一些java类方法中:
within some java class method:
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
// assign callbackContext to class property named callbackContext
this.callbackContext = callbackContext;
然后,您可以将一个字符串(例如序列化的 JSONObject )传递到在一些java类方法中
Then you can pass a string(for instance serialized JSONObject) into a new instance of PluginResult that is returned to your success/error functions as parameter value:
,返回成功/错误函数的新实例 PluginResult :
within some java class method:
JSONObject serialized = new JSONObject();
serialized.put("value",1234);
// use assigned class property callbackContext to send some data back to your success callback
// because of PluginResult.Status.OK and by passing PluginResult.Status.ERROR you invoke error callback
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, serialized));
查看 接受为参数
在您的plugin.js文件中:
within your plugin.js file:
exec(function(serialized){
console.log(serialized.value);// 1234
}, function(){}, "your plugin name", "your plugin action", { some_arg:'for your plugin'});
这篇关于从CordovaActivity调用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!