activity的使用(十五):surfaceview

package com.example.androidtest;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.graphics.Canvas;
import android.view.SurfaceView;
import android.view.SurfaceHolder;
import android.content.Context;

public class AndroidTest extends Activity {
	
	FastRenderView render;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_android_test);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		 render = new FastRenderView(this);
		setContentView(render);
	}
	
	protected void onResume()
	{
		super.onResume();
		render.resume();
	}
	
	protected void onPause()
	{
		super.onPause();
		render.pause();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.android_test, menu);
		return true;
	}

	class FastRenderView extends SurfaceView implements Runnable
	{
		Thread renderThread = null;
		SurfaceHolder holder;
		
		volatile boolean running = false;
		
		public FastRenderView(Context context) 
		{
			super(context);
			holder = getHolder();
		}
		
		public void resume()
		{
			running = true;
			renderThread = new Thread(this);
			renderThread.start();
		}
		
		public void run()
		{
			while (running) {
				if (!holder.getSurface().isValid()) continue;
				
				Canvas canvas = holder.lockCanvas();
				canvas.drawRGB(255, 0, 0);
				holder.unlockCanvasAndPost(canvas);
			}
		}
		
		public void pause()
		{
			running = false;
			while (true) {
				try {
					renderThread.join(); 
				} catch (InterruptedException e) {
					
				}
			}
		}
	}
}

你可能感兴趣的:(activity的使用(十五):surfaceview)