【问题标题】:Android - Drawing on threadAndroid - 在线程上绘图
【发布时间】:2014-03-21 14:39:40
【问题描述】:

我想每 100 毫秒或按下按钮时重复绘制一些东西。对于按钮 onclick 事件,它可以正常工作,但我无法使其在线程中工作。以下是代码:

点击

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

线程

private Handler handler = new Handler();

private Runnable runnable = new Runnable()
{

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

绘制方法

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);
}

【问题讨论】:

    标签: android multithreading surfaceview


    【解决方案1】:

    这是因为 UI 线程与您的 Runnable 线程分开运行。像这样的单独线程不能交互。您将需要使用AsyncTask 线程,这将使您能够定期访问 UI 线程。

    例如:

    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();
        }
    }
    

    启动线程:

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

    停止线程:

    thread.cancel();
    

    有关 AsyncTask 的更多信息和示例,请访问 this question

    【讨论】:

      猜你喜欢
      • 2014-12-04
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      • 2012-11-15
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多