Reputation:
i 've created an android application on which when one button clicks handler will activate an on every 2 second a toaster will appear. same on the other way i've a stop button from which i want to stop the running thread on clicking
This is my code
private final int FIVE_SECONDS = 2000;
public void scheduleSendLocation() {
handler.postDelayed(new Runnable() {
public void run() {
sendLocation(); // this method will contain your almost-finished HTTP calls
handler.postDelayed(this, FIVE_SECONDS);
}
}, FIVE_SECONDS);
}
protected void sendLocation() {
Toast.makeText(getApplicationContext(), "Your Location is ", Toast.LENGTH_SHORT).show();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
stop = (Button) findViewById(R.id.stop);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
scheduleSendLocation();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// what to write here
}
});
}
Upvotes: 1
Views: 5790
Reputation: 1526
Try calling the following code
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
handler.removeCallbacks(runnable);
}
});
Where runnable
is the runnable which you added while calling postDelayed. Any pending posts of runnable
will be removed that are in the message queue.
Upvotes: 5
Reputation: 8747
Try this:
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
myHandlerThread.interrupt();
myHandlerThread = null;
}
});
Upvotes: 0