Android启动主要优化点
1、Application初始化的一些动作挪到IntentService;
2、SP存储优化
3、layout优化
4、与UI无关的操作可挪到IdleHandler
5、减少dex,gradle dependencies分析依赖
优化工具
AS + Debug.startMethodTracing("trace")
Debug.stopMethodTracing()
从对应的/mnt/sdcard/Android/data/{packageName}/files/trace.trace找到trace文件;
拖入AS中查看各方法执行时间,如下图:
可清晰的查看到各个方法的执行时间及调用链
初始化移到IntentService
IntentService维持HandlerThread,异步加载;无需自己手动维护线程池
逻辑清晰,避免Application代码混乱
执行完毕自动销毁,无需再手动stop
按需加载,Application同步方法中只加载必须要初始的配置;
IntentService源码:
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
//维护HandlerThread
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
//执行完毕,stop service
stopSelf(msg.arg1);
}
}
SP存储优化
获取Editor 对象和sp apply时加入了同步锁,降低了代码执行效率
@Override
public SharedPreferences getSharedPreferences(File file, int mode) {
……
synchronized (ContextImpl.class) {
…………
if (sp == null) {
sp = new SharedPreferencesImpl(file, mode);
cache.put(file, sp);
return sp;
}
}
……
return sp;
}
public Editor edit() {
// context.getSharedPreferences(..).edit().putString(..).apply()
// ... all without blocking.
synchronized (mLock) {
awaitLoadedLocked();
}
return new EditorImpl();
}
apply方法 同步锁
public void apply() {
final long startTime = System.currentTimeMillis();
………
QueuedWork.addFinisher(awaitCommit);
……
SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable);
notifyListeners(mcr);
}
public static void addFinisher(Runnable finisher) {
synchronized (sLock) {
sFinishers.add(finisher);
}
}
优化前调用方式:
SharedPreferences.Editor editor = context.getSharedPreferences(PREFERENCE_NAME,PreferenceActivity.MODE_PRIVATE).edit();
editor.putString(key, v).apply();
SharedPreferences.Editor editor1 = context.getSharedPreferences(PREFERENCE_NAME,PreferenceActivity.MODE_PRIVATE).edit();
editor1.putString(key, v).apply();
……
SharedPreferences.Editor editor8 = context.getSharedPreferences(PREFERENCE_NAME,PreferenceActivity.MODE_PRIVATE).edit();
editor8.putString(key, v).apply();
优化后,调用方式:
SharedPreferences.Editor editor = context.getSharedPreferences(PREFERENCE_NAME,PreferenceActivity.MODE_PRIVATE).edit()
editor.putString(key, v)
.putString(key, v)
.putString(key, v)
.putString(key, v)
.putString(key, v)
.putString(key, v)
.putString(key, v)
.apply();
修改后执行时间,降低一倍
layout优化
首屏splash采用theme配置;
层级嵌套不宜过深,一般不超过十层
能用padding不用margin,减少onMesure次数
删除无用节点属性
布局复用,使用
标签重用layout; -
提高显示速度,使用
延迟View加载; 需要的时候载入它们,提高 UI 渲染速度,一旦 ViewStub 可见或是被 inflate 了,ViewStub 就不再继续存在View的层级机构中了。取而代之的是被 inflate 的 Layout,其 id 是 ViewStub 上的 android:inflatedId 属性。(ViewStub 的 android:id 属性仅在 ViewStub 可见以前可用)
ViewStub 的一个缺陷是,它目前不支持使用标签的 Layout 。 -
减少层级,使用
标签替换父级布局; 当你要将这个 Layout 包含到另一个 Layout 中时(并且使用了
标签),系统会忽略 标签,直接把两个 Button 放到 Layout 中 的所在位置。 注意使用wrap_content,会增加measure计算成本;
-
节点层级相同的情况下,使用LinearLayout,节点层级不同的情况,使用用RelativeaLayout减少节点层级;
LinearLayout 嵌套使用了 layout_weight 参数的 LinearLayout 的计算量也会变大,因为每个子元素都需要被测量两次。这对需要多次重复 inflate 的 Layout 尤其需要注意,比如嵌套在 ListView 或 GridView 时。
UI无关使用IdleHandler
- 完整的启动时间是要到绘制完成为止,绘制界面最晚能被回调的是在onResume方法,onResume方法是在绘制之前调用(具体参考view绘制流程),在onResume中做一些耗时操作都会影响启动时间
- onResume以及其之前的调用的但非必须的事件(如某些界面View的绘制)挪出来找一个时机(即绘制完成以后)去调用。启动时间自然就缩短了。但是整体做的事并没有明显变化
- IdleHandler在looper里面的message处理完了的时候去调用,也就是onResume调用完了以后的时机。
- IdleHandler源码
/**
* Callback interface for discovering when a thread is going to block
* waiting for more messages.
*/
public static interface IdleHandler {
/**
* Called when the message queue has run out of messages and will now
* wait for more. Return true to keep your idle handler active, false
* to have it removed. This may be called if there are still messages
* pending in the queue, but they are all scheduled to be dispatched
* after the current time.
*/
boolean queueIdle();
}
从注释上看IdleHandler在onResume之后执行,它是怎么做到在onResume之后执行
先看MessageQueue中的调用执行源码:
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
从源码调用方式上看,在消息队列都处理完毕后,再执行IdleHandler消息,activity启动流程中都是通过handler分发消息,Acitivity生命周期呈现页面经历onCreate-->onStart-->onResume,启动流程事件分发源码:
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case LAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
………
case RESUME_ACTIVITY:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
SomeArgs args = (SomeArgs) msg.obj;
handleResumeActivity((IBinder) args.arg1, true, args.argi1 != 0, true,
args.argi3, "RESUME_ACTIVITY");
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
……
}
Object obj = msg.obj;
if (obj instanceof SomeArgs) {
((SomeArgs) obj).recycle();
}
if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
}
启动流程都是通过handler消息,分发执行,Handler消息优化于IdleHandler,等handler消息空闲才执行IdleHandler,所以达到了IdleHandler在onResume之后执行,所以把非必须的事件放在IdleHandler中,达到不影响页面启动时长
减少dex,gradle dependencies分析依赖
dex超过65536需要分多个dex文件,但是5.0以下在Dalvik 模式下(5.0以上ART以上安装时合并dex),运行APP需要合并dex,MultiDex加载多个dex文件耗时,分析依赖,尽量减少dex,避免dex文件过大或者采用插件方式加载
分析依赖方式,执行gradle dependencies
分析结果如下:
+--- project :xxx-android-library
| +--- com.facebook.fresco:fresco:1.3.0 (*)
| +--- com.android.support:multidex:1.0.3
| +--- com.facebook.fresco:drawee:1.3.0 (*)
| +--- com.facebook.fresco:fbcore:1.3.0
| +--- com.facebook.fresco:imagepipeline:1.3.0 (*)
| +--- com.facebook.fresco:imagepipeline-base:1.3.0 (*)
+--- com.xxxx.android:xxx-im:1.2.5
| +--- jp.wasabeef:glide-transformations:3.0.1
| | \--- com.github.bumptech.glide:glide:4.0.0 -> 4.2.0 (*)
| +--- com.alibaba:fastjson:1.1.34.android
| \--- org.json:org.json:2.0
相同类型的库
代码中有一份google gson,对应引用包中有fastJson,
glide-->frecso
两者可去掉其中一个,保留一种;从而减少dex文件