I've an andoid (API 21) mainactivity in which a start a thread. Pressing a button i close the thread and mainactivity. Is this a good solution to interrupt thread and close activity? I try to call
mythread.cancel()
finishAndRemoveTask();
But when mainactivity/programs closes it crashes because the thread is still alive.
So when button is clicked i try to change the code and write :
mythread.interrupt();
finishAndRemoveTask();
Is this a good solution ? (i don't know if i can use mythread.join() because the thread runs infinitely..
In OnCreate i create and start the thread
myThread_read = new thread_read(handler_read);
//starting thread
myThread_read.start();
I know i must use Runnable but this code extends Thread class. The thread code is:
private class thread_read extends Thread {
Handler mHandler;
String logString ;
protected volatile boolean running;
/* constructor */
thread_read(Handler h) {
mHandler = h;
}
public void start()
{
Logger.WriteString("thread_read", "Starting");
running = true;
super.start();
}
public void cancel()
{
Logger.WriteString("thread_read", "Stopping");
running = false;
}
public void run() {
while (running) {
try {
Thread.sleep(500); // 500 msecs
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
// do works
}
}
}
}