in my android app i have an ui-update-thread that keeps all my views up-to-date.
protected Thread UIUpdateThread = new Thread()
{
@Override
public void run()
{
while(true)
{
query_some_data_from_service(); // gets some "fresh" data from a service
UIUpdateHandler.sendEmptyMessage(0); // will update all ui elements with the new values
sleep(1234);
}
}
};
i start this thread in onCreate() with
UIUpdateThread.start();
and everything works just fine 🙂 when i leave the activity (e.g. because i switch to another activity) i call
UIUpdateThread.interrupt();
within onStop() to prevent the thread from running all the time. if i dont do this, it would keep running even if i close the app !?!?!!
problem is: how do i bring this thread back to life when returning from some other activity to this one? run() doesnt work, calling the initial start() in some other method like onResume() crashes the app.
i already tried a lot of things, but nothing seems to work 🙁
Atmocreation’s answer is the correct one…assuming that your implementation is a good idea in the first place.
First, the thread that you show here runs briefly and immediately terminates on its own, so you would not need to call
interrupt()to stop it. In that case, you are probably better served switching to anAsyncTaskrather than your own thread and handler, as you will need less code and can take advantage ofAsyncTask‘s thread pool.If your real thread is not what you show here, but some sort of infinite loop, that is a bad idea in general. Never create busy loops, particularly in Android. Most likely, there is a better solution for your problem, perhaps one that would avoid the need for
interrupt()as well.