Android service does not work as singleton

I have a service that is used / bound in several actions (I carefully wrote it so that one activity unties it before another binding in onPause / onResume). However, I noticed that a member of the Service will not stick ...

Action 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 

Action 2:

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

Service Code:

 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; } } 

When changing one thing - turning the downloadItems service into a static one - everything works fine. But it bothers me; I have never used singleton before. Is this the correct method to use one of them?

+6
source share
1 answer

It turns out that Nosfer was right; all I needed to do was make a & d startService() call next to my bindService() , and everything was fine.

Since multiple startService() calls do not call the constructor multiple times, they were exactly what I needed. (This is very lazy of me, but it works now. I don’t know how to check the running (and unrelated) service.) My code now looks like this:

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

See also Bind service to action in Android

+7
source

Source: https://habr.com/ru/post/943997/


All Articles