Android12 Acivity启动流程

本文基于Android12 master分支源码分析
调用链在更新安卓版本后就不一样了,所以没有记住它的必要。所以这篇文章一方面作为记录,另一方面也讲怎样在aosp中找到调用链。
如果你想跟着自己手动在AOSP中查调用链,需要fq访问codesearch网站
我们首先从startActivty开始,在AndroidStudio中不断地向上查调用链,这个过程在AndroidStudio中的源码就能查到,简单省略,最终能看到在Instrumentation.java中地这里,执行了启动方法.

public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
            ...
            int result = ActivityTaskManager.getService().startActivity(whoThread,
                    who.getOpPackageName(), who.getAttributionTag(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                    target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
            }

调用到ServiceManager.getService方法获取一个IActivityTaskManager 对象执行startActivity方法。
旧版本Android中这个方法获取到的是ActivityManagerService,现已经重构为ActivityTaskManager。

interface IActivityTaskManager {//包含startActivity方法
    int startActivity(in IApplicationThread caller, in String callingPackage,
            in String callingFeatureId, in Intent intent, in String resolvedType,
            in IBinder resultTo, in String resultWho, int requestCode,
            int flags, in ProfilerInfo profilerInfo, in Bundle options);}
 ------------------------------------------------
 public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }
    
   private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
            new Singleton<IActivityTaskManager>() {
                @Override
                protected IActivityTaskManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                    return IActivityTaskManager.Stub.asInterface(b);
                }
            };

找到实现了IActivityTaskManager接口的
ActivityTaskManagerService.java

public final int startActivity(IApplicationThread caller, String callingPackage,
          String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
          String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
          Bundle bOptions) {
      return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
              resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
              UserHandle.getCallingUserId());
  }

最终定位到

public class ClientTransaction implements Parcelable, ObjectPoolItem {
/** Target client. */
  private IApplicationThread mClient;
   public void schedule() throws RemoteException {
      mClient.scheduleTransaction(this);
  }
  }

检索ApplicationThread类,但是现在版本的AOSP已经删除了。所以们从client的赋值链去查找,能够定位到

public final class ActivityThread extends ClientTransactionHandler
        implements ActivityThreadInternal {
 private class ApplicationThread extends IApplicationThread.Stub {..
 @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);//这里的transation就是上文的client
        }
}}

ApplicationThread 作为内部类实现在类ActivityThread中,又调用回ActivityThread。接下来的调用链为ActivityStart.execute()-executeRequest()–startActivityUnchecked()-startActivityInner()-mRootWindowContainer.resumeFocusedTasksTopActivities-
Task.resumeTopActivityInnerLocked
resumed[0] = topFragment.resumeTopActivity(prev, options, deferPause);//Task.java line 5038
mTaskSupervisor.startSpecificActivity(next, true, true); // TaskFragment.java// line 1351

ActivityTaskSupervisor	
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);

        boolean knownToBeDead = false;
        if (wpc != null && wpc.hasThread()) {
            try {
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
            knownToBeDead = true;
        }

        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();

        final boolean isTop = andResume && r.isTopRunningActivity();
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }
     boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
            ...
		mService.getLifecycleManager().scheduleTransaction(clientTransaction); //line 880}

通过wpc来判断,当进程未启动的时候需要调用mService.startProcessAsync启动新进程。
mService.getLifecycleManager().scheduleTransaction(clientTransaction); //line 880

public class ClientTransaction implements Parcelable, ObjectPoolItem {
private IApplicationThread mClient;
  public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }}

调用到我们熟悉的IApplicationThread,ActivityThread的内部类实现

public final class ActivityThread extends ClientTransactionHandler
        implements ActivityThreadInternal {
         void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
     private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) }
        Message msg = Message.obtain();
        msg.what = what;
        SomeArgs args = SomeArgs.obtain();
        args.arg1 = obj;
        args.argi1 = arg1;
        args.argi2 = arg2;
        args.argi3 = seq;
        msg.obj = args;
        mH.sendMessage(msg);
    }
      private class ApplicationThread extends IApplicationThread.Stub {
          @Override
     		 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
           		 ActivityThread.this.scheduleTransaction(transaction);
      		 }
         }
 ----------------------------
	public void handleMessage(Message msg) {
	...
     case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);//从这里向后查调用链
                    if (isSystem()) {
                        // Client transactions inside system process are recycled on the client side
                        // instead of ClientLifecycleManager to avoid being cleared before this
                        // message is handled.
                        transaction.recycle();
                    }
                    // TODO(lifecycler): Recycle locally scheduled transactions.
                    break;
                    ..
    }
} 

TransactionExecutor.execute()-
executeCallbacks()-
item.execute(mTransactionHandler, token, mPendingActions);
找到item实现execute的子类有
在这里插入图片描述
我们直接看LaunchActivityItem

public class LaunchActivityItem extends ClientTransactionItem {
public void execute(ClientTransactionHandler client, IBinder token,
           PendingTransactionActions pendingActions) {
       Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
       ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
               mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
               mPendingResults, mPendingNewIntents, mActivityOptions, mIsForward, mProfilerInfo,
               client, mAssistToken, mFixedRotationAdjustments, mShareableActivityToken,
               mLaunchedFromBubble);
       client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
       Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
   }
   }

看这里 client.handleLaunchActivity,全局搜索ClientTransactionHandler ,就能发现ActivityThread继承了这个抽象类,ActivityThread.java

  public final class ActivityThread extends ClientTransactionHandler
       implements ActivityThreadInternal {
    @Override
   public Activity handleLaunchActivity(ActivityClientRecord r,
           PendingTransactionActions pendingActions, Intent customIntent) {
final Activity a = performLaunchActivity(r, customIntent);}
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
       try {
           java.lang.ClassLoader cl = appContext.getClassLoader();
           activity = mInstrumentation.newActivity(
                   cl, component.getClassName(), r.intent);
           StrictMode.incrementExpectedActivityCount(activity.getClass());
           r.intent.setExtrasClassLoader(cl);
           r.intent.prepareToEnterProcess(isProtectedComponent(r.activityInfo),
                   appContext.getAttributionSource());
           if (r.state != null) {
               r.state.setClassLoader(cl);
           }
       } catch (Exception e) {
           if (!mInstrumentation.onException(activity, e)) {
               throw new RuntimeException(
                   "Unable to instantiate activity " + component
                   + ": " + e.toString(), e);
           }
       }

   	 ...
       return activity;
   }

在performLaunchActivity方法中反射创建activity,到这里activity的启动流程就结束了。
android12

Android 中,可以使用 bindService() 方法将 Service 和 Activity 绑定在一起。绑定后,Activity 可以与 Service 进行通信。 以下是一些简单的步骤: 1. 在 Activity 中创建 ServiceConnection 对象,用于在 Service 与 Activity 之间建立连接。 ``` private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { // Service 与 Activity 建立连接时执行的代码 } @Override public void onServiceDisconnected(ComponentName componentName) { // Service 与 Activity 断开连接时执行的代码 } }; ``` 2. 在 Activity 中调用 bindService() 方法,传入 Intent 对象和 ServiceConnection 对象。 ``` Intent intent = new Intent(this, MyService.class); bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); ``` 3. 在 Service 中实现 onBind() 方法,返回一个 IBinder 对象。 ``` public class MyService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } } ``` 4. 在 onBind() 方法中返回的 IBinder 对象中实现 Service 与 Activity 之间的通信逻辑。 ``` public class MyBinder extends Binder { public MyService getService() { return MyService.this; } public void doSomething() { // 执行一些操作 } } public class MyService extends Service { private MyBinder mBinder = new MyBinder(); @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } } ``` 通过这些步骤,就可以将 Service 和 Activity 绑定在一起,并进行通信了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值