Android start/stop repeating Thread after specific time - java

I need a thread repeating after 30 seconds that load data from web service.
i want to stop and start thread onResume and onPause so that it runs when screen is active and disable it when activity paused. Restart on resume.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dataIfInternet(refreshTop);
}
}, 30000);
How to stop it when activity paused.

U can't pause the handler, so u need to cancel it in your onPause and post in again in your onResume
so u probably want something like this:
private Handler myHandler = new Handler();
in your onResume()
Runnable myRunnable = new Runnable()
{
#Override
public void run()
{
dataIfInternet(refreshTop);
}
};
myHandler.postDelayed(myRunnable, 30000);
and in your onPause()
// Cancel the runnable
myHandler.removeCallbacks(myRunnable);
I hope this solves your problem

Related

PostDelayed() inside onFinish() in CountDownTimer

I need to use postDelayed() method inside onFinish() method of the CountDownTimer. I use the following code:
...
public void onFinish() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//do something here after 3 seconds
}
}, 3000);
}
But it does not work. It does not delay.
It's not going to work. You will have to find another way to accomplish your goal. The reason why, is because your post delayed is ran on a different thread then the onFinish. onFinish will run on the UI tread. After onFinish is ran the class will be closed out and the postDelayed thread will be no more.

Running 2 methods with X amount of time difference?

I have a mic, which I want to activate for 5 seconds and then get that data. While the activity thread is still running.
Method 1: Is the activation of mic.
Method 2: Is for collecting the .amr/.mp3 output from the file.
And this will only happen one time.
I want that my activity should call method 1 at the start and after time X(or 5 seconds), it should call the other method. I am able to do this manually by using 2 buttons, one for record and other for save the file. But I am unable to do this automatically.
Thanks in advance.
Maybe something like:
firstMethodCall();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
secondMethodCall();
}
}, 5000);
Or better:
firstMethodCall();
new Timer().schedule(new TimerTask() {
#Override
public void run() {
secondMethodCall();
}
}, 5000);
Create a Thread.
Call first method, Thread.sleep() for some time
and Then Call Second Method.
Example:
Thread thread=new Thread(){
public void run(){
firstMethod();
Thread.sleep(time);
secondMethod();
}
};
//on button click
thread.start();

Android Timer in Background Service not updating on time

I am trying to update a user location to our REST WebService every minute. I have tried using a Timer and a Runnable with Handler. Both of these are having problems.
Both work fine on my Emulator, although on our test devices the timer and Runnable are not running every minute, they update sporadically, sometimes within 1 second of each other, sometimes 5 minutes later, and anywhere in between..
Does anyone know why this might happen?
Context context;
Handler handler = new Handler();
#Override
public void onCreate() {
super.onCreate();
context = this;
handler.postDelayed(runnable, 0);
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
updateLocation(context);
handler.postDelayed(this, 60000);
}
};

How to prevent multiple ScheduledExecutorServices from being created upon reopening activity

My issue is that upon opening a certain activity in my project, I initialize a ScheduledExecutorService that sends an Intent to an IntentService class every 20 seconds.
Now when I first open the activity that contains the ScheduledExecutorService, the Intent fires once every 20 seconds as planned.
The issue arises when I exit the activity (staying in the app) and then reenter the activity. This results in the Intent being sent twice in a 20 second window, and I figure it has to do with my creating a new ScheduledExecutorService in the onResume of my activity.
How do I ensure that there is only one instance of ScheduledExecutorService at any given time?
Relevant code is below:
#Override
public void onResume() {
super.onResume();
ScheduledExecutorService scheduleIntentSender = Executors.newScheduledThreadPool(1);
scheduleIntentSender.scheduleAtFixedRate(new Runnable() {
public void run() {
sendIntent();
}
}, 0, 20,TimeUnit.SECONDS);
mDownloadStateReceiver =
new DownloadStateReceiver();
// Registers the DownloadStateReceiver and its intent filters
LocalBroadcastManager.getInstance(this).registerReceiver(
mDownloadStateReceiver,
testIntentFilter);
}
I suggest not doing that in your Activity because it's intended to display a UI. Do that in a Service instead. You can launch a Service in onStart and track the state of the executor in your Service, whether it's launched or not. Service is good because it's a background component which is not tied to UI at all. It will not be affected during screen rotations etc.
You should cancel the previous ScheduledExecutorService after closing activity:
ScheduledExecutorService scheduleIntentSender = Executors.newScheduledThreadPool(1);
final ScheduledFuture schedulHandler = scheduleIntentSender.scheduleAtFixedRate(new Runnable() {
public void run() {
sendIntent();
}
}, 0, 20,TimeUnit.SECONDS);
//Call schedulHandler.cancel(true) to cancel scheduleIntentSender in onDestroy()

Save timer time and resume on onResume

I'am a beginner.
I have a timer in my puzzle game. But there is a bug. When the user turns off the screen, the timer doesn`t stop. If user turns screen on again he can see game over screen and this is not good from UX perspective.
Here is my code for timer
private void initializeProgressBar() {
//initialize progressbar
progress = ApplicationConstants.GAME_TIME;
mProgress = (ProgressBarDetermininate) findViewById(R.id.progressDeterminate);
mProgress.setMax(progress);
mProgress.setProgress(progress );
timer = new Timer();
progressBarUpdateTask = new ProgressBarUpdateTask();
timer.schedule(progressBarUpdateTask, 20, 20);
}
class ProgressBarUpdateTask extends TimerTask {
#Override
public void run() {
runOnUiThread(new Runnable(){
#Override
public void run() {
progress-=1;
if(progress==0)
{
TimeOver();
}
mProgress.setProgress(progress);
}
});
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
this.timer.cancel();
}
I can`t figure out how to fix this onResume, because now timer stops when user turn off the screen, but doesnt resume when user turn on screen.
Then you should pause the timer in your onPause() method not cancel it and in the onResume() method you could restart the timer with the seconds which were left, before the screen has been turned off. For further informations about the lifecycle of an activity have a look at the Activity Lifecycle.
But what I think you really need is the CountDownTimer class not the Timer class.
look into CountDownTimer. The timer you are using now is not supposed to really be used like that. Unfortunately there is no pause so onTick save a variable to know what the timer is currently at, then on pause cancel the timer. then in onresume create a new time and set the time to the variable you are using to keep track of the last timer.
http://developer.android.com/reference/android/os/CountDownTimer.html

Categories