不要将Android上下文类放在静态字段中;这是内存泄漏 [英] Do not place Android context classes in static fields; this is a memory leak
问题描述
我有一个具有BeaconNotificationsManager
的服务,我想在我的Activity
中访问该BeaconNotificationsManager
.目前,我的BeaconNotificationsManager
是static
:
I have a service which has a BeaconNotificationsManager
, I want to access this BeaconNotificationsManager
in my Activity
. Currently my BeaconNotificationsManager
is static
:
public class MyService extends Service {
public static BeaconNotificationsManager bnm;
}
我正在像这样在我的Activity
中访问它:
And I am accessing this in my Activity
like this:
if(MyService.bnm != null){
// do stuff
}
尽管Android告诉我这很糟糕.正确的方法是什么?
Although Android is telling me this is bad. What is the correct way to do this?
推荐答案
关于静态问题:只需说您正在引用其他类中的服务bnm
,并且服务已被操作系统,但是某些活动仍在使用静态对象(bnm),因此除非您将活动内的bnm
引用设置为null,否则它将保留垃圾回收中的服务上下文,这将泄漏所有应用程序资源
About Static issue: let just say you are referencing your service bnm
from another class and your service has been destroyed by the OS but the static object(bnm) is still in use by some activity so this will hold on the service context from garbage collection unless you set your bnm
reference inside your activity to null and this will leak all the application's resources
解决方案:
最佳选择是使用BindService
,这样您就可以通过service对象在service use IBinder
The optimal option is use BindService
in this way you will get the more control over your service through the object of service , in service use IBinder
class MyService..{
public BeaconNotificationsManager bnm;
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// inside service class
public boolean getStatus(){
return bnm==null;
}
}
因此,当您绑定服务时,您将获得绑定器对象,该对象可以进一步为您提供服务对象并使用您的函数检查无效性
So when you bind a service , you will get the binder object which can further give you the service object and use your function to check nullity
1.)创建一个ServiceConnection对象
1.) Create a ServiceConnection object
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
bnmNull= mService.getStatus(); // bnm status
}
2.)使用第一步中创建的ServiceConnection
对象绑定Service
2.) Bind a Service
using ServiceConnection
object created in first step
Intent intent = new Intent(this, MyService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
,因此只需在类"getStatus"中具有一个函数,然后将其与通过活页夹检索到的对象一起调用即可,请检出
,so then simply have a function in your class 'getStatus' and call it with the object retrieved through the binder check out the link for code example
这篇关于不要将Android上下文类放在静态字段中;这是内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!