Android常见内存泄漏以及解决办法

Dear 丶 2022-07-12 03:40 326阅读 0赞

#1. 注意你的Context引用

##尝试使用合适的context##

(1).Toast能在许多的Activity看到, 使用 getApplicationContext()
(2).service经常比activity生命周期长,所以使用如下的代码:

Intent myService = new Intent(getApplicationContext(), MyService.class)

下图展示了哪些场合使用Contexts时合适的

#2. 检查你是否关闭了service

例如使用Google位置service,但是忘记调用googleApiClient.disconnect()来关闭

  1. //Disconnect from API onDestroy()
  2. if (googleApiClient.isConnected()) {
  3. LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, GoogleLocationService.this);
  4. googleApiClient.disconnect();
  5. }

#3. 检查 image 和 bitmaps的使用
如果你使用Square’s 的第三方库 Picasso, 我发现如果不调用.fit()会造成内存泄漏, 这个函数把我的内存从50M减少到少于19M

  1. Picasso.with(ActivityExample.this) //Activity context
  2. .load(object.getImageUrl())
  3. .fit() //This avoided the OutOfMemoryError
  4. .centerCrop() //makes image to not stretch
  5. .into(imageView);

#4.broadcast receivers
使用 broadcast receivers要解除注册

#5.Observer
如果你使用 java.util.Observer (Observer pattern):

确认调用 deleteObserver(observer);

发表评论

表情:
评论列表 (有 0 条评论,326人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Android 常见内存泄漏

    内存泄漏(Menory Leak) 进程中某些对象已经没有使用价值,但是他们却还是直接或间接地被引用到GC Root导致无法回收。 内存溢出(OOM) 当内存泄漏