I have this problem in android. i have a main activity who calls a thread with this
Runnable work = new Runnable() {
public void run() {
while (kill) {
try {
Thread.sleep(5000);
connect();
} catch (InterruptedException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
kill its a public boolean in MainActivity. what can i do to save the thread so when i resume the activity i still can kill the thread?
I think you want to do something closer to what this solution proposes.
However, if you really want to keep doing it in a Thread
, then I suggest you extend a new class from Thread
and add a method called killMe()
. This will modify the (now private) boolean kill
flag. Then, in your onRetainNonConfigurationInstance()
you can return this Thread
and you can retrieve it again in onResume
. If you return and activity has not been killed, then it's fine, you can just call killMe()
on the existing Thread
.
Example:
@Override
public Object onRetainNonConfigurationInstance() {
return thread;
}