D
D
Dmitry Smerks2018-11-13 08:21:05
Java
Dmitry Smerks, 2018-11-13 08:21:05

Question about threads in Android?

I have code:

public class MainActivity extends AppCompatActivity {
MyDraw draw;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        draw = new MyDraw(this);
        setContentView(draw);
        time t1 = new time();
        t1.start();
    }

    class time extends Thread implements Runnable{
        @Override
        public void run() {
            for (int i = 1; i < 10; i++)  {
                Log.d("MyTestTag", "Поток активен. Цикл начался");
                draw.invalidate();
            }
            }

}

public class MyDraw extends View {
    int cx = 0;
    int cy = 0;
    public MyDraw(Context context) {
        super(context);
    }

    public void onDraw(Canvas canvas){
     super.onDraw(canvas);
     canvas.drawColor(Color.BLUE);
        Paint paint=new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.WHITE);
        i += 10;
     canvas.drawCircle(cx,cy,50,paint);
        Log.d("MyTestTag" ,"Обновление внутри");
    }


}

We use a thread where we loop through invalidate(); but for unknown reasons, my message is displayed in the log that we called the thread in the cycle, but from OnDraw the message about the update comes to the logs once, although according to the idea it should call invalidate 10 times in the cycle. We called invalidate() in the loop and it should start redrawing 10 times, where we change the coordinates and draw the object again

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
raxmatart, 2018-11-13
@SmerxDimas

https://developer.android.com/reference/android/vi...
Logs come once because the view is drawn once during initialization. It is impossible to access the view in android not from the main thread. A banal solution is to use postInvalidate()
PS If you want to see what and how is called, better use a debugger, not logs)

S
Sergey Gornostaev, 2018-11-13
@sergey-gornostaev

To be honest, I don't know exactly how the Android graphics subsystem works, but it's probably the same as the GUI libraries on the PC. When you run a GUI application, an event loop and an event queue are created. Events from the program, from the operating system, and from the user are queued. At each iteration, the event loop dequeues them and passes them to the appropriate handlers. In this case, the redraw handler will not be called 10 times at one iteration of the event loop if there are 10 invalidation events in the queue. This makes no sense both from the standpoint of the logic of the graphical interfaces and from the standpoint of performance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question