资讯中心

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

📅 2026/7/21 12:12:53
Android性能优化实战:启动、UI与内存优化技巧
1. Android性能优化面试核心要点解析作为Android开发者性能优化是面试中必问的技术点。我在小米担任资深工程师期间主导过多个大型应用的性能优化工作今天系统梳理一下Android性能优化的核心知识体系。1.1 启动优化实战技巧启动速度直接影响用户体验优化启动时间是性能优化的首要任务。冷启动过程涉及系统创建应用进程、初始化Application和启动Activity三个阶段。冷启动耗时统计的两种实用方法ADB命令方式adb shell am start -W com.example/.MainActivity输出结果中重点关注TotalTime字段表示所有Activity启动耗时。代码埋点方式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 nameLaunchTheme parentTheme.AppCompat.Light.NoActionBar item nameandroid:windowBackgrounddrawable/launch_background/item item nameandroid:windowFullscreentrue/item item nameandroid:windowDrawsSystemBarBackgroundsfalse/item /style1.2 UI渲染优化深度剖析UI卡顿的根源在于16ms内未完成帧绘制。我曾优化过一个电商应用将帧率从45fps提升到稳定的60fps关键优化点过度绘制检测adb shell setprop debug.hwui.overdraw show在开发者选项中开启调试GPU过度绘制理想状态是蓝色1x过度绘制。自定义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(); }布局优化黄金法则减少布局层级不超过10层避免嵌套权重LinearLayout的weight使用ConstraintLayout替代多层嵌套复用布局 标签2. 内存优化实战指南2.1 内存泄漏检测与修复内存泄漏是Android开发的常见问题我总结了一套高效定位方案使用LeakCanary进行检测dependencies { debugImplementation com.squareup.leakcanary:leakcanary-android:2.7 }典型内存泄漏场景静态变量持有Activity引用单例模式不当使用Handler未及时移除消息匿名内部类持有外部类引用使用MAT分析hprof文件hprof-conv input.hprof output.hprof2.2 大图加载优化方案在相册类应用中我实现了以下优化方案图片采样val options BitmapFactory.Options().apply { inJustDecodeBounds true BitmapFactory.decodeResource(resources, R.drawable.large_image, options) inSampleSize calculateInSampleSize(options, reqWidth, reqHeight) inJustDecodeBounds false }图片缓存策略三级缓存架构内存-LRU缓存、磁盘缓存、网络Glide默认实现最优缓存策略使用WebP格式cwebp -q 80 input.png -o output.webp3. 网络与电量优化策略3.1 网络请求优化方案在社交类App中我实现了以下优化请求合并interface ApiService { GET(batch) suspend fun batchRequests( Query(requests) requests: ListString ): ResponseBatchResponse }数据压缩implementation com.squareup.okhttp3:okhttp:4.9.1 // 默认支持gzip弱网优化策略指数退避重试机制数据分页加载优先加载关键数据3.2 电量优化实战经验后台任务调度val workRequest OneTimeWorkRequestBuilderSyncWorker() .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.UNMETERED) .setRequiresCharging(true) .build() ) .build() WorkManager.getInstance(context).enqueue(workRequest)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 资源优化方案资源压缩工具android { buildTypes { release { shrinkResources true minifyEnabled true } } }使用AndResGuard进一步压缩apply plugin: AndResGuard andResGuard { mappingFile null use7zip true useSign true keepRoot false compressFilePattern [ *.png, *.jpg, *.jpeg, *.gif, resources.arsc ] }4.2 代码优化策略移除无用代码android { buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile(proguard-android.txt), proguard-rules.pro } } }动态加载方案功能模块按需下载使用App Bundle分发格式5. 性能优化监控体系5.1 线上监控方案性能埋点设计class PerformanceMonitor { fun trackColdStart(duration: Long) { FirebaseAnalytics.getInstance(context).logEvent( cold_start, Bundle().apply { putLong(duration, duration) } ) } }异常监控implementation com.bugsnag:bugsnag-android:5.9.05.2 性能优化度量标准启动时间冷启动 1.5s热启动 0.5s内存占用普通页面 50MB图片列表页 100MB帧率列表滑动 ≥ 55fps复杂动画 ≥ 50fps在实际项目中我通常会建立性能基线每次发版前进行回归测试确保新功能不会导致性能退化。性能优化不是一蹴而就的工作需要持续监控和迭代优化。