I am experimenting with drawing on canvas using a stream to create a simple game engine, but I am having some strange problems that I cannot explain. The purpose of this βgameβ is to draw a circle every second on the canvas. This works, but not the way I want it to work, it seems that the application switches between two stripes and adds a circle to each canvas, so that you switch between two stripes every second with the same number of circles, but in a different place on the canvas .
I donβt know what I am doing wrong, but I am not familiar with Treadding, is it somehow related to how many cores does my Android device have or something like that?
My code is shown below, so I just use startthread, which uses a layout file that refers to an animation that starts a thread and draws a circle on the canvas every second. (You can ignore touchhevent, it is not used yet).
The project exists from the main launch:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
which uses this layout file:
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.androidtesting.AnimationView android:id="@+id/aview" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </FrameLayout>
And my Surfaceview class with inner Thread class:
class AnimationView extends SurfaceView implements SurfaceHolder.Callback { private boolean touched = false; private float touched_x, touched_y = 0; private Paint paint; private Canvas c; private Random random; private AnimationThread thread; public AnimationView(Context context, AttributeSet attrs) { super(context, attrs); SurfaceHolder holder = getHolder(); holder.addCallback(this); thread = new AnimationThread(holder); } class AnimationThread extends Thread { private boolean mRun; private SurfaceHolder mSurfaceHolder; public AnimationThread(SurfaceHolder surfaceHolder) { mSurfaceHolder = surfaceHolder; paint = new Paint(); paint.setARGB(255,255,255,255); paint.setTextSize(32); } @Override public void run() { while (mRun) { c = null; try { c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { doDraw(c); sleep(1000); } } catch (Exception e) { e.printStackTrace(); }finally { if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } } } private void doDraw(Canvas canvas) {