Android API 17 added a very powerful RenderScript feature: the ability to group scripts together and execute them as one. This helps greatly with performance and management of the scripts as the RenderScript engine handles the optimum way to exchange data with the scripts and removes the overhead associated with this coordination happening in Java. Unfortunately, the documentation is not very clear on how this feature can be leveraged, other than strictly the new intrinsics.

Let’s say you have a script which generates a RGB image into a bitmap Allocation, but you really need it in YUV format once it is done. To do this you can tie your custom script, fancy_image_gen, to the ScriptIntrinsicColorMatrix using a group. Start in the usual way: create a RenderScript object and your instances of the scripts.

RenderScript rsCtx = RenderScript.create(context);
ScriptC_fancy_image_gen myGen =
    new ScriptC_fancy_image_gen(rsCtx,
                                context.getResources(),
                                R.raw.fancy_image_gen);
ScriptIntrinsicColorMatrix mtrx =
    ScriptIntrinsicColorMatrix.create(rsCtx,
                                      Element.RGB_8888(rsCtx));

Now you need to create the ScriptGroup to pull them together.  The framework provides a ScriptGroup.Builder class to do this.  First create a ScriptGroup.Builder class then add your script instances to it and connect the two via their kernel IDs.  Now you are likely scratching your head and wondering what the heck a kernel ID is and where you get one.  If you look at the intrinsic classes you’ll see that each one of them has a getKernelID() method.  If you examine the documentation for ScriptC (the base reflection class for all scripts) there is no such method!  However, if you open up your generated Java file (assuming the standard root definition), you’ll see that there was a method generated for you:

public Script.KernelID getKernelID_root() {
    return createKernelID(mExportForEachIdx_root, 3, null, null);
}

This little guy is what you need to add the script to the group. So now we can finish out setting up our group:

Script.KernelID fancyID = myGen.getKernelID_root();
Script.KernelID mtrxID = mtrx.getKernelID();
ScriptGroup.Builder bldr = new ScriptGroup.Builder(rsCtx);
bldr.addKernel(fancyID);
bldr.addKernel(mtrxID);
Type.Builder tbldr =
    new Type.Builder(rsCtx, Element.RGB_8888(rsCtx));
bldr.addConnection(tbldr.create(), fancyID, mtrxID);

Now that you’re all setup, you can setup your input data and execute the group as needed:

SciptGroup rsGrp = bldr.create();
...
rsGrp.execute();

In the end this creates a more optimized method for doing your number crunching in well defined components while taking advantage of the new Android RenderScript intrinsics.