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);
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() .
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.
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.
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 } });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With