I am trying to understand how background threads work. i am calling a background thread from my activity and i implement my thread handler in this activity as well. Lets say the user goes to activity b while my background thread is running. what happens when my background thread finishes its operation will i have to开发者_开发知识库 implement handlers in every single activity in the app or will the handler from activity a will be automatically invoked and will direct the user to activity a?
Handler
javadoc says:
Each Handler instance is associated with a single thread and that thread's
message queue.
Since all activities are created and their methods invoked on main application thread (also called EDT) and this is where you created your Handler, then when you invoke your handler (via post() or similar methods) from a background thread it will be execute in EDT.
what happens when my background thread finishes its operation will i have to
implement handlers in every single activity in the app or will the handler from
activity a will be automatically invoked and will direct the user to activity a?
- When in the background thread you invoke handler.post(runnable) than runnable's
run()
method will be executed in thread where you created handler (= the main app thread). - No it will not direct user to Activity A or make it visible. It will just execute
runnable.run()
method that you defined in Activity A.
In general you usually want to be using AsyncTask for threading because it will allow you to work with the UI thread in onPreExecute()
and onPostExecute()
.
You shouldn't do too much when their associated activity is not active. Ideally, you'd stop a thread in onPause()
.
For tasks that need to have their own life apart from that of an Activity, Services are recommended. From the docs:
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
You could then have multiple activities interacting with the same service that performs long-running operations.
精彩评论