Search code examples
javamultithreadingpollingsystem-tray

Java Thread stopping when hiding to SystemTray


For my parents I am writing a simple program to copy files from their digital photocamera to their 'My Documents' folder. They always need my help (they are not so technically advanced) to get their pictures off their camera so I decided to help them out. I called it The Copying Machine. Since I couldn't find a suitable USB-Listener in Java, I wrote one myself:

private void sync()
{
    // All devices in an ArrayList
    File[] roots = File.listRoots();
    ArrayList<File> newList = new ArrayList<File>();
    for(File f : roots)
    {
        newList.add(f);
    }

    // Delete unavailable devices
    ArrayList<File> removeThese = new ArrayList<File>();
    for(File f : devices)
    {
        if(!newList.contains(f))
        {
            removeThese.add(f);
        }
    }
    devices.removeAll(removeThese);

    // Add unknown devices
    for(File f : newList)
    {
        if(!devices.contains(f) && f.canRead() && f.canWrite())
        {
            alarm(f); // Called when new device inserted
            devices.add(f);
        }
    }
}

This method is called every 1000ms in a seperate Thread and I guess that will do. Admitted, this is a dirty method but it works. I tested this function often and I always had the result I wanted. When I continued building my programm, I found that the thread would stop detecting new devices when I hide my programm to the SystemTray. When I open it again, the detection thread still won't work. Could anyone tell me what causes this and how this is to be solved?


Solution

  • Upon saving the data inserted by the user, I stopped detection of new devices. This was foolish of me so I thank you for making me aware of this.

    public boolean saveSettings() 
    {
        File f = new File(fsv.getHomeDirectory() + File.separator + "settings.cms");
        ObjectOutputStream objOut;
        try 
        {
            // Here was my problem. 
            detector.stopDetection();
    
            if(gui.saveSettings())
            {
                // Settings-file wegschrijven
                objOut = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
                objOut.writeObject(settings);
                objOut.flush();
                objOut.close();
                return true;
            }
            else
            {
                return false;
            }
        } 
        catch (IOException e) 
        {
            handleExceptions(e);
            return false;
        }
    }