代码如下
package org.example.ch04_android_basics;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
public class SurfaceViewTest extends Activity {
FastRenderView renderView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
renderView = new FastRenderView(this);
setContentView(renderView);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
renderView.pause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
renderView.resume();
}
class FastRenderView extends SurfaceView implements Runnable{
Thread renderThread = null;
SurfaceHolder holder;
Random rand = new Random();
volatile boolean running = false;
public FastRenderView(Context context) {
super(context);
// TODO Auto-generated constructor stub
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(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
holder.unlockCanvasAndPost(canvas);
}
}
public void pause(){
running = false;
while(true){
try{
renderThread.join();
}catch(InterruptedException e){
// retry
}
}
}
}
}
我照书上敲的代码,用一个SurfaceView在UI主线程外的另一个不同线程进行简单的渲染
运行的时候屏幕一直在闪着不同颜色的光,当我按返回键时,这个Activity就卡住了
屏幕马上变黑了,但又没有退出程序,最后显示程序未响应
public void pause(){
running = false;
while(true){
try{
renderThread.join();
}catch(InterruptedException e){
// retry
}
}
}
我感觉就是这段代码有问题,可能是死循环了,书上说用renderThread.join();
的目的是等待线程完全销毁
------解决方案--------------------
把pause里面的while循环去掉。