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().
- package com.distriqt.extension.util;
- public class Resources
- * Retrieves an Android resource id for the given package, class and asset name.
- * @param packageName This should be the package of your application
- * from something like Context.getPackageName()
- * @param className The class of the resource, eg "drawable"
- * @param name The name of the resource, eg "icon"
- * @return The Android resource id of the resource or -1 if it wasn't found
- int id = 0;
- for (int i = 0; i < Class.forName(packageName + ".R").getClasses().length; i++)
- if(Class.forName(packageName + ".R").getClasses()[i].getName().split("\\$").equals(className))
- if(Class.forName(packageName + ".R").getClasses()[i] != null)
- id = Class.forName(packageName + ".R").getClasses()[i].getField(name).getInt(Class.forName(packageName + ".R").getClasses()[i]);
- catch (Exception e)
- return -1;
- return id;
Once you've got this class in your native extensions code, you can find a resource as follows:
- int iconId = Resources.getResourceIdByName( context.getPackageName(), "drawable", "icon" );
Grab the class code here.