【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )

文章目录

一、自动移除无用资源 ( 不推荐使用 )

自动移除无用资源 :

Android Studio 重构工具中 , 给出了一个自动移除无用资源的工具 , 可以一键移除没有被引用的资源 ;

” 菜单栏 / Refactor / Remove Unused Resources ” 选项 ,

《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

点击后弹出如下对话框 , 选择 ” Refactor ” 按钮 , 即可一键移除无用资源 ;

《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

这种方法只能移除没有直接使用的资源 , 使用 R.xxx.xxx 等方式引用了该资源 , 表示该资源被直接使用了 ;

动态引用的资源不包括在上述情况中 , 如果移除了动态引用资源 , 运行时会崩溃 ;

二、直接引用资源与动态获取资源

1、直接引用资源

直接引用图片示例 : 只要使用 R.drawable.ic_plane , 就算直接使用 ;

  • Java 代码中使用 :
// 动态获取图片
var drawable: Drawable = resources.getDrawable(R.drawable.ic_plane)
  • 布局文件中使用 :
    <ImageView
        android:id="@+id/first_image"
        android:layout_width="100dip"
        android:layout_height="100dip"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0"
        app:srcCompat="@drawable/ic_plane"/>

2、动态获取资源 id

动态获取图片资源示例 : 该获取的资源值就是 R.drawable.ic_plane 值 , 是 int 类型 ;

        // 动态获取图片资源 int
        var drawable2: Int = resources.getIdentifier(
                "ic_plane",
                "drawable",
                "kim.hsl.svg");

三、Lint 检查资源

选择 ” 菜单栏 / Analyze / Run Inspection by Name … ” 选项 ,

《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

执行指定名称的 Lint 检查 , 在弹出的输入框中输入 ” unused resources ” , 执行该 Lint 检查 ,

《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

按下回车键 , 即可执行 Lint 检查 , 弹出如下对话框 ,

《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

选择检查范围 , 只检查 app 模块 , 选择 ” Module ‘SVG.app’ ” 范围 , 点击 OK 按钮 ,

《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

如果没有检查出来 , 在右下角弹出提示 , ” No suspicious code found. 37 files processed in ‘Project ‘SVG’’. ” ;

《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

如果检查出来未使用的资源 , 则显示在 ” Inspection Result ” 面板中 ,

《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

面板右侧可以选择对该未引用的资源处理 , 此处可以对不同的资源进行不同处理 , 如果确定某个资源没有使用过 , 可以是手动删除该资源 ;

《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

对应不确定的资源 , 可以选择全局搜索 , 使用 Ctrl + Shift + F 快捷键 , 或选择 ” 菜单栏 / Edit / Find / Find in Path ” 选项 ,

《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

全局搜索对话框 : 逐个搜索未引用的资源 , 如果确实没有用到的资源 , 直接删除 ;
《【Android 安装包优化】移除无用资源 ( 自动移除无用资源 | 直接引用资源 | 动态获取资源 id | Lint 检查资源 )》

四、参考资料

博客资源 :

    原文作者:韩曙亮
    原文地址: https://blog.csdn.net/han1202012/article/details/116651266
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞