java - Why not do all the operations in the main thread(Android)? -
this clarifying question regarding asynctask class , specific illustration of using class networking operation(grabbing data).
how onpostexecute method running synchronously after doinbackground operation different having main thread work(onpostexecute , doinbackground)?
that main thread these operations sequentially, grabbing network info performing work in onpostexecute.
from docs:
when application launched, scheme creates thread of execution application, called "main." thread of import because in charge of dispatching events appropriate user interface widgets, including drawing events.
in other words, all ui-related tasks occur on same thread, , called main thread or ui thread.
when app performs intensive work in response user interaction, single thread model can yield poor performance unless implement application properly. specifically, if happening in ui thread, performing long operations such network access or database queries block whole ui.
simply put, when ui has wait i/o, info retrieval or info processing finish before can finish rendering screen, application "hangs" till process complete.
the user might decide quit application , uninstall if unhappy.
i think self-explanatory.
there 2 rules android's single thread model:
1. not block ui thread
2. not access android ui toolkit outside ui thread
hence, not related ui must done in separate thread, , related ui must done without kind of parallel processing.
so how perform parallel processing ? android offers different kinds of parallel processing based on needs:
1. old java threads
2. handlers
3. activity.runonuithread(runnable)
4. view.post(runnable)
5. view.postdelayed(runnable, long)
6. asynctasks
7. intentservices (services do not run on separate thread).
on side note, android enforces network operations performed on separate thread, else networkonmainthreadexception thrown.
now coming question : my question how difference form running on main thread? know onpostexecute has wait xml in background retrieve finish still lock ui user?
what happens if device has more 1 core, ui rendering done through 1 core (the main thread) while doinbackground() method executed on other core (the asynctask thread), , onpostexecute() method called on main thread after doinbackground() has returned. means onpostexecute() waiting ui finish rendering, both ui rendering & onpostexecute() occur on main thread.
now if device has 1 core, happen on single core, doinbackground() executed on separate thread, , onpostexecute() called after ui rendering finish , doinbackground() has returned.
i hope helpful.
further reading:
1. understanding asynctask – 1 time , forever
2. is android’s asynctask executing tasks serially or concurrently?
java android multithreading android-asynctask clarity
No comments:
Post a Comment