我需要编写一个 cordova 插件来检索用于 Android 应用程序的应用程序名称、版本代码和版本名称。请尽快回复...在此先感谢 :)
这是我的代码....收到无效的操作错误消息。
在My.js 中
var AppInfo = function() {};
AppInfo.prototype.getVersionName = function(successCallback, failureCallback) {
return cordova.exec(
successCallback,
failureCallback,
'AppInfo',
'GetVersionName',
[]
);
};
在AppInfo.java (插件)中
package com.cordova.plugin.appInfo;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.api.PluginResult.Status;
public class AppInfo extends CordovaPlugin {
public final String ACTION_GET_VERSION_NAME = "GetVersionName";
Context ctx;
public PluginResult execute(String action, JSONArray args, String callbackId) {
ctx = cordova.getContext();
PluginResult result = new PluginResult(Status.INVALID_ACTION);
PackageManager packageManager = this.ctx.getPackageManager();
if(action.equals(ACTION_GET_VERSION_NAME)) {
try {
PackageInfo packageInfo = packageManager.getPackageInfo(
this.ctx.getPackageName(), 0);
result = new PluginResult(Status.OK, packageInfo.versionName);
}
catch (NameNotFoundException nnfe) {
result = new PluginResult(Status.ERROR, nnfe.getMessage());
}
}
return result;
}
}
在.html中
<script>
function onDeviceReady () {
$('#send').bind('click', function () {
alert('Hello World');
window.applicationInfo = new AppInfo();
window.applicationInfo.getVersionName( function(versionName){
alert("versionName" + versionName);
},
function (errorMessage){
alert("Error is "+errorMessage);
}
);
});
}
document.addEventListener("deviceready", onDeviceReady, false);
</script>
最后在plugin.xml中设置权限和插件