How to generate status bar icons from text for an Android App

In the Android framework, the status bar icons have to be packaged with the APK and can’t be created dynamically. It’s ok if you need just a few icons, but what if you need a lot of icons? Here you run into a problem. In my case, I needed a set of icons created from text. Think for example that you would want to create an app that put a small icon on the status bar with the current temp and weather state. something like “45 rainy”. In order to accomplish that you need to combine all the combinations for temp + state. How can you do that?

One nice way to do that is to run code that executes a command-line script of an Image editor program called “ImageMagick”. With that program, you can produce automatically icons from a text and do a lot of other manipulations. Of course, the program must be installed on your computer.

In my case, I run this code from Unit test code, this way I didn’t have to deal with build a traditional Java program with a main method.

@Test
public void printIcons() throws IOException, InterruptedException {
    String iconContent;
    String fileName;
    String[] folders = {"/res/drawable-mdpi/", "/res/drawable-hdpi/", "/res/drawable-xhdpi/", "/res/drawable-xxhdpi/"};
    String[] sizes = {"24x24", "36x36", "48x48", "72x72"};
    String[] weatherStates = {"sunny", "rainy", "clear", "snow"};
    for (String state : weatherStates) {
        for (int i = -30; i < 25; i++) {
            iconContent = String.format("label:%d\n%s", i, state);
            for (int j = 0; j < 4; j++) {
                String path = String.format("/Users/******/Documents/test%s", folders[j]);
                Runtime.getRuntime().exec("mkdir -p " + path).waitFor();
                fileName = String.format("/Users/********/Documents/test%s%s_%d.gif", folders[j], state, (i));
                ProcessBuilder pb = new ProcessBuilder("/opt/local/bin/convert", "-background", "transparent", "-fill", "white", "-font", "Times-Bold-Italic",
                        "-size", sizes[j], "-gravity", "center", iconContent, fileName);
                pb.redirectErrorStream(true);
                Process process = pb.start();
                process.waitFor();
            }

        }
    }
}

In windows, the path for the “convert” may be different. Maybe something with “_full_path_/Magick convert”.

You can get the right R.drawable for the icon in this way:

int id = context.getResources().getIdentifier("clear_18", "drawable", context.getPackageName());
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
        .setContentTitle("title")
        .setContentText("content")
        .setSmallIcon(id);

Leave a Reply

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