Sunday, 8 July 2012

Enable Hardware Acceleration using Java code

To enable Hardware Acceleration programmatically using Java code, call the following code with FLAG_HARDWARE_ACCELERATED:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

The flag FLAG_HARDWARE_ACCELERATED indicates whether this window should be hardware accelerated. Requesting hardware acceleration does not guarantee it will happen.

Enable Hardware Acceleration using Java code


It is important to remember that this flag must be set before setting the content view of your activity or dialog.

This flag cannot be used to disable hardware acceleration after it was enabled in your manifest using hardwareAccelerated (refer Enable Hardware Acceleration for Android 3.0 or later devices). If you need to selectively and programmatically disable hardware acceleration (for automated testing for instance), make sure it is turned off in your manifest and enable it on your activity or dialog when you need it instead, using the method described above.

package com.example.androidhardwareacceleration;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView hw;
ImageView imageView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

setContentView(R.layout.activity_main);

imageView = (ImageView)findViewById(R.id.iv);
hw = (TextView)findViewById(R.id.hw);

imageView.setImageResource(R.drawable.ic_launcher);

imageView.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
boolean isHWAccelerated = imageView.isHardwareAccelerated();
hw.setText("isHardwareAccelerated: " + String.valueOf(isHWAccelerated));

}});

}

}


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/hw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Touch the big icon to check isHardwareAccelerated"/>

</RelativeLayout>


Related:
- Enable Hardware Acceleration for Android 3.0 or later devices


No comments:

Post a Comment