wolfgang
wolfgang

Reputation: 4953

Android - Offscreen Drawing from non-UI thread

Short verson

Is it allowed, or do I need to use the UI thread?

EDIT: A reference to a place in the official android docs would be ideal.

Long version

Android docs make it clear that it's not allowed to "access the Android UI toolkit from outside the UI thread".

On the other hand, creating Bitmap objects from worker threads seems to be allowed, at least it's being done in sample code: http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html Apparently, the Bitmap class is not considered part of the "UI toolkit" as far as threading is concerned.

I've got a piece of code that seems to work when invoked from a non-ui thread. It involves using Bitmap.createBitmap(int,int,Bitmap.Config), new Canvas(bitmap), Typeface.create() and text drawing. My code does not refer to any View object.

Can someone point me to a piece of documentation that says that I may do these things from a background thread? Or will doing this lead to random crashes?

Upvotes: 5

Views: 2896

Answers (3)

Tae-Sung Shin
Tae-Sung Shin

Reputation: 20643

UI toolkit means UIs such as buttons, labels, listview, and so on provided by Google. You can't access them from non-ui thread mainly because they are not thread-safe.

What you are doing is not on UI toolkit but on low-level Canvas which is allowed (actually should be allowed) to access from non-ui threads. This mechanism is used in game development all the time. So I believe you are safe.

Upvotes: 4

zmbq
zmbq

Reputation: 39013

It should be legal as bitmaps just sit in memory all by themselves before you draw them.

I am looking into game development, in it seems there are some threads updating the UI ther too (using a similar technique of doing in-memory rendering)

Upvotes: 0

Jakub Szczygieł
Jakub Szczygieł

Reputation: 1222

Updating views has to be made on UI thread, or from remote thread with post function (which basiclly tells UI thread that remote thread wants something to be done), which is part of View class.

Upvotes: 0

Related Questions