apk优化的几种方式:

1.svg图片的使用

强调点:在安卓5.0 以下是不支持这种方式的,需要做以下兼容:

在app的build.gradle目录下的defaultConfig中添加

1
2
//将svg图片生成指定的png图片
vectorDrawables.generatedDensities('xhdpi','xxhdpi','xxxhdpi')

或者添加

1
2
//使用support-v7兼容
vectorDrawables.useSupportLibrary = true

2.使用tint着色器来给png图片增加颜色

1
2
3
4
5
6
7
8
9
10
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/test"/>

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/test"
android:tint="@android:color/holo_green_dark" />

也可以增加类似的点击效果:

1
2
3
4
5
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/test"
android:tint="@color/color" />

color的selector:

1
2
3
4
5
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@android:color/holo_green_dark"/>
<item android:color="@android:color/transparent" />

</selector>

3.打包时只保留中文语言:

在app的build.gradle目录下的defaultConfig中添加

1
resConfigs('zh-rCN','ko')//中文和韩语

4.打包时将只打包需要的so库:

在app的build.gradle目录下的defaultConfig中添加

1
2
3
ndk{
abiFilters('armeabi','armeabi-v7a')//这两种是常见的手机架构
}

5.删除无用的资源(Lint工具检查)

Analyze->Run Inspection by name->搜索unused resource 删除

6.混淆的使用:

1
2
3
4
5
release {
//开启代码混淆
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}

7.资源压缩:

1
2
3
4
5
6
7
release {
//开启代码混淆
minifyEnabled true
//资源压缩
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}

此外还可以通过指定的方式不压缩某些资源,在res目录下新建raw文件夹,新建keep.xml文件:

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
tools:discard="@color/color"
tools:keep="@layout/activity_main" //指定不压缩的资源
tools:shrinkMode="strict">

</resources>

8.androidStudio中webp插件的使用:

右键png或jepg图片convert to webp可以压缩需要的图片

9.资源混淆、压缩对齐(待详解~~~)

本文地址: http://www.yppcat.top/2019/04/02/apk优化方式/