6

複数のアクティビティで使用/バインドされているサービスがあります (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

アクティビティ 2:

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 変数を静的なものに変更すると、すべてが完全に機能します。しかし、それをしなければならないのは心配です。この方法でシングルトンを使用したことはありません。これは、これらのいずれかを使用する正しい方法ですか?

4

2 に答える 2