我知道您问过不写 Java 类,但是您需要以一种或另一种方式编写。你需要PhoneGap Plugin
像安德烈所说的那样写。
创建自定义PhoneGap plugin
:
在您的应用程序包中创建一个新类:
package com.phonegap.plugins; //your package name
import org.json.JSONArray;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.api.PluginResult.Status;
public class Version extends Plugin {
public final String ACTION_GET_VERSION_NAME = "GetVersionName"; //not used in this version
public final String ACTION_GET_VERSION_CODE = "GetVersionCode";
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult result = new PluginResult(Status.INVALID_ACTION);
PackageManager packageManager = this.cordova.getActivity().getPackageManager();
if(action.equals(ACTION_GET_VERSION_CODE)) {
try {
PackageInfo packageInfo = packageManager.getPackageInfo(this.cordova.getContext().getPackageName(), 0);
result = new PluginResult(Status.OK, packageInfo.versionCode);
}
catch (NameNotFoundException nnfe) {
result = new PluginResult(Status.ERROR, nnfe.getMessage());
}
}
return result;
}
}
在 plugins.xml 中,添加以下行:
<plugin name="Version" value="your.package.Version" />
在您的deviceready
事件中添加以下代码:
var Version = function() {};
Version.prototype.getVersionCode = function(successCallback, failureCallback) {
return cordova.exec(successCallback, failureCallback, 'Version', 'GetVersionCode', []);
};
if(!window.plugins) {
window.plugins = {};
}
if (!window.plugins.version) {
window.plugins.version = new Version();
}
然后,您可以通过执行以下操作获取 versionCode 属性:
window.plugins.packageManager.getVersionCode(
function(versionCode) {
//do something with versionCode
},
function(errorMessage) {
//do something with errorMessage
}
);