Improve Android App Performance

本文详细介绍了改善Android应用性能的10种关键策略,包括内存泄漏管理、使用UI线程、利用现有库、优化大型JSON解析、避免系统滥用、了解废弃API、自定义手套版本、架构设计和理解APK细节。这些方法旨在提高应用的流畅性和稳定性。

According to Droidcon NYC 2015 : 10 ways to improve your Android app performance
Boris Farber | YouTube | SlideShare

Attention: If you have a small app forget this article.

1.Memory Leaks

  • a.Listener’s Leak
public class LeakActivity extends Activity{
//...
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    NastyManager.getInstance().addListener(this);
  }
}
  • a.Fix Listener’s Leak
@Override
public void OnDestroy(){
  super.onDestroy();
  NastyManager.getInstance().removeListener(this);
}
  • b.Activity Leaks
public class MainActivity extends Activity {
  //...
  Handler handler;
  @Override
  protected void onCreate(Bundle savedInstacneState) {
    super.onCreate(savedInstanceState);
    //...
    handler = new Handler() {
      @Override
      public void handleMessage(Message msg){
        //...
      }
    }
    //What happens if handler.postDelayed(...)
  }
}
  • b.Fix Activity’s Leaks
private static class FixedHandler extends Handler {
  private final WeakReference<MainActivity> mActivity;
  //...
  public FixedHandler(MainActivity activity) {
    mActivity = new WeakReference<MainActivity>(activity);
    //...
  }
  @Override
  public void handlerMessage(Message msg) {}
  //...
}
  • c Static References

    • Activities/Fragments etc - they have a life cycle
    • Activity will not be GC-ed
    • Static references - become dangling “pointers”
    • m_staticActivity = staticFragment.getActivity();
  • c.Fix Prefer static to non static inner classes

    • Non static Handler –> Activity leak
    • Both classes have a different lifetime
  • d.what you can do Activity Leaks -1

    • Remove away static references
    • Use event bus
    • Unregister listeners
    • Prefer static inner classes to non static ones
  • d.what you can do Activity Leaks -2
    • Do code reviews
    • Understand your app structure
    • Use tools
    • Print logs on callbacks

2.Use UI Thread only for UI

Symptons
  • Scrolling
Not on UI thread
  • Images
  • Networking
  • JSON (next bullet) (Use libraries)
  • Database access (Use Loaders)

3.Use libraries

Use libraries
  • Already solve the problem
  • Requires specialization (easy to make mistake)
    • Threading
    • Memory
    • Networking
    • Images
  • Don’t lose focus
  • Develop your solution for a good reason
  • Common Async Http
    • Volley
    • OkHttp
    • Retrofit
  • Image Loading
    • Glide
    • Picasso
    • Fresco
    • UIL
  • Pick 3rd party lib checklist
    • Solves your problem
    • Plays nicely with your current dependencies
    • Dex method count
    • Dependencies
    • Maintenance
    • Runtime permissions

4.Large JSONs

Large json
  • Parsing has a performance effect
  • Converted to class with getters and setters

JSON

  • Small JSONs - GSON is the best
  • Large JSONs -
    • FastJson
    • Jackson
    • GSON + immutables type adapters

So.Scrolling
+ Keep UI thread only for UI
+ Understand concurrency APIs
+ Use libraries (memory, caching, json…)
+ Use loaders

5.System abuse

System Abuse
  • Don’t call private APIs by reflection
  • Don’t call private native methods (NDK/C level)
  • Don’t use Runtime.exex
  • “adb shell am” to communicate with other process is not something we want to support
  • Don’t abuse the System
  • Know and use APIs

6.Deprecation

Deprecation
  • API will be removed
  • Your app will not work
  • No way to update APIs and tools
  • There is a compelling reason to move
    • Security
    • Correctness
    • Performance
  • Know and use APIs
  • Refactor you dependencies
  • Update your dependencies and tools
Don’t use Apache Http Connection
  • Removed at M (still available as dependency)
  • *Use HttpURLConnection
    • Simple API
    • Small size
    • Transparent compression
    • Response caching

7.Bring your own gloves

Bring your own gloves
  • Various versions, devices, OEMs
  • APIs and libraries shipped with platform might behave differently
  • Async task…
  • Consider bundling your own version
  • Check dex limit
  • Check code bloat
Security
  • Own wrapped library (SSL/crypto etc)
  • Rooted devices
  • Your own sensitive data/protocols

8.Architesture

Understand app components life cycle
  • Activities
  • Fragments
  • Tasks
  • Flags
  • Add logs on callbacks
Work with framework not against
  • Framework components have a purpose
  • Specific semantics
  • Don’t over engineer
  • Keep simple
What you can do Architecture
  • Consistent
  • Get people on board quickly
  • Have someone experienced
  • Pick your dependencies wisely
Design your app for
  • Sleeping most of the time
  • Responsive when “awaken”

9.Know your APK

Know your executable
  • Dex limit numbers
  • Obfuscation
  • Package counts
  • Why I need the dependency
APK Analysis
  • Native methods in multidex
  • Interfaces + abstracts - LinearAlloc
ProGuard is a tool used in Android development to optimize and obfuscate the compiled code. It helps reduce the size of the APK file and makes it harder for reverse engineers to understand and modify the code. ProGuard performs several tasks to achieve this, including: 1. Shrinking: It analyzes the code and removes unused classes, fields, and methods, thereby reducing the size of the application. 2. Optimization: ProGuard applies various optimizations, such as inlining methods, removing dead code, and simplifying constant expressions, to improve the app's performance. 3. Obfuscation: It renames classes, fields, and methods with short, meaningless names, making it difficult for others to understand the code. To enable ProGuard in an Android project, you need to add the following lines to your project's `build.gradle` file: ```groovy android { // ... buildTypes { release { // ... minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } ``` Here, `minifyEnabled true` enables code shrinking and obfuscation, while `proguardFiles` specifies the ProGuard configuration files. The `getDefaultProguardFile('proguard-android-optimize.txt')` line includes a default set of rules provided by the Android SDK, and you can customize these rules in your own `proguard-rules.pro` file. It's important to note that ProGuard can sometimes cause issues if it mistakenly removes code that is actually used, or if it conflicts with certain libraries or reflection-based code. In such cases, you may need to tweak the ProGuard configuration to exclude specific classes or methods. Overall, ProGuard is a useful tool for optimizing and securing your Android app.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值