Reputation: 201
When I write codes on Android platform,I often must be careful about the UI operation,which can only be done in UI Thread,I know it clearly,and I know why GUI use single thread to operate UI widget,in case of multi-thread simultaneous operation.But I want to know how the android system can distinguish between the UI thread and our own non-UI thread.Does UI-thread have a identifier?
Upvotes: 1
Views: 127
Reputation: 1251
This information is held by the Android framework, and it can be investigated in the same.
However, when you are developing an application, best practice is that you should avoid judging or reverse engineering the frameworks inner working and adapting your application. Rather, you should look at your requirement and find a way to reach it.
In your case, its apparent that you need to execute a piece of code on the GUI thread. For that, you do not need to make your thread as the GUI thread. You can do it in one of the following ways:
Use Runnables and post your code to the main activity, something like;
myActivity.post(new Runnable(){
@override
public void run(){
// your code to be run on GUI thread
}
)};
If activity is not accessible, then you can find the main handler of the app and post to it. Something like;
Handler appHandler = new Handler(context.getMainLooper()); appHandler.post(new Runnable(....
You can use runOnUIThread()
Upvotes: 0
Reputation: 200160
If you want to know if you are in the UI thread you can do something like:
if("main".equals(Thread.currentThread().getName())) {}
So, to answer your question, yes, the UI thread does have an identifier: "main".
Upvotes: 2
Reputation: 188
Any process you call from your MainActivity is run on the UI thread. If you don't want something to run on the UI thread, then launch it in an AsyncTask or background thread. This will prevent it from blocking the user interface so the user will still be able to interact with your app.
Upvotes: 0