简体   繁体   English

应用程序类是否在UI线程上运行?

[英]Application class does it run on UI thread or?

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? 抱歉,我是新手,但是我在Java的Application类中创建了一个方法,使用复杂到中等算法的方法运行安全吗? is it going to be a hiccup in the UI's? 它会在用户界面中打a吗?

From Processes and Threads | 进程和线程| Android Developers (emphasis mine): Android Developers (重点是我的):

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. 当应用程序组件启动并且该应用程序没有任何其他组件在运行时,Android系统将通过一个执行线程为该应用程序启动一个新的Linux进程。 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. 在UI线程中实例化在同一进程中运行的所有组件,并且从该线程调度对每个组件的系统调用。 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. 因此,响应系统回调的方法(例如onKeyDown()以报告用户操作或生命周​​期回调方法)始终在流程的UI线程中运行。

So yes, methods like onCreate in your Application class will be called on the main (UI) thread. 因此,是的,将在主(UI)线程上调用Application类中的诸如onCreate类的方法。

There are only a few classes that do start asynchronously, like the IntentService for example. 只有少数几个类可以异步启动,例如IntentService

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. 如果很复杂,则应使用ThreadAsyncTaskIntentService或更适合您的方式以异步方式运行它,但不要直接在Application / Activity / Fragment / Service的子类上运行它在UI线程上运行。 It will slow down the start up of you application otherwise. 否则,它将减慢您的应用程序的启动速度。

是的,从活动到广播接收器的所有应用程序组件都在ui线程上运行,仅当您必须执行一些长时间的提取任务或后台执行或网络提取时,才使用asynctask或intent服务在单独的线程中对其进行处理,以使它不会滞后您的用户界面屏幕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM