TimerTask / Handler with Delay getting called Multiple times - android

I need a delay for around 5 seconds. I have tried using Timer using below code :
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
Log.d(TAG,"Timer");
}
}, 4000, 5000);
When i check logs, the Timer is getting printed thrice. If I change time, sometimes it gets printed in log 4 times as well.
I have tried using Handler as well like below :
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.d(Utility.TAG,"Sleep::");
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
But again the log is printing multiple times. I just want to call my method once not multiple times. How can I achieve it ?
EDIT
used handler without thread as well like below :
final Handler h = new Handler();
final int delay = 3000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
//do something
h.postDelayed(this, delay);
Log.d(Utility.TAG,"Sleep ::");
}
}, delay);
But again, Log is getting printed thrice

Your third approach (no Timer, no Thread) is the closest to being correct. It's printing multiple times because the Runnable is re-posting itself every time it runs. If you only want it to run once, remove this line from the run() method:
h.postDelayed(this, delay);

Related

a good way to check if timer already run repeatedly

I'm working on React Native and i want to create a never ending service that run every (n) seconds on Native Modules (on this topic is android).
I've create a simple service like this
public void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.v(TAG, "SERVICE RUN");
try{
if(haveNetworkConnection()){
db.openDB();
if(db.countRowNewStructure()>0){
//send data to server
} else{
Log.v(TAG, "No data should be send to server");
}
} else {
Log.v(TAG, "Ga ada sinyal");
}
} catch (JSONException e){
e.printStackTrace();
}
}
}, 0, 1000);
}
above code run every second to check, but i'm facing the problem when i re-run the service from React Native, the log showing me those code every 0.5 seconds
the simulation may be like :
0----------------1 //seconds
startTimer()
re-run startTimer() conscious
0----------------1 //seconds
startTimer()
//now i have two startTimer() that will run every 1 sec on different interval
I want to keep my startTimer() just running once even I trigger startService() every 0.5 sec.
how can i do that? is it possible?
this may help you. Timmer to perform the certain action in android after the particular time.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask timertaskforsynctime = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// your action here
}
});
}
};
timer.schedule(timertaskforsynctime,5000,10000);// decide the time when it will start and after how much time it will run continusly.
}`
for one time
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// your code that will run after 1 sec
}
}, 1000);
You could make use of the cancel method to cancel the previous Timer.
public class YourModule extends ReactContextBaseJavaModule {
Timer tim = new Timer();
public void startTimer() {
tim.cancel();
tim = new Timer();
tim.scheduleAtFixedRate(
new TimerTask() {
public void run() {
// Run tasks
}
},
0,
1000);
}
}

How to handle handler again enter into same activity?

I created one handler for calling AsyncTask in background when I start the application its working fine when I re-enter into the application it will call two times in for first one and present one, how can I handle that
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
checkandsave();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 300000); //execute in every 60000 ms = 1 minute

Changing text in text view

I am displaying text in textview that changes after a period of time.I want to do this on a loop ie the text reverts to its original and then changes again.Here is the code.
MainActivity.java
qoutes=(TextView)rootView.findViewById(R.id.textView_q);
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
qoutes.setText("I don’t trust words. I trust pictures. – Gilles Peress ");
}
}, 10000);
Handler handler1 = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
qoutes.setText("You don’t take a photograph. You ask quietly to borrow it. – Unknown ");
}
}, 20000);
Try this.
qoutes=(TextView)rootView.findViewById(R.id.textView_q);
int i = 0;
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
if(i%2==0){
qoutes.setText("I don’t trust words. I trust pictures. – Gilles Peress ");
}else{
qoutes.setText("You don’t take a photograph. You ask quietly to borrow it. – Unknown ");
}
i++;
}
}, 10000);
Edit:
Timer timer;
TimerTask timertask;
int i = 0;
qoutes=(TextView)rootView.findViewById(R.id.textView_q);
timer = new Timer();
timertask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(i%2==0){
qoutes.setText("I don’t trust words. I trust pictures. – Gilles Peress ");
}else{
qoutes.setText("You don’t take a photograph. You ask quietly to borrow it. – Unknown ");
}
i++;
}
});
}
};
timer.scheduleAtFixedRate(timertask, 100, 10000);
First, create your String resources and a member variable to keep track of the current text shown. It would be best to store in strings.xml, but for this simple example we'll just use a String array. Also create a Handler as a member variable.
TextView qoutes;
Handler handler = new Handler();
int currentTextPosition = -1;
String[] textArray = new String[]{"I don’t trust words. I trust pictures. – Gilles Peress ",
"You don’t take a photograph. You ask quietly to borrow it. – Unknown "};
Then, in onCreateView():
qoutes=(TextView)rootView.findViewById(R.id.textView_q);
handler.postDelayed(setTextRunnable, 10000);
And, the definition for your Runnable:
Runnable setTextRunnable = new Runnable(){
#Override
public void run() {
if (currentTextPosition < 0 ) {
currentTextPosition = 0;
} else {
currentTextPosition++;
if (currentTextPosition >= textArray.length) {
currentTextPosition = 0;
}
}
qoutes.setText(textArray[currentTextPosition]);
handler.postDelayed(this, 10000);
}
};
This will run every 10 seconds until you stop it, which you can do by calling:
handler.removeCallbacks(setTextRunnable);

[ANDROID]Implementing Delay in Message in HandlerThread

i want to do some stuff on every few seconds in my app, for that purpose , i have implemented HandlerThread & handler via following code
handlerThread = new HandlerThread(getClass().getSimpleName());
handlerThread.start();
handler = new Handler(handlerThread.getLooper(), new Callback() {
#Override
public boolean handleMessage(Message msg) {
//my code here
return l.this.handleMessage(msg);
}
});
I initiate this handler by sending message from onCreate()
I handle the message as follows :
private boolean handleMessage(Message msg) {
switch (msg.what) {
default:
return false;
case MY_MESSAGE:
if(handler_stop==0)
{
checkLauncher();
sendMessage(MY_MESSAGE); // I Send the message from here to make //this continuous
}
}
return true;
}
It's Working fine but it Sends message too fast , i mean constantly , instead i want this message to be sent after 2 or 3 seconds , In Short , i want to repeat task every 2-3 seconds.
How can i do this on above code ? please some one help
First declare one global varialbe for Handler to update the UI control from Thread, like below:
Handler mHandler = new Handler();
Now create one Thread and use while loop to periodically perform the task using the sleep method of the thread.
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);// change the time according to your need
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
Else just add this in your code:
handler.postDelayed(new Runnable(){
public void run() {
// do something
}}, 20000);
Why not to use Handler.sendMessageDelayed? It allows you to schedule your message to be delivered to the Handler with delay that you specify. So your code will look like this:
private boolean handleMessage(Message msg) {
switch (msg.what) {
default:
return false;
case MY_MESSAGE:
if(handler_stop == 0) {
checkLauncher();
sendMessageDelayed(MY_MESSAGE, 2000); // Send message everytime with 2 seconds delay
}
}
return true;
}
hi i have an simple way for doing this
try this
Runnable runnable;
final Handler handler = new Handler();
runnable = new Runnable() {
public void run() {
// HERE I AM CHANGING BACKGROUND YOU CAN DO WHATEVER YOU WANT
_images[i].setBackgroundResource(imageArray[0]);
i++;
handler.postDelayed(this, 1000); // for interval...
}
};
handler.postDelayed(runnable, 1000); // for initial delay..
worked for me hope you will also find it working
thanks
Vote Up if find usefull.

Call method after 5 millisecond

How to call record method after 5 millisecond playing audio with MediaPlayer. I tried something like that but i don't know and i didn't find any good examples to end this.
while(mp.isPlaying()){
if(record=0){
for(int i=0; i<5millisec; i++){ //how to define 5 millisec or is any better solution
}
startRecord();
record=1;
}
}
mp.stop();
mp.release();
mp=null;
5 milliseconds is a very short time period and you can't limit audio output to such duration.
you can use Handler to execute a delayed function but it will not ensure execution at 5 milliseconds after scheduling.
a code for doing that:
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
startRecord();
mp.stop();
mp.release();
}
}, 5);
You can use the method postDelayed.
In the example below I run my routine 100 millis after to call the method.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
barVolume.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
}
},
100);
try this:
//Auto Start after 2 seconds
if(ENABLE_AUTO_START) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
// this code will be executed after 2 seconds
doThis();
}
}, 2000);
}
Perhaps you want to use Thread.sleep?
Like so:
if(record == 0){
Thread.sleep(5);
}
Notice that I used == in the if statement to check for equality, rather than assigning the value of 0 each time, I assume this is what you want.
It is worth mentioning that putting a Thread to sleep will stop it doing anything for the duration that you specify. If this is a UI Thread, then you will effectively "freeze" the UI for that duration, so make sure you are using it appropriately. Hwoever, you example for loop indicates this is exactly the kind of thing you are attempting to do.
You could try using Thread.sleep(5), or, if you don't want to use the UI thread for this, you could use a Timer, or an AsyncTask which triggers a callback after waiting 5ms in the doInBackground() method.
Here is a pretty good example for using Timer:
https://stackoverflow.com/a/4598737/832008
You can also use ScheduledExecutorService
Using an ExecutorService, you can schedule commands to run after a given delay, or to execute periodically. The following example shows a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
public static MediaRecorder mRecorder = new MediaRecorder();
public void startRecording(String fileName) {
if(mRecorder != null) {
try {
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(fileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(StartPhoneCallService.class.getSimpleName(), "prepare() failed");
}
mRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
public void stopRecording() {
if(mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
Now you can call the Handler to play 5 millisecond
private final int recording_time = 5;
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
startRecording("YOUR FILE NAME");
// Stop your recording after 5 milliseconds
stopRecording();
}
}, recording_time );

Categories

Resources