Android服务不是单身人士

6 java singleton android

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

活动1:

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
Run Code Online (Sandbox Code Playgroud)

活动2:

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

服务代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

改变一件事 - 将服务的downloadItems变量变成静态变量 - 一切都很完美.但是必须这样做让我担心; 我之前从未使用过这种单身人士.这是使用其中一种的正确方法吗?

小智 7

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

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

Intent queueIntent = new Intent(getApplicationContext(), QueueService.class);
bindService(queueIntent, mConnection, Context.BIND_AUTO_CREATE);
startService(queueIntent);
Run Code Online (Sandbox Code Playgroud)

另请参阅将服务绑定到Android中的活动