0

I have a problem regarding the lifetime of a variable.

My Android-App should write sensor-data to a file and send this file to a server. For this I created a Activity (Main-Activity) and two Services. One is for writing the sensor-data to files (Sensor-Service) and one for sending the files to a server (Upload-Service). The activity has two toggle-buttons for start/stop the two services seperately.

The communication between the two services works with a list: When a new file with sensor-data is ready (has a particular size) the name of the file is appended to a list. The Upload-Service checks in an infinite-loop if new files are in the list and uploads them.

But this list causes a problem: When my App runs in Background and I open many other Apps at some point the reference on the list becomes NULL in Sensor-Service (and probably also in Upload-Service).

The list is defined in the Main-Activity:

private static LinkedBlockingDeque<String> mFileSendQueue;

and initialised in onCreate of the Main-Activity:

mFileSendQueue = new LinkedBlockingDeque<String>();

and passed to the two Services via a static method setQueue (both services contain such a method):

public static void setQueue(LinkedBlockingDeque<String> queue) {
    mFileSendQueue = queue;
}

I know that the Activity can be closed by Android e.g. if space is required, but in my opinion the list shouldn't be deleted as long as there is at least one reference to it. Does anybody know what my mistake is?

Thanks for reading

steckl
  • 404
  • 8
  • 16
  • Instead of sharing an in memory list, I'd recommend sharing a persistent file on disk (or a database). And instead of polling for the file, you can use custom broadcasts. – S.D. Oct 27 '12 at 17:14

1 Answers1

2

Id recommend that your "sender service" keeps record itself. You could name files by timestamps and the sender stores the last timestamp that was uploaded.

Android / dalvik vm seems to delete references after some time in the background. I've seen it happen in my services, suddenly hardware sockets are null etc.

NikkyD
  • 2,209
  • 1
  • 16
  • 31
  • Thanks for confirming that this behavior is common for Android. I solved the Problem by using a Singleton-Pattern. Every-Time I need the list I call getInstance(). If the Instance is NULL I re-initialize the list (and insert the names of all old files from disk). Otherwise I return the list as before. In Addition I changed all required Attributes to be static and I use startForeground(). I don't know which of these methods solves my problem, but it seems to be solved now. It runs for 10 Hours now without any problem. – steckl Nov 01 '12 at 09:57
  • i just want to add that i am not some android guru, ive seen it happen but i dont know if its "common" – NikkyD Nov 02 '12 at 19:44