【发布时间】: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 谢谢;这正是我需要知道的!我会或者会选择你作为最佳答案。