我正在尝试定期执行onDraw,例如每30ms执行一次。
private Canvas canvas;
private final long updateInterval = 30;
private long curDeadline;
@Override
protected void onDraw(Canvas canvas)
{
this.canvas = canvas;
long now = System.currentTimeMillis();
if (now < curDeadline) //too early, need to wait
{
long delay = curDeadline - now; //e.g. start drawing 5ms later
handler.postDelayed(runDoDraw, delay);
}
else
doDraw(); //execute immediately
}
private void doDraw()
{
long now = System.currentTimeMillis();
curDeadline = now+updateInterval;
canvas.drawBitmap(bmp, 0, 0, null);
invalidate();
}
private Runnable runDoDraw = new Runnable()
{
public void run()
{
doDraw();
}
};
但它会抛出
java.lang.NullPointerException
at android.view.GLES20RecordingCanvas.drawBitmap(GLES20RecordingCanvas.java:105)
at MyGame.doDraw(MyGame.java:963)
at MyGame.access$1(MyGame.java:945)
at MyGame$2.run(MyGame.java:1007)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
在source code中,它在第105行说明
super.drawBitmap(bitmap, src, dst, paint);
看起来像是一个错误的方法正在调用drawBitmap。 这是Android的错误吗?