xiaowoo
xiaowoo

Reputation: 2308

Android Force GPU Rendering How to enable and disable?

I am building an app that requires a lot of drawing on the canvas. I notice that the app is a bit laggy in devices with high resolution (nexus 7 for example). I saw there is a Force GPU option in the developer option. When Force GPU is enabled, my app runs absolutely smooth.

I have read that this Force GPU option is called Hardware Acceleration and it is available only for Android 3.0 and above.

My app is targeting Android 2.3 and above.

Is it possible to programmatically enable Hardware Accelerated (or Force GPU--whatever the magic is called) on any Android 3.0 or above devices?

Something like:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){

    Turn On Hardware Accelerate HERE but How can i do this?
    any code snippet would be welcome/helpful/thanks

}

Upvotes: 12

Views: 12986

Answers (3)

Niko
Niko

Reputation: 8153

If you want to build your application using lower api level you can access the method via reflection:

    try {
        Method setLayerType = view.getClass().getMethod(
                "setLayerType", new Class[] { int.class, Paint.class });
        if (setLayerType != null)
            setLayerType.invoke(view, new Object[] { LAYER_TYPE_X, null });
    } catch (NoSuchMethodException e) {
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    }

Where LAYER_TYPE_X is the constant integer value of wanted layer type:

LAYER_TYPE_NONE = 0
LAYER_TYPE_SOFTWARE = 1
LAYER_TYPE_HARDWARE = 2

Upvotes: 0

bmkay
bmkay

Reputation: 462

Set minSdkVersion to 10 and targetSdkVersion to maximum

Like below

 <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />

then

<application android:hardwareAccelerated="true" ...>

Now will work

And for particularities

if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){
     view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}

or

if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){
     view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

Upvotes: 4

ianhanniballake
ianhanniballake

Reputation: 200040

I assume you've already added android:hardwareAccelerated to your Manifest file?

<application android:hardwareAccelerated="true" ...>

That is what enables hardware acceleration within your application per the guide on hardware acceleration and should do exactly what forcing GPU does at a system level.

Upvotes: 7

Related Questions