Android性能优化实战:启动、UI与内存优化技巧

1. Android性能优化面试核心要点解析

作为Android开发者,性能优化是面试中必问的技术点。我在小米担任资深工程师期间,主导过多个大型应用的性能优化工作,今天系统梳理一下Android性能优化的核心知识体系。

1.1 启动优化实战技巧

启动速度直接影响用户体验,优化启动时间是性能优化的首要任务。冷启动过程涉及系统创建应用进程、初始化Application和启动Activity三个阶段。

冷启动耗时统计的两种实用方法:

  1. ADB命令方式:
adb shell am start -W com.example/.MainActivity

输出结果中重点关注TotalTime字段,表示所有Activity启动耗时。

  1. 代码埋点方式:
class LaunchTracker { companion object { private var startTime: Long = 0 fun startRecording() { startTime = System.currentTimeMillis() } fun endRecording(tag: String = "") { val cost = System.currentTimeMillis() - startTime Log.d("LaunchTime", "$tag cost: ${cost}ms") } } } // 在Application中 override fun attachBaseContext(base: Context) { LaunchTracker.startRecording() super.attachBaseContext(base) } // 在Activity中 override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) if(hasFocus) LaunchTracker.endRecording("onWindowFocusChanged") }

启动主题优化技巧:

<style name="LaunchTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowBackground">@drawable/launch_background</item> <item name="android:windowFullscreen">true</item> <item name="android:windowDrawsSystemBarBackgrounds">false</item> </style>

1.2 UI渲染优化深度剖析

UI卡顿的根源在于16ms内未完成帧绘制。我曾优化过一个电商应用,将帧率从45fps提升到稳定的60fps,关键优化点:

  1. 过度绘制检测:
adb shell setprop debug.hwui.overdraw show

在开发者选项中开启"调试GPU过度绘制",理想状态是蓝色(1x过度绘制)。

  1. 自定义View优化示例:
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 使用clipRect避免不必要的绘制 canvas.save(); canvas.clipRect(left, top, right, bottom); canvas.drawBitmap(bitmap, x, y, paint); canvas.restore(); }
  1. 布局优化黄金法则:
  • 减少布局层级(不超过10层)
  • 避免嵌套权重(LinearLayout的weight)
  • 使用ConstraintLayout替代多层嵌套
  • 复用布局( 标签)

2. 内存优化实战指南

2.1 内存泄漏检测与修复

内存泄漏是Android开发的常见问题,我总结了一套高效定位方案:

  1. 使用LeakCanary进行检测:
dependencies { debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7' }
  1. 典型内存泄漏场景:
  • 静态变量持有Activity引用
  • 单例模式不当使用
  • Handler未及时移除消息
  • 匿名内部类持有外部类引用
  1. 使用MAT分析hprof文件:
hprof-conv input.hprof output.hprof

2.2 大图加载优化方案

在相册类应用中,我实现了以下优化方案:

  1. 图片采样:
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true BitmapFactory.decodeResource(resources, R.drawable.large_image, options) inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight) inJustDecodeBounds = false }
  1. 图片缓存策略:
  • 三级缓存架构(内存-LRU缓存、磁盘缓存、网络)
  • Glide默认实现最优缓存策略
  1. 使用WebP格式:
cwebp -q 80 input.png -o output.webp

3. 网络与电量优化策略

3.1 网络请求优化方案

在社交类App中,我实现了以下优化:

  1. 请求合并:
interface ApiService { @GET("batch") suspend fun batchRequests( @Query("requests") requests: List<String> ): Response<BatchResponse> }
  1. 数据压缩:
implementation 'com.squareup.okhttp3:okhttp:4.9.1' // 默认支持gzip
  1. 弱网优化策略:
  • 指数退避重试机制
  • 数据分页加载
  • 优先加载关键数据

3.2 电量优化实战经验

  1. 后台任务调度:
val workRequest = OneTimeWorkRequestBuilder<SyncWorker>() .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.UNMETERED) .setRequiresCharging(true) .build() ) .build() WorkManager.getInstance(context).enqueue(workRequest)
  1. WakeLock使用规范:
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE); PowerManager.WakeLock wakeLock = pm.newWakeLock( PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag"); wakeLock.acquire(10*60*1000L /*10分钟*/); // ...执行工作... wakeLock.release();

4. 安装包体积优化技巧

4.1 资源优化方案

  1. 资源压缩工具:
android { buildTypes { release { shrinkResources true minifyEnabled true } } }
  1. 使用AndResGuard进一步压缩:
apply plugin: 'AndResGuard' andResGuard { mappingFile = null use7zip = true useSign = true keepRoot = false compressFilePattern = [ "*.png", "*.jpg", "*.jpeg", "*.gif", "resources.arsc" ] }

4.2 代码优化策略

  1. 移除无用代码:
android { buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } }
  1. 动态加载方案:
  • 功能模块按需下载
  • 使用App Bundle分发格式

5. 性能优化监控体系

5.1 线上监控方案

  1. 性能埋点设计:
class PerformanceMonitor { fun trackColdStart(duration: Long) { FirebaseAnalytics.getInstance(context).logEvent( "cold_start", Bundle().apply { putLong("duration", duration) } ) } }
  1. 异常监控:
implementation 'com.bugsnag:bugsnag-android:5.9.0'

5.2 性能优化度量标准

  1. 启动时间:
  • 冷启动 < 1.5s
  • 热启动 < 0.5s
  1. 内存占用:
  • 普通页面 < 50MB
  • 图片列表页 < 100MB
  1. 帧率:
  • 列表滑动 ≥ 55fps
  • 复杂动画 ≥ 50fps

在实际项目中,我通常会建立性能基线,每次发版前进行回归测试,确保新功能不会导致性能退化。性能优化不是一蹴而就的工作,需要持续监控和迭代优化。