Android在從9.0版本開始修改了啟動(dòng)Activity流程直奋, 跟以往版本的主要區(qū)別在于使用了Transaction。
Android9.0代碼:clientTransaction.addCallback函數(shù)傳入了LaunchActivityItem叔壤。
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
......
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
......
Android9.0以下版本代碼會(huì)向ActivityThread的mH發(fā)送LAUNCH_ACTIVITY消息朽基。
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
......
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global and
// override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, !andResume,
mService.isNextTransitionForward(), profilerInfo);
......
運(yùn)行時(shí)執(zhí)行startActivity后在主線程MessageQueue新增what等于100的Message, 這也是啟動(dòng)Activity是異步的原因榨了; 下圖為Android8.0在startActivity后的消息隊(duì)列截圖袍暴。
Android9.0及后續(xù)版本AndroidQ在新增what等于159即EXECUTE_TRANSACTION的消息些侍, 且obj是ClientTransaction類對象。
因?yàn)锳ndroid消息是個(gè)隊(duì)列政模, 當(dāng)啟動(dòng)Activity時(shí)會(huì)向隊(duì)列尾部新增一條Message岗宣, 如果消息隊(duì)列中有耗時(shí)操作的Message會(huì)導(dǎo)致啟動(dòng)Activity時(shí)機(jī)延后。
安卓Looper會(huì)循環(huán)消費(fèi)MessageQueue中的Message(注意:并不是真正的先入先出淋样,原因是異步消息可以插隊(duì))耗式, 想讓某個(gè)Message提前執(zhí)行可以動(dòng)態(tài)調(diào)整它在隊(duì)列中的位置。
由于Linux的epoll機(jī)制趁猴, 保證了Looper.loop的死循環(huán)獲取消息時(shí)并不會(huì)阻塞主線程刊咳。 當(dāng)前主線程無消息時(shí)進(jìn)入睡眠狀態(tài)并阻塞等待nativePollOnce函數(shù), 有消息時(shí)喚醒nativePollOnce函數(shù)并繼續(xù)向下執(zhí)行儡司。
調(diào)整啟動(dòng)Activity對應(yīng)Message的測試代碼:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
//new Handler().post(new Runnable() {
// @Override public void run() {
// try {
// //模擬主線程MessagQueue中有耗時(shí)的Message娱挨,導(dǎo)致startActivity運(yùn)行時(shí)機(jī)被延后
// Thread.sleep(200);
// } catch (InterruptedException ex) {
// ex.printStackTrace();
// }
// }
//});
Log.d("brycegao", "------------------queue111111111");
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
MessageQueue queue = Looper.myQueue();
changeMsgSequence(queue);
Log.d("brycegao", "------------------queue22222222");
}
});
}
private void changeMsgSequence(MessageQueue queue) {
Class clz = MessageQueue.class;
try {
Field field = clz.getDeclaredField("mMessages");
field.setAccessible(true);
Object obj = field.get(queue);
if (obj != null && obj instanceof Message) {
Message msg = (Message) obj;
Message newHead; //新的mMessage值
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
newHead = alterMsgOrderBeforeAndroidP(msg);
} else {
//Android9及以上版本
newHead = alterMsgOrderAfterAndroidP(msg);
}
field.set(queue, newHead);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private Message getNextMessage(Message msg) {
Class clz = Message.class;
try {
Field field = clz.getDeclaredField("next");
field.setAccessible(true);
Object object = field.get(msg);
if (object != null && object instanceof Message) {
return (Message) object;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* 設(shè)置當(dāng)前Message的下一個(gè)為next
* @param cur
* @param next
*/
private void setNextMessage(Message cur, Message next) {
Class clz = Message.class;
try {
Field field = clz.getDeclaredField("next");
field.setAccessible(true);
field.set(cur, next);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Android9及后續(xù)版本Q移動(dòng)activity啟動(dòng)消息到隊(duì)列頭部
* @param msg, 主線程MessageQueue的mMessages
* @return
*/
private Message alterMsgOrderAfterAndroidP(final Message msg) {
Message head = msg;
Message destMsg = msg;
Message last = msg;
while (head != null) {
if (head.what == 159 && head.getTarget() != null
&& head.getTarget().getClass().toString().contains("android.app.ActivityThread$H")
&& isObjLaunchActivityItem(head.obj)) {
Message nextMsg = getNextMessage(head);
setNextMessage(last, nextMsg);
setNextMessage(head, msg);
return head;
}
last = head;
head = getNextMessage(head);
}
return destMsg;
}
/**
* 判斷Message的obj參數(shù)是否匹配啟動(dòng)Activity
* @param object, Message的obj參數(shù)
* @return
*/
private boolean isObjLaunchActivityItem(Object object) {
if (object == null || !object.getClass().toString()
.contains("android.app.servertransaction.ClientTransaction")) {
return false;
}
try {
Class clz = Class.forName("android.app.servertransaction.ClientTransaction");
Field field = clz.getDeclaredField("mActivityCallbacks");
field.setAccessible(true);
Object data = field.get(object);
if (data != null && data instanceof List) {
List items = (List)data;
if (items.size() > 0) {
Object tranItem = items.get(0);
if (tranItem.getClass().toString().endsWith("LaunchActivityItem")) {
return true;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
private Message alterMsgOrderBeforeAndroidP(final Message msg) {
Message head = msg;
Message destMsg = msg; //新的隊(duì)列頭捕犬,即啟動(dòng)activity消息
Message last = msg;
while (head != null) {
if (head.what == 100 && head.getTarget() != null
&& head.getTarget().getClass().toString().contains("android.app.ActivityThread$H")) {
//判斷是啟動(dòng)activity的消息
//{ when=-1m0s908ms what=100 obj=ActivityRecord{672a27c token=android.os.BinderProxy@4392705 {com.brycegao.findview/com.brycegao.findview.SecondActivity}} target=android.app.ActivityThread$H }
Message nextMsg = getNextMessage(head);
setNextMessage(last, nextMsg);
setNextMessage(head, msg);
return head;
}
last = head;
head = getNextMessage(head);
}
return destMsg;
}
啟動(dòng)優(yōu)化建議:
1跷坝、如果消息隊(duì)里中有耗時(shí)操作的Message, 建議運(yùn)行時(shí)修改啟動(dòng)Activity對應(yīng)Message在隊(duì)列中的位置碉碉, 從而達(dá)到提前啟動(dòng)Activity的目的柴钻。
2、App冷啟動(dòng)或啟動(dòng)Activity時(shí)將一部分必須運(yùn)行在主線程的任務(wù)調(diào)整到IdleHandler中垢粮。