android - 在 cordova 应用程序中使用 native 代码

标签 android cordova

我在 native android中有以下代码

List<PackageInfo> PackList = getPackageManager().getInstalledPackages(0);
for (int i=0; i < PackList.size(); i++)
{
    PackageInfo PackInfo = PackList.get(i);
    if ( ( (PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true)
    {
        String AppName = PackInfo.applicationInfo.loadLabel(getPackageManager()).toString();
        Log.e("App" + Integer.toString(i), AppName);
    }
}

用于获取有关移动设备中已安装应用程序的信息。我想在 cordova/phonegap 应用程序中使用。

  1. 我如何使用它?
  2. 我需要执行哪些步骤?
  3. 或者在不同的平台上使用相同的代码 (安卓、Windows)?

我也检查了这个link但没看懂

提前致谢

最佳答案

要在 phonegap 应用程序中使用 native 代码,您必须创建一个 phonegap 插件。这实际上非常简单:

1) 创建您的 phonegap 插件类,在这种情况下,插件仅响应“toast”操作以创建原生 Android toast:

public class ExamplePlugin extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if("toast".equals(action)) {
            // The first String in the arguments array is the text for the toast
            String text = args.getString(0);
            Toast toast = Toast.makeText(this.cordova.getActivity(), text, Toast.LENGTH_SHORT);
            toast.show();

            // With PluginResult you can send results back to the js layer.
            PluginResult result = new PluginResult(PluginResult.Status.OK, "--toast displayed.");
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
        }

        // Return true if everything worked as it should. If an error occurs return false.
        // Depending on this return value either the success or error callback is invoked.
        return true;
    }

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        // Here you can perform some initialisations for your plugin.
    }
}

然后在您的 phonegap 应用程序的 config.xml 中添加以下行:

<plugin name="ExamplePlugin" value="com.phonegap.example.ExamplePlugin" />

名称是您可以从 javascript 调用插件的名称,值是插件的完整类名。

现在您可以从 javascript 调用插件:

cordova.exec(successCallback, errorCallback, "ExamplePlugin", "toast", ["Hello Cordova!!1"]);

你提供了两个回调,你想要调用的插件的名称,你想要执行的 Action 和一个参数数组,在我们的例子中,插件被命名为“ExamplePlugin”, Action 是“toast”,我们只有在字符串参数上作为我们 toast 的文本。

当然这只适用于 Android。如果您想要不同平台的相同功能,例如iOS、Windows Phone 等。您还必须为它们中的每一个创建一个插件。

关于android - 在 cordova 应用程序中使用 native 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22455361/

相关文章:

javascript - ionic : Crosswalk crashing on Samsung S6 device

android - ionic 状态重置不起作用

javascript - 如何摆脱 Ionic/Cordova 模拟器中的 Facebook 警告?

java - Activity.finish() 在 Android 中是如何工作的?

android - 如何在 Android 中打开 pdf?

java - Android 开发从网站中提取数据并将其格式化为应用程序

cordova - 从 SocialSharing-PhoneGap-Plugin 的列表中删除不需要的社交共享选项

android - 什么是 ERROR_INTERNAL

Android 登录 - 帐户验证器与手动验证

android - Ionic Cordova Build Android找不到安装的构建工具