Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In android can you load resources outside the ui thread

Tags:

android

I have what is hopefully a simple question. I want to know if you can safely load resources from a non-ui thread. I'm talking about things in the "res" folder. I just can't find any documentation that definitively answers this question. There are a lot of mentions in the SDK related to what is not allowed on the UI Thread. I never saw anything that mentioned loading resources in this way.

For example can I call this code from a background thread? Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_resource);

Does it help if I remove the context.getResources() part and only do: Bitmap icon = BitmapFactory.decodeResource(res, R.drawable.icon_resource);

like image 734
Nathan Avatar asked Jan 23 '13 03:01

Nathan


People also ask

What is difference between main thread and UI in Android?

Main Thread: The default, primary thread created anytime an Android application is launched. Also known as a UI thread, it is in charge of handling all user interface and activities, unless otherwise specified. Runnable is an interface meant to handle sharing code between threads. It contains only one method: run() .

Can we update UI from thread in Android?

However, note that you cannot update the UI from any thread other than the UI thread or the "main" thread. To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help: Activity.

Why should you avoid to run non UI code on the main thread?

If you put long running work on the UI thread, you can get ANR errors. If you have multiple threads and put long running work on the non-UI threads, those non-UI threads can't inform the user of what is happening.

What are different ways of updating UI from background thread?

In this case, to update the UI from a background thread, you can create a handler attached to the UI thread, and then post an action as a Runnable : Handler handler = new Handler(Looper. getMainLooper()); handler. post(new Runnable() { @Override public void run() { // update the ui from here } });


1 Answers

Yes you can!

But it strongly depends on how the API's handle such calls. For example. if an API expects a context, then you may have to provide it the right one by saving your UI context and passing it on to the background thread.

However, when it comes to setting UI components, you will have to return to the UI thread.

like image 114
Royston Pinto Avatar answered Oct 14 '22 22:10

Royston Pinto