您的位置:首页 > 移动开发 > Android开发

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

2017-02-09 13:14 501 查看

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);

帮朋友招聘职位如下

普照天星【Java开发工程师】20-30k

http://www.jianshu.com/p/8b52751360df

产品经理20-30k

http://www.jianshu.com/p/cb0ac7a00796

我的微信二维码如下



微信订阅号二维码如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 内存泄露