Android常见导致内存问题的案例

常见导致内存问题的案例

1. Handler的使用

    private val handler = Handler(Looper.getMainLooper(), object : Handler.Callback {
        override fun handleMessage(msg: Message): Boolean {
            //Looper内的message -> handler -> 匿名内部类 -> activity
            Log.d(TAG, "handleMessage")
            TAG = "Callback"
            return true;
        }
    })

    private val handler1 = object:Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            TAG = "handler1"
            super.handleMessage(msg)
        }
    }
    
    inner class InnerHandler(context: Context?) : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            TAG = "inner class"
        }
    }
    
    handler.postDelayed(Runnable {
        TAG = ""
    }, 200000)

    handler.sendEmptyMessageDelayed(0, 200000)

在 Handler 代码里 android.os.Handler#enqueueMessage 很明显能看到 message 持有 Handler 的引用。因为一个线程只有一个 Looper , 但是可以有多个 Handler ,所以 message 需要持有 Handler 引用来分发到指定的 Handler 。

然而上面三种写法都有导致 Handler 持有外部 Activity 的引用。

第一种是 object 为 实现了 Handler.Callback 接口的匿名内部类

第二种是 object 为继承了 Handler 的 匿名内部类

第三种是 InnerHandler 为继承了 Handler 的内部类

所以只要消息一直存在于主线程,就会导致 Activity 不能释放,导致了内存泄漏。

解决方法:

//静态内部类 kotlin 也为了避免内部类持有导致的内存泄漏频繁发生,所以 默认一个 class 代表的是静态内部类,不持有外部引用
//inner class 才是内部类
class Handler2(context: Context?) : Handler(Looper.getMainLooper()) {
  private val weakReference: WeakReference<Context> = WeakReference(context)
    override fun handleMessage(msg: Message) {
    //TAG = "weakReference"
    weakReference.get()?.let {
      Log.e("", "")
    }
  }
}

//如果 Message 在退出界面后可以忽略不处理时,可以选择移除消息
override fun onDestroy() {
  super.onDestroy()
    handler.removeCallbacksAndMessages(null)
}


2. Static/单例模式

Singleton.getInstance(MainActivity@this)

public class Singleton {
    private static Singleton mInstance;

    private Context context;

    private Singleton(Context context) {
        this.context = context;
    }

    public static Singleton getInstance(Context context){
        if(mInstance == null){
            mInstance = new Singleton(context);
        }
        return mInstance;
    }

}

一般情况下,静态变量 和 Class 与 ClassLoader 的生命周期,进程的生命周期一致。上诉写法会导致 第一次调用 getInstance 传入的activity 不会释放,从而导致内存泄漏。所以 Static 关键字修饰的成员变量要注意引用关系。

解决方案:

  1. 尽量不在单例里构造函数使用 context , 如果一定要用的话,可以传入 ApplicationContext 因为它与进程的生命周期一致。大部分情况下不会涉及界面的修改, ApplicationContext 就足够了。
  2. 如果实在非要使用 Activity 的 context,可以使用软引用。

3. 非静态匿名内部类

val thread = Thread(mRunnable)
thread.start()
  
private val mRunnable = object :Runnable {
  override fun run() {
    try {
      TAG = "mRunnable"
        Thread.sleep(200000);
    }catch (e: Exception){
      e.printStackTrace()
    }
  }
}

mRunnable 为非静态匿名内部类实例,持有了外部引用,与 handler 例子类似导致了泄漏。

解决方案:

JAVA 中 设置 mRunnable 为静态 。

kotlin 编译阶段有优化,只要不掉用外部变量,则不会持有引用。

4.属性动画

anim = ValueAnimator.ofFloat(0f, 1f)
anim.duration = 30000

animator = ObjectAnimator.ofFloat(textview, "alpha", 1f, 0f, 1f)
animator.duration = 500000
animator.start()

主要原因在于 android.animation.AnimationHandler#sAnimatorHandler 是 static 的,导致了内存泄漏。

可以按如下顺序跟代码:

android.animation.ValueAnimator#cancel
android.animation.ValueAnimator#endAnimation
android.animation.ValueAnimator#removeAnimationCallback
android.animation.ValueAnimator#getAnimationHandler
android.animation.AnimationHandler#getInstance
android.animation.AnimationHandler#sAnimatorHandler

解决方案:

    override fun onDestroy() {
        super.onDestroy()
        anim.cancel()
        animator.cancel()
    }

5.资源未关闭

BraodcastReceiver,ContentObserver,File,游标 Cursor,Stream 等资源未及时解注册和释放

解决方案:

及时解注册。资源及时释放。有些语法糖比如Java 1.7 提供的try-with-resource。以及Kotlin FileReadWrite.kt 大多实现了kotlin.io.CloseableKt#use

6.自定义View onDraw 每次new对象

@Override
protected void onDraw(Canvas canvas) {
		Paint paint = new Paint();
}

onDraw执行非常频繁,如果在里面new 对象会导致频繁的申请内存和释放。另外一方面,频繁的 GC 也会导致卡顿。

解决方案:

private Paint mPaint;
 
public TestView(Context context) {
		super(context);
  	mPaint = new Paint();
}

7. 所有图片都预先加载

 //mJustView 其实只有部分机型收到广播后才需要add到window上,然而这里直接在初始化时就已经加载到内存里了。
private void makeJustView() {
        RelativeLayout root = (RelativeLayout) View.inflate(mContext, R.layout.eye_layout, null);
        mConfrim = (Button) root.findViewById(R.id.confirm);
        mConfrim.setOnClickListener(this);
        mJustView = root;
}
private void init() {
        makeJustView();
}

解决方案:

//使用懒加载,仅有部分机型收到广播后,才会加载这张图,对于其他机型这部分内存就省下了
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context conmTextView, Intent intent) {
                showProtectView(getJustView());
        }
    }
};

private View getJustView(){
		if(mJustView == null){
				makeJustView();
		}
		return mJustView;
}
private void init() {
		
}

8. 图片放错目录

假设本应该放在xhdpi的图片 放在了mdpi目录下,在xhdpi的机器上运行时,长宽会被放大两倍,相应的内存会变成两倍。

直接放错的概率不到,比较容易发生在换图,UI只提供了一张图什么的。

9. XML布局

有些view可能在布局里只显示一次的,比如引导图,其实是可以使用 ViewStub。代替VISIBLE/GONE的,需要时再加载。

imageView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);

10.Bitmap使用

https://mp.weixin.qq.com/s?__biz=MzA3NTYzODYzMg==&mid=403263974&idx=1&sn=b0315addbc47f3c38e65d9c633a12cd6&scene=21#wechat_redirect

  • inSampleSize 采样加载bitmap
BitmapFactory.Options options = new Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId, options);
  • Matrix 矩阵 小图放大,内存只有采样出来的大小,但是显示效果是放大的。

    Matrix matrix = new Matrix();
    matrix.postScale(2, 2, 0, 0);
    imageView.setImageMatrix(matrix);
    imageView.setScaleType(ScaleType.MATRIX);
    imageView.setImageBitmap(bitmap);
    
  • Bitmap的像素格式

    格式描述
    ALPHA_8只有一个alpha通道
    ARGB_4444这个从API 13开始不建议使用,因为质量太差
    ARGB_8888ARGB四个通道,每个通道8bit,默认。
    RGB_565每个像素占2Byte,其中红色占5bit,绿色占6bit,蓝色占5bit。不需要 alpha 时资源为jpg时用这个比较理想
  • 帧动画 比如 loading动画 //用自定义view 代替

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值