Android开发最重要的就是保持系统运行的流畅性,为了减少内存使用、优化代码编程风格,本文将对于一些常见的错误进行介绍以及给出解决办法,希望能够通过本文介绍,能够对大家有所帮助。
本文主要通过编程常见错误以及sdk选择两个方面进行介绍
编程常见错误
Handle导致的内存泄露
描述:
This Handler class should be static or leaks might occur (anonymous android.os.Handler)
less… (⌘F1)
解决方法:
Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.
解读:
示例:
public class MyActivity extends Activity {
private MyHandler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new MyHandler(this);
}
@Override
protected void onDestroy() {
// Remove all Runnable and Message.
mHandler.removeCallbacksAndMessages(null);
super.onDestroy();
}
static class MyHandler extends Handler {
// WeakReference to the outer class's instance.
private WeakReference<MyActivity> mOuter;
public MyHandler(MyActivity activity) {
mOuter = new WeakReference<MyActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
MyActivity outer = mOuter.get();
if (outer != null) {
// Do something with outer as your wish.
}
}
}
}
静态变量导致的内存泄露
描述:
Static member ‘com.h2y.android.shop.activity.receiver.SMSBroadcastReceiver.mMessageListener’ accessed via instance reference less… (⌘F1)
解决方法:
Shows references to static methods and fields via class instance rather than a class itself.
Activity管理类导致的内存泄露
描述:
使用ActivityManager管理Activity时,一定不要忘记弹出finish掉的Activity实例,要不然存在引用,也会导致Activity在内存中无法释放而导致的内存泄露。
常见SDK内存泄露情况
百度地图
百度地图SDK本身存在内存泄露的情况。。。