Android性能优化典例(二)

时间:2023-03-08 22:08:54

1、使用 Maven 依赖方案代替使用导入jar包方案

如果项目中需要用到第三方jar包,常用的做法是去网上下载后然后放入libs文件夹,再添加到项目依赖,不过,在Android Studio已经不推荐使用这套做法了,因为如果jar有更新,那么每次都要去下载最新版本然后删除历史依赖再添加新版本的依赖,这样做很繁琐,而在Android Studio中,这个问题使用Maven已经很好的解决了,因为AS中默认的是jcenter*库,而jcenter默认会同步Maven*库,所以我们可以使用Gradle来添加依赖来代替之前的做法,例如:

dependencies {
    compile 'com.android.support:appcompat-v7:22.+'
    compile 'com.squareup.okhttp:okhttp:2.0.+'
    compile 'com.android.support:recyclerview-v7:22.+'
    compile 'com.android.support:cardview-v7:22.2.+'
}

我们这样使用,就指定了一个版本范围,当构建项目时候会自动从Maven库中获取指定范围的最新版本的jar包资源

2、避免深层次的布局结构(最多不要超过5层)

复杂的结构可以考虑用相对布局

3、将相同控件的相同属性抽取出来为一个style

例如:

假如有若干个Button,而Button的样式都是统一的,这时候我们可以将Button的字体大小、颜色、背景色、字体类型等抽取出来放在一个style中,供多个Button复用,如:

<style name="MyButton" parent="Base.Widget.AppCompat.Button">
        <item name="android:textSize">16sp</item>
        <item name="android:textColor">#ffffff</item>
        <item name="android:background">#202020</item>
        <item name="android:typeface">sans</item>
</style>

layout布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        style="@style/MyButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <Button
        style="@style/MyButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/action_settings" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <Button
        style="@style/MyButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name" />
</LinearLayout>

效果:

Android性能优化典例(二)

可以看到这三个Button的样式都一样,复用了相同的style

4、慎用AsyncTask,使用网络请求框架(Volley、OkHttp)代替

关于AsyncTask在异步网络请求方面用的非常多,因为它使用起来比较轻量,但是关于AsyncTask也存在内存泄漏和结果丢失等问题,下面一起来看看:

1、内存泄漏

如果在Activity中使用AsyncTask以匿名内部类的方式请求网络,由于AsyncTask的生命周期可以比Activity的长(因为请求网络数据是比较耗时的),AsyncTask内部类持有Activity的引用的话,如果还在请求网络时就关闭了Activity,那么将导致Activity对象将无法回收,进而产生内存泄漏

2、结果丢失

假如Activity的launchMode是默认或者是标准的,那么当AsyncTask在请求网络数据时把屏幕旋转了,那么将会重新创建一个新的Activity,又因为还在运行的AsyncTask持有之前Activity的引用,那么将导致onPostExecute()方法不起任何作用,请求获得的数据不能加载到新的Activity上,而且也将导致内存泄漏

3、串行和并行多版本不一致

AsyncTask在1.6之前为串行,在1.6-2.3为并行,在3.0之后又改为串行,在3.0之后虽然可以通过代码来改变默认的串行为并行,但是又是一个繁琐的操作

相关文章