怎么在这个类中用onTouchEvent的MotionEvent.ACTION_DOWN实现线程的暂停

本文介绍了一个基于Android平台的游戏视图(GameView)类的设计与实现。该类通过SurfaceView进行屏幕绘制,支持基本的游戏循环逻辑,包括每秒60帧的刷新率控制,并实现了触摸事件的处理。此外,还提供了回调钩子(callback hook)机制以便于扩展。
package edu.qypt.zzh;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public abstract class GameView extends SurfaceView implements Callback,
Runnable {

private static final MotionEvent MotionEvent = null;

protected int refreshTime = 1000 / 60;

private boolean isRunning = false;

protected SurfaceHolder holder;

protected Paint paint;

protected int screenWidth;

protected int screenHeight;

protected CallbackHook callbackHook;
protected boolean su=true;
protected int n=0;

public GameView(Context context) {
super(context);
holder = this.getHolder();
holder.addCallback(this);
paint = new Paint();
paint.setColor(Color.WHITE);
setFocusable(true);
setKeepScreenOn(true);
}


@Override
public void run() {
while (isRunning) {
if(su==true){
long start = System.currentTimeMillis();
play();
draw();
long end = System.currentTimeMillis();
try {
if (end - start < refreshTime) {
Thread.sleep(refreshTime - (end - start));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
        }
}

public void addCallbackHook(CallbackHook callbackHook) {
this.callbackHook = callbackHook;
}

@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
}

@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
this.screenWidth = this.getWidth();
this.screenHeight = this.getHeight();
if (callbackHook != null) {
callbackHook.onSurfaceCreated(surfaceHolder);
}
new Thread(this).start();
isRunning = true;
}

@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
isRunning = false;
}

protected void draw() {
Canvas canvas = null;

try {
canvas = holder.lockCanvas();
if (canvas != null) {
canvas.drawRGB(0, 0, 0);
doDraw(canvas);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}

protected void doDraw(Canvas canvas) {
}

protected abstract void play();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值