Search code examples
androidmultithreadingresume

onRetainNonConfigurationInstance with Multiple Threads?


I have about resuming multiple threads within the same Activity: I've three different threads in my app, that I call AThread, BThread and CThread.

If my app is closed and reopened, I need to reopen all preview Threads. How could I do that? I thought on returning a list of threads. Is that a good option? Something like:

@Override
public Object onRetainNonConfigurationInstance() {
    return new ArrayList<Thread>(AThread, BThread, CThread);
}

And than, at the function onCreate, call a "for each" that verifies all Threads. Something like

    @Override
    public void onCreate(Bundle savedInstanceState) {
(...)
        super.onCreate(savedInstanceState);
        ArrayList<Thread> allThreads = (ArrayList<Thread>) getLastNonConfigurationInstance();
        AThread = allThreads.get(0);
        BThread = allThreads.get(1);
        CThread = allThreads.get(2);
        if (AThread != null && AThread.isAlive()) {
            // TODO SOMETHING
        }
        if (BThread != null && BThread.isAlive()) {
            // TODO SOMETHING
        }
        if (CThread != null && CThread.isAlive()) {
            // TODO SOMETHING
        }
    }

Is that correct? Any better Idea? Cheers =)


Solution

  • Use a Fragment to host your Threads (or more preferably an AsyncTask) and call setRetainInstance(true) in the Fragment's onCreate method. The Fragment will be retained across configuration changes and the Fragment (and its Threads) won't be destroyed along with the Activity. I believe this is preferred over using onRetainNonConfigurationInstance.