Android - Drawing on thread

纵饮孤独 提交于 2019-12-23 03:46:10

问题


I want to draw something repetitivelely each 100 milliseconds or when a button is pressed. For the button onclick event it works right, but I can't make it work in a thread. Following is the code:

onclick

    button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Draw();
        }
    });

thread

private Handler handler = new Handler();

private Runnable runnable = new Runnable()
{

    public void run()
    {
        Draw();
        handler.postDelayed(this, 1000);
    }
};

Draw method

private void Draw(){

    Paint paint = new Paint();
    int i;

    Canvas canvas = holder.lockCanvas();

    // Dibujo el fondo
    paint.setColor(getResources().getColor(android.R.color.black));
    canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), paint);

    holder.unlockCanvasAndPost(canvas);
}

回答1:


This is because the UI thread runs separately to your Runnable thread. Separate threads like this cannot interact. You will need to use an AsyncTask thread which will enable you to periodically access the UI thread.

For example:

private class ExampleThread extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {}

    @Override
    protected void doInBackground(Void... params) {
         while(!isCancelled()) { // Keep going until cancelled
             try {
                 Thread.sleep(100); // Delay 100 milliseconds
             } catch (InterruptedException e) {
                 Thread.interrupted();
             }
             publishProgress(); // Run onProgressUpdate() method
             if(isCancelled()) break; // Escape early if cancel() is called
         }

    }

    @Override
    protected void onPostExecute(Void... params) {}

    @Override
    protected void onProgressUpdate(Void... params) {
        // Here you can access the UI thread
        Draw();
    }
}

To start the thread:

ExampleThread thread = new ExampleThread();
thread.execute();

To stop the thread:

thread.cancel();

More information and examples with AsyncTask can be found on this question.



来源:https://stackoverflow.com/questions/22548764/android-drawing-on-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!