I have count down timer in a service.
When I stop the service, will the countdown timer still count? I mean will its onFinished method will be called even if the service has been stopped?
Countdown timer runs in a different thread and the callbacks are executed on the UI thread. Hence you need to manually cancel the timer whenever service is stopped. You can follow Hiren's answer.
private CountDownTimer mCountDownTimer;
on onCreate:
mCountDownTimer = new CountDownTimer(30000,1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
// Your stuff
}
};
mCountDownTimer.start();
on onDestroy:
#Override
protected void onDestroy() {
if(mCountDownTimer!=null){
mCountDownTimer.cancel();
}
super.onDestroy();
}
For stop service:
stopService(Your_Intent_For_Service);
Done
Yes, it would be called. You would end up leaking the service if the count down timer is not a static inner class
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
I have a service as MyService. In my service, I have a global variable: value which is controled by a function control_Value(). The function used to control the value of varialbe value as follows rules:
The time when calling the function is called initial time. At intial time, the value is set as One. After 3 seconds from initial time, the value is set to Zero. The value will maintain Zero until the function is called again.
Based on the rule above, I wrote the control_Value() as follows:
public void control_Value()(){
value="One";
try{
Thread.sleep(3000);
value="Zero";
}
catch{}
}
Do you think Thead.sleep(3000) is a good approach? If not, please give me a better solution. Note that, the above function worked well.
This is my service
public class MyService extends Service {
String value=null;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
#Subscribe
public void onSMSContentReceived(OnSMSReceiverEvent event) {
control_Value();
}
}
Update: The onSMSContentReceived is called automatically when a SMS come to phone.
This is solution using countdown timer from suggestion of TGMCians
//Global variable
private CountDownTimer mCountDownTimer;
//
#Override
protected void onDestroy() {
if(mCountDownTimer!=null){
mCountDownTimer.cancel();
}
super.onDestroy();
}
public void control_Value()(){
mCountDownTimer = new CountDownTimer(3000,1000) {
#Override
public void onTick(long millisUntilFinished) {
value="One";
}
#Override
public void onFinish() {
// Your stuff
value="Zero";
}
};
mCountDownTimer.start();
}
Do you think Thead.sleep(3000) is a good approach?
Never. Service run on application main thread without UI. Application will prompt ANR message in case you hold application main thread for certain seconds.
What to do
If you want to perform operation after certain seconds, then you can use CountDownTimer in your service which has methods onTick & onFinish where onTick hits on regular interval and onFinish hits when time is up.
I'm trying to create a Timer that does something after 5 seconds.
Now in my main activity ( I only got 1 ) I wrote this class:
class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
textFeedback.setText("test");
timer.cancel();
}
}
}
In a function (and also in my mainactivity) I create a timer as new Reminder(5).
After 5 seconds the application crashes.
I don't see whats wrong, because I do it in normal java apps like this.
Not sure where you have initialized textFeedback.
textFeedback.setText("test"); cannot update ui from a timer task. Timer task runs on a non ui thread. Ui can be updated only on ui thread.
Your options use a Handler or runOnUiThread.
Note runOnUiThread is a method of Activity class. Requires Activity Context
More info
Android Thread for a timer
Thanks.
Solved it like this:
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
//textFeedback.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
textFeedback.setText("");
}
}.start();
when the class Remainder is istatiate not know the var textFeedback , becaouse you nees to pass the owmer of the textFeedback
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'm extending the CountDownTimer class to obtain some custom functionality .In onTick() in case some conditions are met I call cancel() , expecting that will be the end of it, however the onTick() callback gets call until the the count down is reached . So how to prevent this from happening ?
CountDownTimer.cancel() method seems to be not working. Here's another thread without a solution Timer does not stop in android.
I would recommend you to use Timer instead. It's much more flexible and can be cancelled at any time. It may be something like that:
public class MainActivity extends Activity {
TextView mTextField;
long elapsed;
final static long INTERVAL=1000;
final static long TIMEOUT=5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextField=(TextView)findViewById(R.id.textview1);
TimerTask task=new TimerTask(){
#Override
public void run() {
elapsed+=INTERVAL;
if(elapsed>=TIMEOUT){
this.cancel();
displayText("finished");
return;
}
//if(some other conditions)
// this.cancel();
displayText("seconds elapsed: " + elapsed / 1000);
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, INTERVAL, INTERVAL);
}
private void displayText(final String text){
this.runOnUiThread(new Runnable(){
#Override
public void run() {
mTextField.setText(text);
}});
}
}
CountDownTimer is also working fine for me, but I think it only works if you call it OUTSIDE of the CountDownTimer implemetation (that is don't call it in the onTick).
Calling it inside also didn't worked.
I tried this code snippet, since most answers are saying you cannot cancel the timer inside its implementation, thus i tried using a handler inside onFinish. Old post but if anyone comes across this its helpful.
new Handler().post(new Runnable() {
#Override
public void run() {
timerTextView.setText("00:" + String.format("%02d", counter));
cancel();
}
});