Java 不要将Android上下文类放在静态字段中;这是内存泄漏

Java 不要将Android上下文类放在静态字段中;这是内存泄漏,java,android,android-context,Java,Android,Android Context,我有一个服务有一个BeaconNotificationsManager,我想在我的活动中访问这个BeaconNotificationsManager。当前我的beaconficationsManager是静态的: public class MyService extends Service { public static BeaconNotificationsManager bnm; } 我在我的活动中访问它,如下所示: if(MyService.bnm != null){

我有一个服务有一个
BeaconNotificationsManager
,我想在我的
活动中访问这个
BeaconNotificationsManager
。当前我的
beaconficationsManager
静态的

public class MyService extends Service { 
    public static BeaconNotificationsManager bnm;
}
我在我的
活动中访问它,如下所示:

if(MyService.bnm != null){
     // do stuff
}

虽然安卓告诉我这很糟糕。正确的方法是什么

关于静态问题:假设您正在从另一个类引用您的服务
bnm
,并且您的服务已被操作系统销毁,但静态对象(bnm)已损坏仍由某些活动使用,因此这将保留垃圾收集中的服务上下文,除非将活动中的
bnm
引用设置为null,否则这将泄漏应用程序的所有资源

解决方案:

最佳选择是使用
BindService
,这样您就可以通过服务对象在服务中使用
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;
    }
}
因此,当您绑定一个服务时,您将获得binder对象,它可以进一步为您提供服务对象,并使用您的函数检查空值

1.)创建ServiceConnection对象

  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

    Intent intent = new Intent(this, MyService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

,那么只需在类“getStatus”中设置一个函数,并使用通过活页夹检索到的对象调用它即可查看

实现界面为什么它是静态的?你不能把它变成一个实例变量吗?@MickMnemonic,也许你已经知道,启动服务不会提供对服务实例的访问,活动和服务没有直接的关系,除非它们被绑定,所以接口不是最佳解决方案。谢谢Pavneet,我会尝试一下