Android线程计时器实现
cocos2dx的计时器很好用,但当app进入后台,其计时器会pause掉,如果想要一个稳恒计时器就得自己去实现完成了,在Cocos2d-x for ios中我们可以利用NSTimer类并结合objc++来实现,非常好用。在Android平台我们就不得不用java类和jni来实现,计时器很多时候是用来刷新UI,所以还得考虑opengl线程调用问题
下面我贴了一个用java线程来实现的类,这个是项目正在使用的部分代码。一个是秒计时器,用于倒计时使用;一种是毫秒计时器,取网络数据包时使用
package com.iGamer; import org.cocos2dx.lib.Cocos2dxActivity; import org.cocos2dx.lib.Cocos2dxGLSurfaceView; public class TimerJavaToC { public static String SECOND_TIMER_NAME = "SECOND_TIMER_NAME"; public static String MILSECOND_TIMER_NAME = "MILSECOND_TIMER_NAME"; private Cocos2dxGLSurfaceView mGLSurfaceView = null; private Cocos2dxActivity mActivity; // 定义jni调用函数 private static native void secondTickHandler(); // 调用c++获取网络包 private static native void milsecondTickHandler(); private boolean _isSecondRunFlag = false; private boolean _isMilSecondRunFlag = false; public TimerJavaToC(Cocos2dxActivity act) { mActivity = act; mGLSurfaceView = Cocos2dxGLSurfaceView.getInstance(); _isSecondRunFlag = true; _isMilSecondRunFlag = true; init(); } private void init() { Thread secondThread = new Thread(new Runnable() { public void run() { try { if (!_isSecondRunFlag) { Thread.currentThread().interrupt(); //方法调用终止线程 return ; //跳出run方法 } while (_isSecondRunFlag) { //暂停一秒 Thread.sleep(1000); mGLSurfaceView.queueEvent( new Runnable() { @Override public void run() { //调用jni TimerJavaToC.secondTickHandler(); } }); } } catch(Throwable t) { //jest end the thread } } }); secondThread.start(); secondThread.setName(SECOND_TIMER_NAME); Thread milsecondThread = new Thread(new Runnable() { public void run() { try { if (!_isMilSecondRunFlag) { Thread.currentThread().interrupt(); //方法调用终止线程 return ; //跳出run方法 } while (_isMilSecondRunFlag) { //暂停一毫秒 Thread.sleep(1); mGLSurfaceView.queueEvent( new Runnable() { @Override public void run() { //调用jni \ TimerJavaToC.milsecondTickHandler(); } }); } } catch(Throwable t) { //jest end the thread } } }); milsecondThread.start(); milsecondThread.setName(MILSECOND_TIMER_NAME); } public void stopAllThread() { _isMilSecondRunFlag = false; _isSecondRunFlag = false; } }