I am developing an application which has to use timer for some purpose. What I need to do is, to set a timer when a condition satisfies and to cancel it correspondingly. Then again I may start the same timer which I cancelled. Please provide a solution.
For a single timer android sets a single thread. When you cancel that timer its execution thread terminates gracefully, and no more tasks may be scheduled on it. So you have to create a new instance of the timer object.
you can do as shown below.
if(condition == true)
{
timer = new Timer();
timer.schedule(new TimerTask(), delay, span);
}
else{
timer.cancel();
}
Create CountDownTimer class like:
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
// do something of finish timer
}
#Override
public void onTick(long millisUntilFinished) {
// do something on tick of timer
}
}
and should make an object of MyTimer like below:
MyCount timerCount = new MyCount(<TIME_UNTIL_FINISH_MILLISECONDS>, <TIME_OF_EACH_TICK>);
and can start timer everywhere you want with:
timerCount.start();
and cancel it with:
timerCount.cancel();
Related
I want to set network status in TextView, which I want to repetitively call method and set in background, so I used AsyncTask class with infinite loop
class setNetworkText extends AsyncTask
{
#Override
protected Object doInBackground(Object[] params) {
for(;;)
{
if(isNetworkConnected()) //check internet connection and if found it return true
setOnline(); // it set my TextView text to Online
else
setOffline(); // it set my TextView text to Offline
Thread.sleep(2000);
}
return null;
}
}
but it is not working, it stops my application.
Android will (in most versions) only execute one AsyncTask at a time - so if you keep blocking in doInBackground of one AsyncTask, no other AsyncTasks will run, thus blocking your application.
Take a look at using Handler.postDelayed or using a TimerTask. They are more suited for repeating actions.
You can not use AsyncTask to do that. You should use Handler to schedule a task periodically.
// Create the Handler
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableTask = new Runnable() {
#Override
public void run() {
if(isNetworkConnected())
setOnline();
else
setOffline();
}
};
// Call on main thread (for example, inside onResume())
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(runnableTask, 2000);
}
// Remember to unregister it onPause()
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnableTask);
}
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//check something on time interval here 1 second
}
public void onFinish() {
//when your task done here 3 second is time to end
}
}.start();
explanation
CountDownTimer(long millisInFuture, long countDownInterval)
millisInfuture will be how long you want to run the task and countDownInterval is the interval in your case it is 2 seconds
In my application i want to set a timeout when the user turn on 3G... after a certain amount of time elapsed , i will turn off 3G..
my problem is cancelling the scheduled timer.. every time i call timer.cancel() .. the program throws errors
the problem cause when i call clearTimeout() method..
Timer timer;
class RemindTask extends TimerTask {
public void run() {
//do something when time's up
log("timer","running the timertask..");//my custom log method
timer.cancel(); //Terminate the timer thread
}
}
public void setTimeout(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
public void clearTimeout(){
log("timer", "cancelling the timer task");//my custom log method
timer.cancel();
timer.purge();
}
please help me .. i am an android beginner..
Android has a class CountdownTimer which has start() and cancel().
I have implemented a countdown timer in an application of mine. It runs in the background fine and dandy, but when i use advanced task killer, it stops the timer and the only way to restart it is to open the application again. Is there anyway to have the timer persist, even if I use something like advanced task killer?
Code:
TextView tv;
final MyCounter timer = new MyCounter(10000,1000);
tv = (TextView)findViewById(R.id.healthtext);
tv.setText("10");
timer.start();
}
public class MyCounter extends CountDownTimer{
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "death", Toast.LENGTH_LONG).show();
}
#Override
public void onTick(long millisUntilFinished) {
tv.setText((millisUntilFinished/1000)+"");
as far as I know - nope, since task killers destroy your app's process causing any running threads to exit
Not while the timer is part of your application. You can of course make a timer that is not part of the application.
How do I stop the media recorder when it comes two minutes in android? I used stMaxduration and info listener, there is no guarantee in the call in the api.
Can anybody tell me any other way to achieve this? Provide code please
Thanks
The best way is to implement a countdown timer where you need to execute something after definite times. Below is the code. Here 120000 milliseconds represents two minutes and 1000 milliseconds represents 1 second "MyCount(120000, 1000)"
MyCount counter = new MyCount(120000, 1000);
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
//do your stuff here
}
#Override
public void onTick(long millisUntilFinished) {
}
}
Run using the threads when you stop the thread the media player will gets stop.
snippet:
Runnable r = new Runnable()
{
public void run()
{
mp1.start();
}
};
new Thread(r).start();
I am using a countdown timer to perform a repeating task. I want to be sure what I'm doing is valid since I'm not sure if the countdown timer object gets destroyed when it times out. Same question applies if I call the cancel method. Here is my code:
public class MyCount extends CountDownTimer
{
public MyCount(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
new myAsyncTask().execute();
this.start();
}
#Override
public void onTick(long millisUntilFinished)
{
}
}
What you are doing is fine. The timer object will be freed only when the object is no longer reachable. That is, you can call timer.start() repeatedly on the same object as you are doing. timer.cancel() also does not free the object. You can call timer.cancel() and then call timer.start() to reset the timer, all on the same object.