Android - 是否可以从包装在PhoneGap中的应用程序中触发本机意图

Android - Is it possible to fire a native intent from an application wrapped in PhoneGap

本文关键字:应用程序 意图 本机 PhoneGap 是否 包装 Android      更新时间:2023-09-26

我正在Sencha Touch 2.0.1和PhoneGap上开发一个应用程序。
我需要捕获在Sencha Touch中触发的事件并将其传输到本机Android环境。

即:一些煎茶触摸控制按钮需要在点击时触发意图以启动另一个活动(非PhoneGap活动)。

到目前为止,我已经找到了各种例子,例如webintents和这个。但据我所知,这些不适用于我的情况。

我试图放弃PhoneGap并使用另一个包装器,或者以某种方式规避此问题。提前感谢!

我认为您需要制作自己的phonegap插件,该插件可以从其执行方法内部启动本机活动。

有一个ContactView插件,你应该能够用作编写自己的指南。

https://github.com/phonegap/phonegap-plugins/blob/master/Android/ContactView/ContactView.java

具体来说这两种方法

    @Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
    startContactActivity();
    PluginResult mPlugin = new PluginResult(PluginResult.Status.NO_RESULT);
    mPlugin.setKeepCallback(true);
    this.callback = callbackId;
    return mPlugin;
}
public void startContactActivity() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
    this.ctx.startActivityForResult((Plugin) this, intent, PICK_CONTACT);
}

看看这个,显式和隐式意图部分(1.2,1.3):http://www.vogella.de/articles/AndroidIntent/article.html

然后看看WebIntent.java的源代码,特别是startActivity函数:https://github.com/phonegap/phonegap-plugins/blob/master/Android/WebIntent/WebIntent.java

void startActivity(String action, Uri uri, String type, Map<String, String> extras) {
  Intent i = (uri != null ? new Intent(action, uri) : new Intent(action));

然后是这里的意图构造函数(搜索构造函数):http://developer.android.com/reference/android/content/Intent.html

WebIntent不支持采用Android类的Intent构造函数。

但是你可以扩展函数,让它以明确的意图工作(下面的代码快速、肮脏且未经测试):

void startActivity(String action, Uri uri, String type, String className, Map<String, String> extras) {
  Intent i;
  if (uri != null)
    i = new Intent(action, uri)
  else if (className != null)
    i = new Intent(this.ctx, Class.forName(className));
  else
    new Intent(action));

上面,在 execute 函数中,您还必须解析出"解析参数"部分中的新参数

// Parse the arguments
JSONObject obj = args.getJSONObject(0);
String type = obj.has("type") ? obj.getString("type") : null;
Uri uri = obj.has("url") ? Uri.parse(obj.getString("url")) : null;
String className = obj.has("className") ? obj.getString("className") : null;
JSONObject extras = obj.has("extras") ? obj.getJSONObject("extras") : null;

然后在调用中传递新的类名字符串以启动活动几行:

startActivity(obj.getString("action"), uri, type, className, extrasMap);

然后,您应该能够使用类似以下内容按类名调用 android 活动:

Android.callByClassName = function(className) { 
  var extras = {};
  extras[WebIntent.EXTRA_CUSTOM] = "my_custom";
  extras[WebIntent.EXTRA_CUSTOM2] = "my_custom2";
  window.plugins.webintent.startActivity({
    className: className, 
    extras: extras 
  }, 
  function() {}, 
  function() {
    alert('Failed to send call class by classname');
  }
); 

};

其中类名类似于:com.company.ActivityName

免责声明:粗略的代码,未经测试。