How do I stop this Thread in Android? - android

While learning using Threads in Android I've created simple thread that updates time textview every second:
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(time!=0){
if(time>9){timeLeftTV.setText("0:"+time);}
else{timeLeftTV.setText("0:0"+time);}
time--;
}
else {
//timeLeftTV.setText("finished");
}
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
I want to display dialog box when the time expires. How do I stop this thread?

use CountDownTimer
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
This is example of 30 seconds for 1 second time interval.
You can display dialog box on onFinish() method.

Most of the time I use a Runnable that can be scheduled with a Handler as followed:
final int timeInterval = 1000;
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run () {
textView.setText("time..");
// schedule the same Runnable after one second
handler.postDelayed(this, timeInterval);
}
};
handler.postDelayed(runnable, timeInterval);
To stop your loop, remove the Runnable from the Handler:
handler.removeCallbacks(runnable);
When you don't want to use the method above, simply use a Boolean that prevents your loop to continue and your Thread will end itself:
boolean stop = false;
Thread t = new Thread() {
#Override
public void run () {
while (!stop) {
// do stuff
}
}
};
t.start();
To stop the Thread:
stop = true;

Just interrupt the thread, Where you want to stop it.
thread.interrupt();

There are many ways to stop thread.
Like you can use Executor Services instead of timer. But for the quick solution you can go ahead with the following one:
long startTimer= System.currentTimeMillis();
long stopTimer= startTimer+ 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < stopTimer)
{
// Perform your all the required operation here
}
Hope it will help you.
For Executor service check the below stack link:
How to timeout a thread

Related

Running backgound thread every X seconds (Android Studio)

I have a code that plays 5 sounds with 1 second delay between the sounds and I want this part of code to be executed every 5 seconds (so it will run in a row so far as a boolean variable is true, and when it becomes false the tread run stopped - I have a button to both start and stop this executions). Everything works perfectly, but the issue is that I can't get rid of the 5 seconds delay in the first time I click the button, so when I first click, the sounds beggins only after 5 seconds. How can I make it start right away and only after the first time start taking the delays?
Here is the button onClick code:
public void clickHandlerStartTempo(final View view) {
if (!tempoOn) {
Toast toast = Toast.makeText(getApplicationContext(), "Start Tempo!", Toast
.LENGTH_SHORT);
toast.show();
tempoOn = true;
final Handler handler = new Handler();
final int delay = 5000; //milliseconds
handler.postDelayed(new Runnable() {
public void run() {
if (tempoOn) {
runCode(view);
handler.postDelayed(this, delay);
}
}
}, delay);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Stop Tempo!", Toast
.LENGTH_SHORT);
toast.show();
tempoOn = false;
}
}
And here is the runCode method:
public void runCode(View view) {
Runnable runnable = new Runnable() {
#Override
public void run() {
playSound(0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 4; i++) {
if (tempoOn) {
playSound(1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
return;
}
}
}
};
Thread thread = new Thread(runnable);
Log.i(TAG, "runCode: Thread id = " + thread.getId());
thread.start();
}
I'm new to android development and any help would be very much appreciated.
Thanks.
First you need to playsound without thread after that you will execute your reaming 5 second logic stop thread after 4 count.
public void onStartPress(){
playSound();
someMethod();
}
public void someMethod(){
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.postDelayed(new Runnable() {
#Override
public void run() {
playSound();
someMethod();
}
},1000);
}
Don't use actual Threads unless you really want to do something off the Ui thread. Most of the time you do want to keep things on the Ui thread.
For simple repeating tasks, you can easily repurpose the CountDownTimer class. Often with an (almost) infinite run time or Long.MAX_VALUE (292 million years). The fist onTick happens immediately after starting.
private CountDownTimer mTimer;
private void start() {
if (mTimer == null) {
mTimer = new CountDownTimer(Long.MAX_VALUE, 5000) {
#Override
public void onTick(long millisUntilFinished) {
// start a beeping countdown
new CountDownTimer(5000, 1000) {
private int state = 1;
#Override
public void onTick(long millisUntilFinished) {
playSound(state);
state = state + 1 % 2;
}
#Override
public void onFinish() {
playSound(0);
}
}.start();
}
#Override
public void onFinish() { /* ignore, never happens */ }
};
mTimer.start();
}
}
private void stop() {
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}

Android Button click Handler

I have a button(in say Activity 1), which when clicked should start a service (eg Service 1). But there must be a delay of 5 seconds before the service starts. I achieved this using SystemClock.sleep(5000) in the onStartCommand of the service. This worked properly.
Now I want to add the functionality that if the button is clicked again(even before the 5 seconds end), the service WILL NOT BE STARTED.
Any ideas how to do this?
(Edit : Please read the entire question before marking it as a duplicate. Thanks)
You can use handler with post delayed to achieve your goal. Make your button disable and enable it after five seconds along with starting your service. You can implement the following code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//start your service here
button.setEnabled(true);
}
}, 5000);
}
});
Above code will disable your button for 5 second and will start your service after 5 second.
I'd use a util class similar to the following. Pass it in a runnable and a delay in ms and you can call stop() on it to cancel before it has run. You can also call restart() if you want to restart your timer. I use it for things like auto showing/hiding controls on an immersive view.
public class DelayableRunnable{
int mDelay = 0;
Handler mHandler = new Handler();
Runnable mRunnable;
boolean mIsRunning = false;
public DelayableRunnable(Runnable runnable, int delay){
mRunnable = runnable;
mDelay = delay;
}
public void setNewDelay(int delay){
mDelay = delay;
}
public void start(){
if(mIsRunning) {
stop();
}
mHandler.postDelayed(mRunnable, mDelay);
mIsRunning = true;
}
public void stop(){
mHandler.removeCallbacks(mRunnable);
mIsRunning = false;
}
public void restart(){
stop();
start();
}
}
You can use Handler.postDelayed function for delayed actions in Android enviroment (better than plan java methods)
final Handler handler = new Handler(); // or use existed one your_view.getHandler()
handler.postDelayed(new Runnable() {
#Override
public void run() {
//start your service
}
}, 5000 /* 5s * 1000ms */);
Or simpler use you view function (work same as above):
your_view.postDelayed(new Runnable() {
#Override
public void run() {
//start your service
}
}, 5000 /* 5s * 1000ms */);
A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals void schedule (TimerTask task,long delay) Schedules the specified task for execution after the specified delay.
new Timer().schedule(new TimerTask() {
#Override
public void run() {
alertDialog.dismiss();
startActivity(new Intent(****.this,*********.class));
}
},5000);

Android Timer update UI between multiple tasks

I have tried multiple ways to have a single persistent timer update the ui in multiple activities, and nothing seems to work. I have tried an AsyncTask, a Handler, and a CountDownTimer. The code below does not execute the first Log.i statement.... Is there a better way to start the timer (which must be called from another class) in Main (which is the only persistent class)?
public static void MainLawTimer()
{
MainActivity.lawTimer = new CountDownTimer(MainActivity.timeLeft, 1000)
{
public void onTick(long millisUntilFinished)
{
Log.i("aaa","Timer running. Time left: "+MainActivity.timeLeft);
MainActivity.timeLeft--;
if(MainActivity.timeLeft<=0)
{
//do stuff
}
else
{
//call method in another class
}
}
public void onFinish()
{ }
}.start();
}
To clarify my problem:
When I run the code the Log.i("aaa","Timer running") statement is never shown in the log, and the CountDownTimer never seems to start. MainLawTimer is called from another class only (not within the same class.
For CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
You can use a Handler
Handler m_handler;
Runnable m_handlerTask ;
int timeleft=100;
m_handler = new Handler();
#Override
public void run() {
if(timeleft>=0)
{
// do stuff
Log.i("timeleft",""+timeleft);
timeleft--;
}
else
{
m_handler.removeCallbacks(m_handlerTask); // cancel run
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
Timer
int timeleft=100;
Timer _t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
Log.i("timeleft",""+timeleft);
//update ui
}
});
if(timeleft>==0)
{
timeleft--;
}
else
{
_t.cancel();
}
}
}, 1000, 1000 );
You can use a AsyncTask or a Timer or a CountDownTimer.
Thank you all for your help, I discovered the error in my code... timeLeft was in seconds rather then milliseconds. Since timeLeft was under 1000 (the wait period) the timer never started.

I want show the elapsed seconds from 60 to 1

I want to show a text view with elapsed seconds from 60 to 1.
How should I take handler event?
time = GetTime.Showtime();
elapsetime.setText(time + " Secs");
Use a CountDownTimer, http://developer.android.com/reference/android/os/CountDownTimer.html
First of all, you have to create and initialize Timer object:
Timer myTimer;
myTimer = new Timer();
After that you can call use the schedule method to call timerMethod() (or your method). It will the timerMethod() every second (1000 milliseconds).
myTimer.schedule(new TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 0, 1000);
//Runs your doSomething() in the UI Thread
private void timerMethod()
{
this.runOnUiThread(doSomething);
}
// make your doSomething() runnable
private Runnable doSomething = new Runnable() {
public void run() {
// Your code for doing something
}
i use handler thread runnable.
handler =new Handler();
runnable = new Runnable() {
#Override
public void run() {
elapsetime.setText(time+" Secs");
time--;
if(time<1){
handler.removeCallbacks(runnable);
}else{
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(runnable, 1000);

How to run a Runnable thread in Android at defined intervals?

I developed an application to display some text at defined intervals in the Android emulator screen. I am using the Handler class. Here is a snippet from my code:
handler = new Handler();
Runnable r = new Runnable() {
public void run() {
tv.append("Hello World");
}
};
handler.postDelayed(r, 1000);
When I run this application the text is displayed only once. Why?
The simple fix to your example is :
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
tv.append("Hello World");
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
Or we can use normal thread for example (with original Runner) :
Thread thread = new Thread() {
#Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(this);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.
More details are here http://developer.android.com/reference/android/os/Handler.html
new Handler().postDelayed(new Runnable() {
public void run() {
// do something...
}
}, 100);
I think can improve first solution of Alex2k8 for update correct each second
1.Original code:
public void run() {
tv.append("Hello World");
handler.postDelayed(this, 1000);
}
2.Analysis
In above cost, assume tv.append("Hello Word") cost T milliseconds, after display 500 times delayed time is 500*T milliseconds
It will increase delayed when run long time
3. Solution
To avoid that Just change order of postDelayed(), to avoid delayed:
public void run() {
handler.postDelayed(this, 1000);
tv.append("Hello World");
}
For repeating task you can use
new Timer().scheduleAtFixedRate(task, runAfterADelayForFirstTime, repeaingTimeInterval);
call it like
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
}
},500,1000);
The above code will run first time after half second(500) and repeat itself after each second(1000)
Where
task being the method to be executed
after the time to initial execution
(interval the time for repeating the execution)
Secondly
And you can also use CountDownTimer if you want to execute a Task number of times.
new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
}
}.start();
//Above codes run 40 times after each second
And you can also do it with runnable. create a runnable method like
Runnable runnable = new Runnable()
{
#Override
public void run()
{
}
};
And call it in both these ways
new Handler().postDelayed(runnable, 500 );//where 500 is delayMillis // to work on mainThread
OR
new Thread(runnable).start();//to work in Background
I believe for this typical case, i.e. to run something with a fixed interval, Timer is more appropriate. Here is a simple example:
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// If you want to modify a view in your Activity
MyActivity.this.runOnUiThread(new Runnable()
public void run(){
tv.append("Hello World");
});
}
}, 1000, 1000); // initial delay 1 second, interval 1 second
Using Timer has few advantages:
Initial delay and the interval can be easily specified in the schedule function arguments
The timer can be stopped by simply calling myTimer.cancel()
If you want to have only one thread running, remember to call myTimer.cancel() before scheduling a new one (if myTimer is not null)
Handler handler=new Handler();
Runnable r = new Runnable(){
public void run() {
tv.append("Hello World");
handler.postDelayed(r, 1000);
}
};
handler.post(r);
Kotlin
private lateinit var runnable: Runnable
override fun onCreate(savedInstanceState: Bundle?) {
val handler = Handler()
runnable = Runnable {
// do your work
handler.postDelayed(runnable, 2000)
}
handler.postDelayed(runnable, 2000)
}
Java
Runnable runnable;
Handler handler;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
// do your work
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
If I understand correctly the documentation of Handler.post() method:
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
So examples provided by #alex2k8, even though are working correctly, are not the same.
In case, where Handler.post() is used, no new threads are created. You just post Runnable to the thread with Handler to be executed by EDT.
After that, EDT only executes Runnable.run(), nothing else.
Remember:
Runnable != Thread.
Kotlin with Coroutines
In Kotlin, using coroutines you can do the following:
CoroutineScope(Dispatchers.Main).launch { // Main, because UI is changed
ticker(delayMillis = 1000, initialDelayMillis = 1000).consumeEach {
tv.append("Hello World")
}
}
Try it out here!
An interesting example is you can continuously see a counter/stop-watch running in separate thread. Also showing GPS-Location. While main activity User Interface Thread is already there.
Excerpt:
try {
cnt++; scnt++;
now=System.currentTimeMillis();
r=rand.nextInt(6); r++;
loc=lm.getLastKnownLocation(best);
if(loc!=null) {
lat=loc.getLatitude();
lng=loc.getLongitude();
}
Thread.sleep(100);
handler.sendMessage(handler.obtainMessage());
} catch (InterruptedException e) {
Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
}
To look at code see here:
Thread example displaying GPS Location and Current Time runnable alongside main-activity's User Interface Thread
now in Kotlin you can run threads this way:
class SimpleRunnable: Runnable {
public override fun run() {
println("${Thread.currentThread()} has run.")
}
}
fun main(args: Array<String>) {
val thread = SimpleThread()
thread.start() // Will output: Thread[Thread-0,5,main] has run.
val runnable = SimpleRunnable()
val thread1 = Thread(runnable)
thread1.start() // Will output: Thread[Thread-1,5,main] has run
}

Categories

Resources