Android启动优化实践

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中查看各方法执行时间,如下图:


20191113175625.jpg

可清晰的查看到各个方法的执行时间及调用链

初始化移到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次数

  • 删除无用节点属性

  • 布局复用,使用<include>标签重用layout;

  • 提高显示速度,使用<ViewStub>延迟View加载;

    需要的时候载入它们,提高 UI 渲染速度,一旦 ViewStub 可见或是被 inflate 了,ViewStub 就不再继续存在View的层级机构中了。取而代之的是被 inflate 的 Layout,其 id 是 ViewStub 上的 android:inflatedId 属性。(ViewStub 的 android:id 属性仅在 ViewStub 可见以前可用)
    ViewStub 的一个缺陷是,它目前不支持使用 <merge/> 标签的 Layout 。

  • 减少层级,使用<merge>标签替换父级布局;

    当你要将这个 Layout 包含到另一个 Layout 中时(并且使用了 <include/> 标签),系统会忽略 <merge> 标签,直接把两个 Button 放到 Layout 中 <include> 的所在位置。

  • 注意使用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.
          <!--没有可以即刻执行的Message,查看是否存在需要处理的IdleHandler,如果不存在,则返回,阻塞等待,如果存在则执行IdleHandler-->
                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文件

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容