Reputation: 2958
Sorry for being a newbie but i created a method in Application class in java, is it safe to run a method with complex to medium algorithm? is it going to be a hiccup in the UI's?
Upvotes: 11
Views: 3540
Reputation: 157457
complex to medium algorithm
if it is complex, you should run it in an asynchronous way, using a Thread
, an AsyncTask
, an IntentService
or whatever suits you better, but don't run it directly on the a subclass of Application
/Activity
/Fragment
/Service
or whatever runs on the UI Thread. It will slow down the start up of you application otherwise.
Upvotes: 3
Reputation: 576
Yes all application components from activity to broadcast receivers run on ui thread,only when you have to do some long fetching task or background execution or a network fetch do it in a separate thread using asynctask or intent service,so that it does nor slag down your ui screen.
Upvotes: 4
Reputation: 100408
From Processes and Threads | Android Developers (emphasis mine):
When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the "main" thread). If an application component starts and there already exists a process for that application (because another component from the application exists), then the component is started within that process and uses the same thread of execution. However, you can arrange for different components in your application to run in separate processes, and you can create additional threads for any process.
And:
The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread. Consequently, methods that respond to system callbacks (such as onKeyDown() to report user actions or a lifecycle callback method) always run in the UI thread of the process.
So yes, methods like onCreate
in your Application
class will be called on the main (UI) thread.
There are only a few classes that do start asynchronously, like the IntentService for example.
Upvotes: 10