Note that there are some explanatory texts on larger screens.

plurals
  1. POMulti-threading in the same Canvas
    text
    copied!<p>Well, I'll try to explain exactly what I pretend:</p> <p>I want to draw a bitmap in a canvas in random positions according to the coordinates of the screen on touch, and I want a message(text) to be displayed everytime the user touches the screen. </p> <p>So, if a draw the text in the same thread than I do for the bitmap, it will appear and dissapear right after, and I want it to stay in the screen for a few seconds and the dissapear. My first idea was to use Thread.sleep(), but for that I have to create a thread only for the text, or I will mess with the Bitmap too. </p> <p>I've been trying to use multithreading in the same canvas, but I don't know how. Can someone please explain to me... </p> <p>That's some of the code i've got so far: </p> <pre><code>private void init() { // CREATE SURFACEHOLDER AND ADD THIS CLASS AS HIS CALLBACK enemyHolder = getHolder(); enemyHolder.addCallback(this); scoreHolder = getHolder(); scoreHolder.addCallback(this); hasSurface = false; } </code></pre> <p>public void resume() {</p> <pre><code> if (surfaceViewThread == null) { surfaceViewThread = new SurfaceViewThread(); // CREATE A NEW // THREAD if (hasSurface) surfaceViewThread.start(); // START OUR THREAD } if (secondThread == null) { secondThread = new SecondThread(); if (hasSurface) secondThread.start(); } } public void surfaceCreated(SurfaceHolder holder) { hasSurface = true; if (surfaceViewThread != null) surfaceViewThread.start(); if (scoreShow == 1) { if (secondThread != null) secondThread.start(); } } </code></pre> <p>// THREAD</p> <pre><code> private final class SurfaceViewThread extends Thread { private boolean done; SurfaceViewThread() { super(); done = false; } @Override public void run() { // TODO Auto-generated method stub super.run(); SurfaceHolder surfaceHolder = enemyHolder; while (!done) { Canvas canvas = surfaceHolder.lockCanvas(); canvas.drawColor(Color.WHITE); canvas.drawBitmap(enemy1, enemy1X, enemy1Y, null); // DRAW // FIRST // ENEMY // SECOND THREAD private final class SecondThread extends Thread { private boolean done; SecondThread() { super(); done = false; } @Override public void run() { // TODO Auto-generated method stub super.run(); SurfaceHolder surfaceHolder = scoreHolder; while (!done) { Canvas canvas = surfaceHolder.lockCanvas(); Paint paint = new Paint(); paint.setColor(Color.BLACK); canvas.drawText("xD", 50, 50, paint); surfaceHolder.unlockCanvasAndPost(canvas); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } scoreShow = 0; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload