源码分析 -- ActivityThread

来源:互联网 发布:淘宝网天猫女装外套 编辑:程序博客网 时间:2024/06/06 01:55

1. ActivityThread功能

       它管理应用进程的主线程的执行(相当于普通Java程序的main入口函数),并根据AMS的要求负责调度和执行activities、broadcasts和其它操作。

       在Android系统中,在默认情况下,一个应用程序内的各个组件(如Activity、BroadcastReceiver、Service)都会在同一个进程(Process)里执行,且由此进程的【主线程】负责执行。

       在Android系统中,如果有特别指定(通过android:process),也可以让特定组件在不同的进程中运行。无论组件在哪一个进程中运行,默认情况下,他们都由此进程的【主线程】负责执行。

     【主线程】既要处理Activity组件的UI事件,又要处理Service后台服务工作,通常会忙不过来。为了解决此问题,主线程可以创建多个子线程来处理后台服务工作,而本身专心处理UI画面的事件。

     【主线程】的主要责任:

       • 快速处理UI事件。而且只有它才处理UI事件, 其它线程还不能存取UI画面上的对象(如TextView等),此时, 主线程就叫做UI线程。基本上,Android希望UI线程能根据用户的要求做出快速响应,如果UI线程花太多时间处理后台的工作,当UI事件发生时,让用户等待时间超过5秒而未处理,Android系统就会给用户显示ANR提示信息。

         只有UI线程才能执行View派生类的onDraw()函数。

      • 快速处理Broadcast消息。【主线程】除了处理UI事件之外,还要处理Broadcast消息。所以在BroadcastReceiver的onReceive()函数中,不宜占用太长的时间,否则导致【主线程】无法处理其它的Broadcast消息或UI事件。如果占用时间超过10秒, Android系统就会给用户显示ANR提示信息。

      注意事项:

      • 尽量避免让【主线程】执行耗时的操作,让它能快速处理UI事件和Broadcast消息。

      • BroadcastReceiver的子类都是无状态的,即每次启动时,才会创建其对象,然后调用它的onReceive()函数,当执行完onReceive()函数时,就立即删除此对象。由于每次调用其函数时,会重新创建一个新的对象,所以对象里的属性值,是无法让各函数所共享。          

1.1 Thread与SurfaceView

      View组件由UI线程(主线程)所执行。如果需要迅速更新UI画面或UI画图需要较长时间,则需要使用SurfaceView。它可由后台线程(background thread)来执行,而View只能由UI(主)线程执行。SurfaceView内有高效的rendering机制,可以让后台线程快速刷新Surface的内容。

      View ---> UI(主)线程

      SurfaceView ---> 后台线程  

2. Android应用程序主线程stack

如果不单独创建子线程,一个应用包含以下的线程,是系统自动创建的

并不是只有一个main主线程。具体看系统应用的启动流程分析

这些线程运行在不同的进程中,除了main,都是系统进程

应用程序所在的进程中只有main这一个线程


main线程启动的stack如下:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. at android.os.MessageQueue.nativePollOnce(Native Method)      
  2. at android.os.MessageQueue.next(MessageQueue.java:118)    
  3. at android.os.Looper.loop(Looper.java:118)    
  4.   
  5. at android.app.ActivityThread.main(ActivityThread.java:4424)    // Java main入口函数  
  6.   
  7. at java.lang.reflect.Method.invokeNative(Native Method)   
  8. at java.lang.reflect.Method.invoke(Method.java:511)   
  9. at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)    
  10. at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)   
  11. at dalvik.system.NativeStart.main(Native Method)     
可以看出Java层的入口函数是通过反射调用的ActivityThread类中的main函数,然后在main函数中进行消息循环。

也就是android的应用进程的入口是ActivityThread,而不是Application.

ActivityThread是主线程,会有个Handler处理消息。

消息处理函数定义如下:

    1. public void handleMessage(Message msg) {  
    2.     switch (msg.what) {  
    3.         //  这里收到消息以后才会反射创建Applicationd 的对象
    4.         case BIND_APPLICATION: // 创建Application对象  
    5.             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");  
    6.             AppBindData data = (AppBindData)msg.obj;  
    7.             handleBindApplication(data);  
    8.             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
    9.             break

ActivitiyThread是应用程序概念空间的重要概念,他建立了应用进程运行的框架,并提供了一个IActivityThread接口作为与 Activity Manager Service的通讯接口.通过该接口AMS可以将Activity的状态变化传递到客户端的Activity对象。

3. IApplicationThread关系图


ApplicationThread类是ActivitiyThread的内部类

private class ApplicationThread extends ApplicationThreadNative {

       // 实现了以下的方法,具体看下面源码分析

        schedulePauseActivity

       scheduleLaunchActivity

}

4. ActivityThread类

4.1 类中关键信息

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * This manages the execution of the main thread in an 
  3.  * application process, scheduling and executing activities, 
  4.  * broadcasts, and other operations on it as the activity 
  5.  * manager requests. 
  6.  * 
  7.  * {@hide} 
  8.  */  
  9. public final class ActivityThread {  
  10.   
  11.     static ContextImpl mSystemContext = null;  
  12.   
  13.     static IPackageManager sPackageManager;  
  14.       
  15.     // 创建ApplicationThread实例,以接收AMS指令并执行  
  16.     final ApplicationThread mAppThread = new ApplicationThread();  //定义的内部类
  17.   
  18.     final Looper mLooper = Looper.myLooper();  
  19.   
  20.     final H mH = new H();   // 定义的内部类,Handler子类,用于处理消息
  21.   
  22.     final HashMap<IBinder, ActivityClientRecord> mActivities  
  23.             = new HashMap<IBinder, ActivityClientRecord>();  // 定义的内部类
  24.       
  25.     // List of new activities (via ActivityRecord.nextIdle) that should  
  26.     // be reported when next we idle.  
  27.     ActivityClientRecord mNewActivities = null;  
  28.       
  29.     // Number of activities that are currently visible on-screen.  
  30.     int mNumVisibleActivities = 0;  
  31.       
  32.     final HashMap<IBinder, Service> mServices  
  33.             = new HashMap<IBinder, Service>();  
  34.       
  35.     Application mInitialApplication;  
  36.   
  37.     final ArrayList<Application> mAllApplications  
  38.             = new ArrayList<Application>();  
  39.   
  40.     static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal<ActivityThread>();  
  41.     Instrumentation mInstrumentation;  
  42.   
  43.     static Handler sMainThreadHandler;  // set once in main()  
  44.   
  45.     static final class ActivityClientRecord {  
  46.         IBinder token;  
  47.         int ident;  
  48.         Intent intent;  
  49.         Bundle state;  
  50.         Activity activity;  
  51.         Window window;  
  52.         Activity parent;  
  53.         String embeddedID;  
  54.         Activity.NonConfigurationInstances lastNonConfigurationInstances;  
  55.         boolean paused;  
  56.         boolean stopped;  
  57.         boolean hideForNow;  
  58.         Configuration newConfig;  
  59.         Configuration createdConfig;  
  60.         ActivityClientRecord nextIdle;  
  61.   
  62.         String profileFile;  
  63.         ParcelFileDescriptor profileFd;  
  64.         boolean autoStopProfiler;  
  65.   
  66.         ActivityInfo activityInfo;  
  67.         CompatibilityInfo compatInfo;  
  68.         LoadedApk packageInfo; //包信息,通过调用ActivityThread.getPapckageInfo而获得  
  69.   
  70.         List<ResultInfo> pendingResults;  
  71.         List<Intent> pendingIntents;  
  72.   
  73.         boolean startsNotResumed;  
  74.         boolean isForward;  
  75.         int pendingConfigChanges;  
  76.         boolean onlyLocalRequest;  
  77.   
  78.         View mPendingRemoveWindow;  
  79.         WindowManager mPendingRemoveWindowManager;  
  80.   
  81.         ...  
  82.     }  
  83.     //  ApplicationThread继承自ApplicationThreadNative, 而ApplicationThreadNative又继承自Binder并实现了IApplicationThread接口。IApplicationThread继承自IInterface。这是一个很明显的binder结构,用于Ams通信。IApplicationThread接口定义了对一个程序(linux的进程)操作的接口。ApplicationThread通过binder与Ams通信,并将Ams的调用,通过下面的H类(也就是Hnalder)将消息发送到消息队列,然后进行相应的操作,入activity的start, stop。
  84.     private class ApplicationThread extends ApplicationThreadNative {  
  85.   
  86.         private void updatePendingConfiguration(Configuration config) {  
  87.             synchronized (mPackages) {  
  88.                 if (mPendingConfiguration == null ||  
  89.                         mPendingConfiguration.isOtherSeqNewer(config)) {  
  90.                     mPendingConfiguration = config;  
  91.                 }  
  92.             }  
  93.         }  
  94.         //  给主消息队列发送消息,处理暂停事件
  95.         //  这些方法是在IApplicationThread接口定义的方法,由ApplicationThread这个类实现。应该是由Ams回调的。
  96.         public final void schedulePauseActivity(IBinder token, boolean finished,  
  97.                 boolean userLeaving, int configChanges) {  
  98.             queueOrSendMessage(  
  99.                     finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,  
  100.                     token,  
  101.                     (userLeaving ? 1 : 0),  
  102.                     configChanges);  
  103.         }  
  104.   
  105.         // we use token to identify this activity without having to send the  
  106.         // activity itself back to the activity manager. (matters more with ipc) 
  107.         // startActivity流程中就是调用的这个函数,应该是由AMs调用的。具体的调用时机看AMS的内容
  108.         public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,  
  109.                 ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,  
  110.                 Bundle state, List<ResultInfo> pendingResults,  
  111.                 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,  
  112.                 String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {            
  113.             ActivityClientRecord r = new ActivityClientRecord();  
  114.   
  115.             r.token = token;  
  116.             r.ident = ident;  
  117.             r.intent = intent;  
  118.             r.activityInfo = info;  
  119.             r.compatInfo = compatInfo;  
  120.             r.state = state;  
  121.   
  122.             r.pendingResults = pendingResults;  
  123.             r.pendingIntents = pendingNewIntents;  
  124.   
  125.             r.startsNotResumed = notResumed;  
  126.             r.isForward = isForward;  
  127.   
  128.             r.profileFile = profileName;  
  129.             r.profileFd = profileFd;  
  130.             r.autoStopProfiler = autoStopProfiler;  
  131.   
  132.             updatePendingConfiguration(curConfig);  
  133.             // 往消息队列发送一个消息LAUNCH_ACTIVITY。启动activity.
  134.             queueOrSendMessage(H.LAUNCH_ACTIVITY, r);  
  135.         }  
  136.   
  137.         ...  
  138.     }  
  139.    
  140.     // 处理主线程的消息
  141.     private class H extends Handler {  
  142.   
  143.         public void handleMessage(Message msg) {  
  144.             if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));  
  145.             switch (msg.what) {  
  146.                 case LAUNCH_ACTIVITY: {  
  147.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");  
  148.                     ActivityClientRecord r = (ActivityClientRecord)msg.obj;  
  149.   
  150.                     r.packageInfo = getPackageInfoNoCheck(  
  151.                             r.activityInfo.applicationInfo, r.compatInfo); 
  152.                     // 对应activity的启动流程,这里面才会反射创建activity的对象和进行初始化,调用onCreate方法
  153.                     handleLaunchActivity(r, null);  
  154.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  155.                 } break;  
  156.                 ...  
  157.             }  
  158.             if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));  
  159.         }  
  160.          
  161.         ...  
  162.     }  
  163.   
  164.     public static ActivityThread currentActivityThread() {  
  165.         return sThreadLocal.get();  
  166.     }  
  167.   
  168.     // 整个应用程序的入口函数
  169.     public static void main(String[] args) {  
  170.         SamplingProfilerIntegration.start();  
  171.   
  172.         // CloseGuard defaults to true and can be quite spammy.  We  
  173.         // disable it here, but selectively enable it later (via  
  174.         // StrictMode) on debug builds, but using DropBox, not logs.  
  175.         CloseGuard.setEnabled(false);  
  176.   
  177.         Environment.initForCurrentUser();  
  178.   
  179.         // Set the reporter for event logging in libcore  
  180.         EventLogger.setReporter(new EventLoggingReporter());  
  181.   
  182.         Process.setArgV0("<pre-initialized>");  
  183.         
  184.         Looper.prepareMainLooper();  //我们都知道主线程可以使用Handler进行异步通信,因为主线程中已经创建了Looper,而这个Looper就是在这里创建的。如果其他线程需要使用Handler通信,就要自己去创建Looper。
  185.   
  186.         // 创建ActivityThread实例  
  187.         ActivityThread thread = new ActivityThread();  
  188.         thread.attach(false);  
  189.   
  190.         if (sMainThreadHandler == null) {  
  191.             sMainThreadHandler = thread.getHandler();  
  192.         }  
  193.   
  194.         AsyncTask.init();  
  195.   
  196.         if (false) {  
  197.             Looper.myLooper().setMessageLogging(new  
  198.                     LogPrinter(Log.DEBUG, "ActivityThread"));  
  199.         }  
  200.   
  201.         Looper.loop();  // 进入消息循环
  202.   
  203.         throw new RuntimeException("Main thread loop unexpectedly exited");  
  204.     }  
  205. }  

4.2 家族图谱

http://blog.csdn.net/gaowenboms/article/details/8815163
0 0
原创粉丝点击