Jika Anda menggunakan PhoneGap, buatlah plugin PhoneGap khusus:
Buat kelas baru di paket aplikasi Anda:
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;
}
}
Di plugins.xml, tambahkan baris berikut:
<plugin name="PackageManagerPlugin" value="com.Demo.PackageManagerPlugin" />
Dalam acara deviceready Anda , tambahkan kode berikut:
var PackageManagerPlugin = function() {
};
PackageManagerPlugin.prototype.getVersionName = function(successCallback, failureCallback) {
return PhoneGap.exec(successCallback, failureCallback, 'PackageManagerPlugin', 'GetVersionName', []);
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin('packageManager', new PackageManagerPlugin());
});
Kemudian, Anda bisa mendapatkan atribut versiName dengan melakukan:
window.plugins.packageManager.getVersionName(
function(versionName) {
//do something with versionName
},
function(errorMessage) {
//do something with errorMessage
}
);
Berasal dari sini dan sini .