Se stai usando PhoneGap, quindi crea un plug-in PhoneGap personalizzato:
Crea una nuova classe nel pacchetto della tua app:
package com.Demo; //replace with your package name
import org.json.JSONArray;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;
public class PackageManagerPlugin extends Plugin {
public final String ACTION_GET_VERSION_NAME = "GetVersionName";
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
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;
}
}
Nel plugins.xml, aggiungi la seguente riga:
<plugin name="PackageManagerPlugin" value="com.Demo.PackageManagerPlugin" />
Nel tuo evento deviceready , aggiungi il seguente codice:
var PackageManagerPlugin = function() {
};
PackageManagerPlugin.prototype.getVersionName = function(successCallback, failureCallback) {
return PhoneGap.exec(successCallback, failureCallback, 'PackageManagerPlugin', 'GetVersionName', []);
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin('packageManager', new PackageManagerPlugin());
});
Quindi, puoi ottenere l'attributo versionName facendo:
window.plugins.packageManager.getVersionName(
function(versionName) {
//do something with versionName
},
function(errorMessage) {
//do something with errorMessage
}
);
Derivato da qui e qui .