Native Extension Tip // Finding an Android Resource ID

Often when writing native extensions we've been faced with the problem of retrieving resources from the library. The official way to do this is to use the FREContext instance and the getResourceById() function. However there are several times when you'll want to access a resource packaged in your extension when the application has not been initialised (for example, onReceive events with a BroadcastReceiver), which initially seems impossible as you won't have access to your FREContext as yet.

There is however a simple workaround using the code below. You'll still need to be able to determine the package name of your application, which you can generally get from the Android Context.getPackageName().

  1. package com.distriqt.extension.util;
  2.  
  3. public class Resources
  4. {
  5. /**
  6.   * Retrieves an Android resource id for the given package, class and asset name.
  7.   *
  8.   * @param packageName This should be the package of your application
  9.   * from something like Context.getPackageName()
  10.   * @param className The class of the resource, eg "drawable"
  11.   * @param name The name of the resource, eg "icon"
  12.   * @return The Android resource id of the resource or -1 if it wasn't found
  13.   */
  14. public static int getResourseIdByName(String packageName, String className, String name)
  15. {
  16. int id = 0;
  17. try
  18. {
  19. for (int i = 0; i < Class.forName(packageName + ".R").getClasses().length; i++)
  20. {
  21. if(Class.forName(packageName + ".R").getClasses()[i].getName().split("\\$")[1].equals(className))
  22. {
  23. if(Class.forName(packageName + ".R").getClasses()[i] != null)
  24. id = Class.forName(packageName + ".R").getClasses()[i].getField(name).getInt(Class.forName(packageName + ".R").getClasses()[i]);
  25. break;
  26. }
  27. }
  28. }
  29. catch (Exception e)
  30. {
  31. return -1;
  32. }
  33. return id;
  34. }
  35. }
  36.  

Once you've got this class in your native extensions code, you can find a resource as follows:

  1. int iconId = Resources.getResourceIdByName( context.getPackageName(), "drawable", "icon" );

Grab the class code here.

Published by

Michael

http://michaelarchbold.com

Leave a Reply

Your email address will not be published. Required fields are marked *