【问题标题】:Why does remote service lose reference to an object, which holds a reference to a service?为什么远程服务会丢失对包含服务引用的对象的引用?
【发布时间】:2014-10-19 13:58:10
【问题描述】:

在我的情况下,我确实与远程进程服务中的服务进行通信......在主应用程序中,我确实在清单中声明了 2 个服务:

<service android:name="com.estimote.sdk.service.BeaconService"/>
<service android:process="my_remote_process" android:name="com.example.ServiceClass"/>

无论我想做什么,在我的主要活动 onCreate() 方法中,我都会启动“服务”,它会检查设备的 SDK 版本并检查 ServiceClass 是否已经在运行,以免在设备上重复 ServiceClass。然后我只需启动“真正的”服务:

context.startService(new Intent(context.getApplicationContext(),ServiceClass.class).putExtra("MyExtra", MyExtra));

在 ServiceClass.java 我声明

protected BeaconManager beaconManager;

作为类范围内的全局变量,我在 onCreate() 方法中实例化对象:

super.onCreate();
beaconManager = new BeaconManager(this);

我还有一个本地自定义类,比如说public class ManageConnections 它使用beaconManager 建立连接、扫描区域等。

beaconManager 持有对BeaconService 的引用,我在清单中声明了它。

现在问题如下:

如果我通过“主页”按钮关闭应用程序,BeaconService 会继续扫描。如果我确实完全关闭了应用程序(请按住“主页”按钮并交换活动)服务将重新启动,因为ServiceClass 返回START_STICKY 并且 BeaconService 继续扫描。但是,如果我通过“返回”按钮关闭应用程序,在 10-20 分钟后(有时甚至立即关闭),我在 ServiceClass 类范围中声明的变量 beaconManager 将失去对 BeaconManager 实例的引用并崩溃扫描BeaconService.

我在这里缺少什么?我误解了处理、线程和服务,还是垃圾收集器破坏了实例?我想说完全关闭应用程序比通过“返回”按钮关闭它更糟糕,但行为告诉我一些不同的事情。

【问题讨论】:

    标签: android service process ibeacon-android


    【解决方案1】:

    检查 ServiceClass 是否已在运行,以免在设备上重复 ServiceClass: 无需这样做,如果您尝试启动服务并且已经在运行,则您的设备中只能运行一个服务实例,该方法将被调用:

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
    
        return START_STICKY;// Restart if killed because of poor resource
    }
    

    我在 ServiceClass 类范围中声明的变量 beaconManager 失去了对 BeaconManager 实例的引用,并导致 BeaconService 扫描崩溃。

    发生这种情况是因为活动和服务不共享相同的上下文,每个活动都有自己的上下文,一旦应用程序从队列中删除,操作系统就会释​​放它引用。如果您想要再次从服务中调用您的活动,则使用 putExtra 将您的应用程序包和类作为字符串发送到服务,并在 onStartCommand 中接收 Extra。

    【讨论】:

      猜你喜欢
      • 2015-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多