【问题标题】:Android service isn't working as a singletonAndroid 服务不能作为单例运行
【发布时间】:2019-04-06 19:46:11
【问题描述】:

我有一个服务正在多个活动中使用/绑定(我仔细编写了它,以便一个活动在另一个绑定之前取消绑定,在 onPause/onResume 中)。但是,我注意到服务中的成员不会坚持....

活动一:

private void bindService() {
    // Bind to QueueService
    Intent queueIntent = new Intent(this, QueueService.class);
    bindService(queueIntent, mConnection, Context.BIND_AUTO_CREATE);
}

...

bindService();

...

mService.addItems(downloads);     // the initial test adds 16 of them

活动二:

bindService();                             // a different one than activity 1
int dlSize = mService.getQueue().size();   // always returns 0 (wrong)

服务代码:

public class QueueService extends Service {
    private ArrayList<DownloadItem> downloadItems = new ArrayList<DownloadItem();

    // omitted binders, constructor, etc

    public ArrayList<DownloadItem> addItems(ArrayList<DownloadItem> itemsToAdd) {
        downloadItems.addAll(itemsToAdd);
        return downloadItems;
    }

    public ArrayList<DownloadItem> getQueue() {
        return downloadItems;
    }
}

更改一件事后——将服务的 downloadItems 变量变为静态变量——一切正常。但不得不这样做让我担心;我以前从未以这种方式使用过单例。这是使用其中之一的正确方法吗?

【问题讨论】:

  • 您是否在活动中的任何地方调用 startService()?这允许服务作为单例保持活力。否则会在绑定到它的activity被销毁时被销毁。
  • @Nospherus 我很快就会添加我所做的——tl;dr “bindService” 和“startService()”一样好用吗?
  • 没有。您必须同时调用 startService() 和 bindService()。如果你只调用bindService(),那么一旦你解除绑定,服务就会死掉。通过调用 startService(),它会一直保持活动状态,直到您调用 stopService()(或服务内部的 stopSelf())。
  • @Nospherus 谢谢;这正是我需要知道的!我会或者会选择你作为最佳答案。

标签: java android singleton


【解决方案1】:

事实证明 Nospherus 是正确的;我需要做的就是在我的bindService() 旁边打一个startService() 电话,一切都很好。

因为多个startService() 调用不会多次调用构造函数,所以它们正是我所需要的。 (这对我来说非常懒惰,但它现在有效。我不确定如何检查已启动(而非绑定)的服务。)我的代码现在看起来像这样:

Intent queueIntent = new Intent(getApplicationContext(), QueueService.class);
bindService(queueIntent, mConnection, Context.BIND_AUTO_CREATE);
startService(queueIntent);

另见Bind service to activity in Android

【讨论】:

  • 哇,我整个上午都在寻找我的两个服务实例的解决方案,这里是......只需 startService 。
  • 我会在绑定之前 startService ,更好的做法。
【解决方案2】:

默认情况下服务总是单例

在给定时间只能存在一个服务实例。如果服务正在运行,那么您将无法创建该服务的另一个实例。期间。

绑定多个Activity

您可以将服务绑定到 n 个活动。每个绑定独立工作。当您从一个 Activity 移动到另一个 Activity 时,Activity1 所做的更改将在您移动到 ​​Activity2 时持续存在仅当服务处于活动状态时。

那么为什么这些更改在我的案例中没有持续存在?
要理解这一点,我们应该知道服务的生命周期

服务的生命周期

onCreate()onDestroy() 之间存在服务

案例一:
案例 2:

【讨论】:

    猜你喜欢
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多