Android - concurrent access to the canvas safely?

2019-08-26 13:45发布

问题:

I'm making a grid + tile activity where tiles need to move across the grid. The grid (and tiles) are being drawn on a surfaceView in a separate thread to the UI (UI deals with touch events and pushes them onto a queue for the grid to process).

This is all fine. I have a toolbar from which I can drag tiles. The toolbar is a View which has been added to the relative layout (and runs on the UI thread).

No matter how many times i use synchronize or try to safeguard the canvas from being written to at the same time, it still eventually causes a native SIGSEV11.

A few potential solutions:

  • Put everything into one thread - likely to fail or be very slow because of touch vs. draw
  • Draw everything that access the canvas in a single thread.

This would require a massive change which would probably take a few days.

Im wondering if anyone else has had similar issues and if I can synchronize access to the canvas without error.

Many Thanks.

回答1:

I would only ever have one thread update the screen, but you can have multiple threads update the data behind the screen then have them set a flag to cause the actual update of the screen.