Android ActivityThread

一、介绍

ActivityThread类是Android系统中负责管理应用程序中所有Activity生命周期的核心类,它负责创建新的进程和线程来运行应用程序,并负责管理应用程序中各个组件对象的生命周期和交互。

ActivityThread本质上是一个线程,用于启动应用程序以及进程中进行应用程序的主循环,它可以理解为应用程序的主线程。在ActivityThread内部会创建一个Application对象,以及多个Activity对象,然后将这些Activity加到调度队列中,根据生命周期状态来挂起或恢复。

在Android系统中,一个应用程序可以没有Activity,但必须要有ActivityThread,这是因为ActivityThread类中封装了程序的入口点(main函数),Android系统要启动一个应用程序时,会先加载应用程序的代码和资源文件,然后调用ActivityThread类的main函数,以创建ActivityThread实例对象,并启动主线程,最后ActivityThread实例对象负责启动和管理程序中的各个组件对象,包括Activity、Service和BroadcastReceiver等。

以下是ActivitThread的一些主要作用:

1、加载应用程序到内存:ActivityThread会在main()方法中被调用,进而启动应用程序并实例化Application、Activity等对象,并将其加入到允许环境中。

2、管理Activity生命周期:ActivityThread负责检测并执行每个Activity的生命周期方法,例如onCreate()、onStart()、onPause等,并根据生命周期状态,控制Activity的创建、启动、停止销毁等过程。

3、管理消息循环:ActivityThread还创建了一个消息循环机制,用于处理Activity中的消息和事件,并根据优先级来处理和分发消息。创建的消息包括用户界面中的用户事件、Intent和Broadcast请求等。

4、管理窗口和视图:ActiviytThread还负责管理窗口的视图的创建和显示,以及与窗口和视图相关的事件处理。

二、ActivityThread相关类和接口

IApplicationThread

用于与应用程序通信的系统专用 API。

IApplicationThread文件路径:

frameworks/base/core/java/android/app/IApplicationThread.aidl

IApplicationThread定义:

oneway interface IApplicationThread {}

ActivityThreadInternal

ActivityThread 内部接口。

ActivityThreadInternal文件路径:

frameworks/base/core/java/android/app/ActivityThreadInternal.java

ActivityThreadInternal定义:

interface ActivityThreadInternal {}

ClientTransactionHandler

ClientTransactionHandler是一个用于处理客户端事务的类。它负责处理与Activity生命周期相关的事务,例如启动、暂停、恢复和停止Activity等操作。该类的主要作用是将客户端事务转发给ActivityThread进行处理。

ClientTransactionHandler文件路径:

frameworks/base/core/java/android/app/ClientTransactionHandler.java

ClientTransactionHandler定义:

public abstract class ClientTransactionHandler {}

ClientTransactionHandler方法:

void scheduleTransaction(ClientTransaction transaction) :Prepare and schedule transaction for execution.
public void executeTransaction(ClientTransaction transaction):Execute transaction immediately without scheduling it.
abstract TransactionExecutor getTransactionExecutor():Get the {@link TransactionExecutor} that will be performing lifecycle transitions and callbacks for activities.
public abstract Activity getActivity(IBinder token):Get activity instance for the token.
public abstract void updatePendingConfiguration(Configuration config):Set pending config in case it will be updated by other transaction item.
public abstract void updateProcessState(int processState, boolean fromIpc):Set current process state. 
public abstract void countLaunchingActivities(int num):Count how many activities are launching.
public abstract Map<IBinder, ClientTransactionItem> getActivitiesToBeDestroyed():Get activity and its corresponding transaction item which are going to destroy.
public abstract void handleDestroyActivity(@NonNull ActivityClientRecord r, boolean finishing, int configChanges, boolean getNonConfigInstance, String reason):Destroy the activity.
public abstract void handlePauseActivity(@NonNull ActivityClientRecord r, boolean finished, boolean userLeaving, int configChanges, PendingTransactionActions pendingActions, String reason):Pause the activity.
public abstract void handleResumeActivity(@NonNull ActivityClientRecord r, boolean finalStateRequest, boolean isForward, String reason):Resume the activity.
public abstract void handleTopResumedActivityChanged(@NonNull ActivityClientRecord r, boolean isTopResumedActivity, String reason):Notify the activity about top resumed state change.
public abstract void handleStopActivity(@NonNull ActivityClientRecord r, int configChanges, PendingTransactionActions pendingActions, boolean finalStateRequest, String reason):Stop the activity.
public abstract void reportStop(PendingTransactionActions pendingActions):Report that activity was stopped to server. 
public abstract void performRestartActivity(@NonNull ActivityClientRecord r, boolean start):Restart the activity after it was stopped. 
public abstract void updatePendingActivityConfiguration(@NonNull IBinder token, Configuration overrideConfig):Set pending activity configuration in case it will be updated by other transaction item.
public abstract void handleActivityConfigurationChanged(@NonNull ActivityClientRecord r, Configuration overrideConfig, int displayId):Deliver activity (override) configuration change.
public abstract void handleSendResult(@NonNull ActivityClientRecord r, List<ResultInfo> results, String reason):Deliver result from another activity.
public abstract void handleNewIntent(@NonNull ActivityClientRecord r, List<ReferrerIntent> intents):Deliver new intent.
public abstract void handlePictureInPictureRequested(@NonNull ActivityClientRecord r):Request that an activity enter picture-in-picture.
public abstract void handlePictureInPictureStateChanged(@NonNull ActivityClientRecord r, PictureInPictureUiState pipState):Signal to an activity (that is currently in PiP) of PiP state changes.
public abstract boolean isHandleSplashScreenExit(@NonNull IBinder token):Whether the activity want to handle splash screen exit animation
public abstract void handleAttachSplashScreenView(@NonNull ActivityClientRecord r, @NonNull SplashScreenViewParcelable parcelable, @NonNull SurfaceControl startingWindowLeash):Attach a splash screen window view to the top of the activity
public abstract Activity handleLaunchActivity(@NonNull ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent):Perform activity launch.
public abstract void handleStartActivity(@NonNull ActivityClientRecord r, PendingTransactionActions pendingActions, ActivityOptions activityOptions):Perform activity start.
public abstract LoadedApk getPackageInfoNoCheck(ApplicationInfo ai, CompatibilityInfo compatInfo):Get package info.
public abstract void handleConfigurationChanged(Configuration config):Deliver app configuration change notification.
public abstract ActivityClientRecord getActivityClient(IBinder token):Get {@link android.app.ActivityThread.ActivityClientRecord} instance that corresponds to the provided token.
public abstract ActivityClientRecord prepareRelaunchActivity(IBinder token, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, int configChanges, MergedConfiguration config, boolean preserveWindow):Prepare activity relaunch to update internal bookkeeping.
public abstract void handleRelaunchActivity(@NonNull ActivityClientRecord r, PendingTransactionActions pendingActions):Perform activity relaunch.
public abstract void reportRelaunch(@NonNull ActivityClientRecord r, PendingTransactionActions pendingActions):Report that relaunch request was handled.

ActivityThread

ActivityThread类是Android系统中负责管理应用程序中所有Activity生命周期的核心类,它负责创建新的进程和线程来运行应用程序,并负责管理应用程序中各个组件对象的生命周期和交互。

ActivityThread文件路径:

frameworks/base/core/java/android/app/ActivityThread.java

ActivityThread定义:

public final class ActivityThread extends ClientTransactionHandler implements ActivityThreadInternal {
    public static final class ActivityClientRecord {}
    final class ProviderClientRecord {}
    static final class ReceiverData extends BroadcastReceiver.PendingResult {}
    static final class CreateBackupAgentData {}
    final class ProviderClientRecord {}
    static final class AppBindData {}
    static final class Profiler {}
    static final class DumpComponentInfo {}
    static final class ContextCleanupInfo {}
    static final class DumpHeapData {}
    static final class DumpResourcesData {}
    static final class UpdateCompatibilityData {}
    static final class RequestAssistContextExtras {}
    private class ApplicationThread extends IApplicationThread.Stub {
        private static final class SafeCancellationTransport extends ICancellationSignal.Stub {}
        class H extends Handler {}
    }
    private class Idler implements MessageQueue.IdleHandler {}
    private static final class ProviderRefCount {}
    private static class AndroidOs extends ForwardingOs {}
}

ActivityThread方法:

public static ActivityThread currentActivityThread() :这个方法返回当前线程的ActivityThread对象,在应用程序中可以通过这个方法获取自己的ActivityThread对象以便进行一些操作。
public void handleStartActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, ActivityOptions activityOptions) :启动新的Activity。
public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) :创建并启动新的Activity。
public void handleResumeActivity(ActivityClientRecord r, boolean finalStateRequest, boolean isForward, String reason):负责处理恢复Activity运行的请求,当一个Activity从暂停状态恢复时,ActivityManagerService会通过Binder远程调用的方式将恢复请求发送给ActivityThread,ActivityThread会根据请求中传递的参数来恢复对应的Activity。
public void handleTopResumedActivityChanged(ActivityClientRecord r, boolean onTop, String reason) :负责处理当顶层Activity发送改变时的请求。
public void handlePauseActivity(ActivityClientRecord r, boolean finished, boolean userLeaving, int configChanges, PendingTransactionActions pendingActions, String reason) :负责处理Activity进入暂停状态的请求。
public void handleStopActivity(ActivityClientRecord r, int configChanges, PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) :负责处理Activity置为停止状态的请求。
public void reportStop(PendingTransactionActions pendingActions):负责通知。ActivityManagerService某个Activity已经停止并已经释放相应资源。
public void performRestartActivity(ActivityClientRecord r, boolean start) :负责处理某个Activity从停止状态重新启动的操作。
public void handleSendResult(ActivityClientRecord r, List<ResultInfo> results, String reason):负责处理Activity向其父Activity返回结果的请求。
public void handleDestroyActivity(ActivityClientRecord r, boolean finishing, int configChanges, boolean getNonConfigInstance, String reason):处理某个Activity被销毁的请求
public ActivityClientRecord prepareRelaunchActivity(IBinder token, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, int configChanges, MergedConfiguration config, boolean preserveWindow) :为即将重启的Activity准备数据和状态。
public void handleRelaunchActivity(ActivityClientRecord tmp, PendingTransactionActions pendingActions):处理某个Activity重启(relaunch)的请求。
public void reportRelaunch(ActivityClientRecord r, PendingTransactionActions pendingActions):负责通知ActivityManagerService某个Activity的relaunch信息。
public void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) :处理系统中某个应用的信息发送了变更的请求。
public void handleActivityConfigurationChanged(ActivityClientRecord r, @NonNull Configuration overrideConfig, int displayId) :处理某个Activity的配置发生变更的情况。
public final IContentProvider acquireProvider(Context c, String auth, int userId, boolean stable) :获取指定ContentProvider的访问权限。
public final IContentProvider acquireExistingProvider(Context c, String auth, int userId, boolean stable) :获取指定ContentProvider的访问权限。
public final boolean releaseProvider(IContentProvider provider, boolean stable) :释放指定ContentProvider的访问权限。
public static ActivityThread systemMain() :由于标识应用程序启动的类型的标志位,用于告诉ActivityThread只启动应用程序的核心服务。
public static void main(String[] args) :这时ActivityThread类的入口点,用于启动应用程序的主线程,以及创建和管理应用程序中的各个组件对象。
final void finishInstrumentation(int resultCode, Bundle results):结束指定的。Instrumentation,释放相关资源。
private ContentProviderHolder installProvider(Context context, ContentProviderHolder holder, ProviderInfo info, boolean noisy, boolean noReleaseNeeded, boolean stable):注册一个ContentProvider。
 private void attach(boolean system, long startSeq) :这个方法用于将应用程序和ActivityThread关联起来,它通过传入应用程序上下文、应用程序的LoadedApk对象等参数,来初始化ActivityThread并关联应用程序。
public void scheduleTransaction(ClientTransaction transaction) :准备和安排要执行的事务。

LoadedApk

LoadedApk是Android中的一个类,用于表示已加载的应用程序包。每个应用程序在Android中都有一个LoadedApk对象,它包含了应用程序的所有信息,如包名、类加载器、资源等。LoadedApk类的主要作用是管理应用程序的资源和类加载器,并提供了一些方法来获取应用程序的信息。

LoadedApk文件路径:

frameworks/base/core/java/android/app/LoadedApk.java

LoadedApk定义:

public final class LoadedApk {
    private class SplitDependencyLoaderImpl extends     SplitDependencyLoader<NameNotFoundException> {}
    private static class WarningContextClassLoader extends ClassLoader {}
    static final class ReceiverDispatcher {
        final static class InnerReceiver extends IIntentReceiver.Stub {}
        final class Args extends BroadcastReceiver.PendingResult {}
    }
    static final class ServiceDispatcher {
        private static class ConnectionInfo {}
        private static class InnerConnection extends IServiceConnection.Stub {}
        private final class RunConnection implements Runnable {}
        private final class DeathMonitor implements IBinder.DeathRecipient}
    }
}

AppComponentFactory

Interface used to control the instantiation of manifest elements.

用于控制清单元素实例化的接口。

AppComponentFactory文件路径:

frameworks/base/core/java/android/app/AppComponentFactory.java

AppComponentFactory定义:

public class AppComponentFactory {}

ClientTransaction

A container that holds a sequence of messages, which may be sent to a client.

一个容器,用于保存一系列消息,这些消息可以发送到客户端。

ClientTransaction文件路径:

frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java

ClientTransaction定义:

public class ClientTransaction implements Parcelable, ObjectPoolItem {}

TransactionExecutor

Class that manages transaction execution in the correct order.

按正确顺序管理事务执行的类。

TransactionExecutor文件路径:

frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java

TransactionExecutor定义:

public class TransactionExecutor {}

TransactionExecutorHelper

{@link TransactionExecutor} 的帮助程序类,其中包含用于生命周期路径解析的实用程序。

TransactionExecutorHelper文件路径:

frameworks/base/core/java/android/app/servertransaction/TransactionExecutorHelper.java

TransactionExecutorHelper定义:

public class TransactionExecutorHelper {}

PendingTransactionActions

Container that has data pending to be used at later stages of {@link android.app.servertransaction.ClientTransaction}.

具有待处理数据的容器,可在 {@link android.app.servertransaction.ClientTransaction} 的后续阶段使用。

PendingTransactionActions文件路径:

frameworks/base/core/java/android/app/servertransaction/PendingTransactionActions.java

PendingTransactionActions定义:

public class PendingTransactionActions {
    public static class StopInfo implements Runnable {}
}

三、ActivityThread相关流程分析

ActivityThread main流程分析

Android13 ActivityThread main流程分析-CSDN博客

ActivityThread attach流程分析

Android13 ActivityThread attach流程分析-CSDN博客

ActivityThread handleBindApplication流程分析

Android13 ActivityThread handleBindApplication流程分析-CSDN博客

ActivityThread handleLaunchActivity流程分析

Android13 ActivityThread handleLaunchActivity流程分析-CSDN博客

ActivityThread handleRelaunchActivity流程分析

ActivityThread handleStartActivity流程分析

Android13 ActivityThread handleStartActivity流程分析-CSDN博客

ActivityThread handlePauseActivity流程分析

Android13 ActivityThread handlePauseActivity流程分析-CSDN博客

ActivityThread handleResumeActivity流程分析

Android13 ActivityThread handleResumeActivity流程分析-CSDN博客

ActivityThread handleStopActivity流程分析

Android13 ActivityThread handleStopActivity流程分析-CSDN博客

ActivityThread handleDestroyActivity流程分析

Android13 ActivityThread handleDestroyActivity流程分析-CSDN博客

ActivityThread handleCreateService流程分析

Android13 ActivityThread handleCreateService流程分析-CSDN博客

ActivityThread handleServiceArgs流程分析

Android13 ActivityThread handleServiceArgs流程分析-CSDN博客

ActivityThread handleBindService流程分析

Android13 ActivityThread handleBindService流程分析-CSDN博客

ActivityThread handleUnbindService流程分析

Android13 ActivityThread handleUnbindService流程分析-CSDN博客

ActivityThread handleStopService流程分析

Android13 ActivityThread handleStopService流程分析-CSDN博客

  • 20
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值