问题
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