This is the code of my testing app:
public class MainActivity extends Activity
{
private TextView text;
private Button start;
private Button stop;
private TestThread Points;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.mainTextView1);
start = (Button) findViewById(R.id.mainButton1);
stop = (Button) findViewById(R.id.mainButton2);
Points = new TestThread();
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View p1)
{
if (! Points.isAlive())
{
Points.start();
}
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View p1)
{
if (Points.isAlive())
{
Points.stop();
}
}
});
}
public class TestThread extends Thread
{
private String points;
@Override
public void run()
{
for (int a = 0; a < 3; a++)
{
try
{
if (a == 0) points = ".";
else if (a == 1) points = "..";
else if (a == 2) {
points = "...";
a = -1;
}
runOnUiThread(new Runnable()
{
@Override
public void run()
{
text.setText(points);
}
});
Thread.sleep(350);
} catch (InterruptedException e) {}
}
}
}
}
When I click on Start button the thread starts successfully but when I click on Stop button the app crashes... How can i stop the thread successfully without force closing?
Thanks a lot
Thread.stop() function is deprecated and should not be used to stop a thread. this is according to the java docs.
a good way to stop a thread is make it exit its run method.
a simple way to achive this is by adding a boolean member to your thread class:
public class TestThread extends Thread
{
private String points;
private boolean keepRunning = true;
public cancel(){
keepRunning = false;
}
@Override
public void run()
{
for (int a = 0; a < 3; a++)
{
if(!keepRunning) break;
try
{
if (a == 0) points = ".";
else if (a == 1) points = "..";
else if (a == 2) {
points = "...";
a = -1;
}
runOnUiThread(new Runnable()
{
@Override
public void run()
{
text.setText(points);
}
});
Thread.sleep(350);
} catch (InterruptedException e) {}
}
}
}
call the TestThread.cancel() function in your stop button onClick method.
Other than adding a Boolean to stop it I believe you could catch InterruptException and just call Thread.interrupt(); which would exit the loop this ending the thread
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With