List of installed Android Apps with PhoneGap

PhoneGap is a project that aims to package WebApps (think HTML5, Javascript, JQuery, …) into native Apps for all the major mobile platforms. In contrast to just using the App in the web browser on your device it allows you to access native functionality (e.g., accelerometer, contacts, geo location, …) via Javascript from within the WebApp. You can even extend this with your own plugins – Boris Smus has an excellent introduction to PhoneGap Plugin Development over at his blog.

Since I needed to get a list of installed Apps on an Android device for a little project I’m currently working on, I have extended his example a bit. In case anyone also needs it – here’s the required code, Java part first:

else if (action.equals("getAppList")) {
  Intent i = new Intent(Intent.ACTION_MAIN, null);
  i.addCategory(Intent.CATEGORY_LAUNCHER);
  List appList = this.ctx.getPackageManager().queryIntentActivities(i, 0);
  JSONArray apps = new JSONArray();
  JSONObject info = new JSONObject();
  for (ResolveInfo appInfo : this.ctx.getPackageManager().queryIntentActivities(i, 0)) {
    apps.put(appInfo.activityInfo.applicationInfo.loadLabel(this.ctx.getPackageManager()).toString());
  }

  return new PluginResult(PluginResult.Status.OK, apps.toString().replace("'", "\\'"));
}

You will have to put all that as the last else if case into the execute()-method of your Plugin-extending class (assuming some programming knowledge here ;)). The last line is a little black magic voodoo – I had problems with some Apps’ name containing a ‘, which threw the JSON Parser into hissy fits, but it’s not quite the most elegant solution. Proceed with caution.

You will also need this Javascript somewhere in your Plugin initialisation file:

AppList.prototype.getAppList =
function(params, success, fail) {
  return PhoneGap.exec(function(args) {
    success(args);
  }, function(args) {
    fail(args);
  }, 'AppList', 'getAppList', [params]);
};

This code snippet assumes your Plugin is namend AppList, so change that into whatever your actual name is.

Well, if I haven’t forgotten to add anything here and you integrated those code snippets successfully to your project, you should be able to call the method as follows:

function getAppList() {
  return window.plugins.applist.getAppList(
    "dummyValue",
    function(data) { // success
      return jQuery.parseJSON(data);
    }, function() { // error
      return false;
    }
  );
}

Again, be aware that this example uses the plugin name of AppList, don’t forget to change that. Hopefully, you now have your list of Applications! Of course, this should be extended for other platforms as well to make it truly ‘PhoneGap-y’, but at least we have Android covered now 😉

This entry was posted in development and tagged , , , , . Bookmark the permalink.