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

#1. 注意你的Context引用

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

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

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

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

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

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


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

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


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

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

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

确认调用 deleteObserver(observer);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值