Reputation: 37
I have several activities going one by one with a button click, but if button isnt clicked during 10 seconds next activity starts automatically with the help of thread.
button1 = (ImageButton)findViewById(R.id.button2);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent firstIntent = new Intent(Tab1.this, Tab2.class);
startActivity(firstIntent);
finish();
}
});
Thread background = new Thread() {
public void run() {
try {
sleep(10*1000);
Intent i=new Intent(getBaseContext(),Tab2.class);
i.putExtra("CountNum", count);
startActivity(i);
finish();
} catch (Exception e) {
}
}
};
background.start();
The problem is: if I go from tab1 to tab2 and then to tab3 with a button click, then in 10 seconds tab2 will start again because of thread from tab1, which was still running(I did not know it works this way =\ ). How to fix it? How to stop the thread if I used a button? Thanks in advance
Upvotes: 0
Views: 65
Reputation: 13761
There's a time that .stop()
has been deprecated an highly discouraged as it might terminate your Thread
in an unsafe way.
The most common approach is having a boolean
controller inside your Thread
, which will check if some action happened (in your case, a button has been pressed), and if so, in the next loop iteration, simply use return
within your Thread
. This will terminate it cleanly and safely.
---- EDIT ----
Suppose this is your button onClickListener()
:
boolean has_been_clicked = false;
but = (ImageButton) findViewById(R.id.your_button_id);
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Do the stuff your need
has_been_clicked = true;
}
});
new Thread(
new Runnable() {
public void run() {
while (!has_been_clicked) {
// Do your stuff here...
...
}
// If you've reached this point, it means you have clicked
// the button since the value of has_been_clicked is true,
// start your Activity here
...
startActivity(i);
return;
}
}
).start();
Upvotes: 1
Reputation: 1020
Here is an example i hope it will help i just modify you code a bit .
First create a Boolean OKToStart , it will be use to check if we are within 10sec laps
button1 = (ImageButton)findViewById(R.id.button2);
boolean OKToStart =true;
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(OKToStart){
Intent firstIntent = new Intent(Tab1.this, Tab2.class);
startActivity(firstIntent);
finish();
}
}
});
Thread background = new Thread() {
public void run() {
while(OKToStart){
try {
sleep(10*1000);
OKToStart =false
} catch (Exception e) {
}
}
}};
background.start();
Upvotes: 0