i want to run asynk task in every 5 seconds till 5 minuts, how can i do this ?
i am able to run asynk task in every 5 seconds but can no limit 5 minuts
public void callAsynchronousTask() {
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 {
new CheckTxnStatusSTResult().execute(final_verification_card);
Log.d("dinesh","execute in every five seconds"+ final_verification_card);
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 15000);
}
Just you can do like this
public void FunctionName() {
new CountDownTimer(Total_time, 1000) {
#Override
public void onTick(long millisUntilFinished) {
MyUtils.Log("execute in every one seconds");
// Display Data by Every Ten Second
}
#Override
public void onFinish() {
// Call Other function on Function
}
}.start();
}
Related
I'm a newer programmer and this is my first project but I'm having a bit of trouble in making a proper loop with three timers that are supposed to run one after the other. I managed to get the objects to hold the values they are supposed to within the loop but for some reason, the timer isn't displaying in the text field like it should.
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("mTimer:", String.valueOf(mTimer));
Log.i("mReps:", String.valueOf(mReps));
Log.i("Flexion:", String.valueOf(flexionTimer));
Log.i("Hold:", String.valueOf(holdTimer));
Log.i("Extension:", String.valueOf(extensionTimer));
for (int iter = 0; iter < mReps; iter++) {
Log.i("Loop:", String.valueOf(iter));
final Timer workingFlexionTimer = new Timer();
workingFlexionTimer.schedule(new TimerTask() {
int counter = ((int) flexionTimer / 1000);
#Override
public void run () {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPhase.setText("Flexion");
mCountDownTimer.setText("" + String.format(String.valueOf(counter + 1)));
}
});
if (counter-- == 0) {
workingFlexionTimer.cancel();
}
}
}, 0, 1000);
final Timer workingHoldTimer = new Timer();
workingHoldTimer.schedule(new TimerTask() {
int counter = ((int) holdTimer / 1000);
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPhase.setText("Hold!!!");
mCountDownTimer.setText("" + String.format(String.valueOf(counter + 1)));
}
});
if (counter-- == 0) {
workingHoldTimer.cancel();
}
}
}, flexionTimer, 1000);
final Timer workingExtensionTimer = new Timer();
workingExtensionTimer.schedule(new TimerTask() {
int counter = ((int) extensionTimer / 1000);
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPhase.setText("Extension");
mCountDownTimer.setText("" + String.format(String.valueOf(counter + 1)));
}
});
if (counter-- == 0) {
workingExtensionTimer.cancel();
}
}
}, (flexionTimer + holdTimer), 1000);
}
I'm kind of at a loss at this point and any suggestion would be appreciated.
Use handler
private void Timer() {
handler = new Handler();
Run =new Runnable() {
#Override
public void run() { //Do something after 10 sec
Toast.makeText(getActivity(), "Timer called!",Toast.LENGTH_LONG).show();
Timer(); // Do again
}};
handler.postDelayed(Run , 10000); // 10 sec
}
UPDATE
For timers I always do:
final TextView textView = (TextView)findViewById(R.id.textView);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
int counter = 10;
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(""+counter);
}
});
if (counter-- == 0){
timer.cancel();
}
}
}, 0, 1000);
timer.schedule(new TimerTask() {
int counter = 10;
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(""+counter);
}
});
if (counter-- == 0){
timer.cancel();
}
}
}, 10000, 1000);
timer.schedule(new TimerTask() {
int counter = 10;
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(""+counter);
}
});
if (counter-- == 0){
timer.cancel();
}
}
}, 20000, 1000);
For more info check this
In the link...
public void schedule(TimerTask task, long delay, long period)
The above code. Start the run() without delay.
long delay = 0;// in ms
long period = 1000;// in ms
So every 1000ms call the run() and counter--. When counter = 0 cancel.
If you want to run, the one after the other, put delay.
UPDATE
Now the first will run immediately, the second will wait 10000ms (10s) and will run, finaly the third will wait 20000ms (20s) and then run.
The first timer flexionCountDownTimer was started in a loop, which means it will be started more than one time if mReps is greater than 1. This might leads to 2nd run of flexionCountDownTimer before the 1st run finished. Is this your expected behavior?
My app needs tracking of real time so I need a button that needs to trigger every 5 seconds but I have no idea how to do it. Can you teach me how?
I want that in every 5 seconds that AsyncTask will be triggered.
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap postLoc = new HashMap();
postLoc.put("txtLat", tvLat.getText().toString());
postLoc.put("txtLng", tvLong.getText().toString());
postLoc.put("txtOwner", pref.getString("username","").toString());
PostResponseAsyncTask taskLoc = new PostResponseAsyncTask(getActivity(), postLoc,false, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, tvLat.getText().toString());
Log.d(TAG, tvLong.getText().toString());
Intent i = new Intent(getActivity(),GPS_Service.class);
getActivity().startService(i);
}
});
taskLoc.execute("http://carkila.esy.es/carkila/locationUpdate.php");
}
});
I think this code might be useful to trigger the code every 5 second
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
public void onCreate() {
super.onCreate();
startTimer();
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
timer.schedule(timerTask, 0, 5000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//code to run after every 5 seconds
}
});
}
};
}
Create a method like this and call the method on button click and also call the method by using a handler like this:
mRunnable = new Runnable() {
public void run() {
public void toBecalled_Every_5_Second();
mHandler.postDelayed(mRunnable, 5000);
}
};
mHandler.postDelayed(mRunnable, 5000);
public void toBecalled_Every_5_Second(){
PostResponseAsyncTask taskLoc = new PostResponseAsyncTask(getActivity(), postLoc,false, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, tvLat.getText().toString());
Log.d(TAG, tvLong.getText().toString());
Intent i = new Intent(getActivity(),GPS_Service.class);
getActivity().startService(i);
}
});
taskLoc.execute("http://carkila.esy.es/carkila/locationUpdate.php");
}
so it will call the method every 5 second and the a sync task will execute....
I would like to have a CountDownTimer which will trigger the button click function after every 5 seconds.
CountDownTimer mTimer = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished) {
// Do nothing
}
public void onFinish() {
btnStart.performClick();
this.start(); // Restart
}
}.start();
You can use Timer with TimerTask and Handler to update the result to main thread i.e your UI.
Something like this:
Timer timer;
TimerTask timerTask;
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
private void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run process
handler.post(new Runnable() {
public void run() {
/**************************/
/** Do your process here **/
/**************************/
}
});
}
};
}
private void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, start run TimerTask then run every 5000ms i.e 5 seconds.
timer.schedule(timerTask, 0, 5000); //
}
private void stopTimerTask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
Insert your processing code in Handler.post(). Then start the trigger by calling startTimer(). To stop the trigger, just call stopTimerTask().
I need a timer when Loaded ListView . Like " Waiting [(Timer) 42] Seconds for buy elements " I want to show users Textview Like it. I can't use Thread in ListView...
I get Error from runOnUiThread. Why ? I cant use timer In Listview.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final TextView LblTime;
inflater=(LayoutInflater)Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.test,parent,false);
LblTime=(TextView)view.findViewById(R.id.LblFragmentAnaListViewKalanSure );
Timer T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Context.getApplicationContext().runOnUiThread(new Runnable() {
#Override
public void run() {
long Time= MyTime.get(position).getTime() - (new Date()).getTime();
long Sec= Time/ 1000 % 60;
long Min= Time/ (60 * 1000) % 60;
LblTime.setText(Min+":"+Sec);
}
});
}
}, 1000, 1000);
return view;
}
Try this.. for call atfer 42 sec..
(new Handler()).postDelayed(new Runnable() {
public void run() {
// do you want
}
}, 42000);
if every sec you need to than do it..
This is using the Handler
Initialize..
Handler handler = new Handler();
Import
import android.os.Handler;
call this for..
handler.postDelayed(yourtask,42*1000);
private Runnable yourtask = new Runnable() {
public void run() {
// Run your code..
handler.removeCallbacks(yourtask);
handler.postDelayed(yourtask, 42*1000); // again start...
}
};
This is Using Timer every one second....
final Handler handler = new Handler();
Timer timer = new Timer();
private int DELAY = 1000 * 60 * 1;
call this
timer.scheduleAtFixedRate(doAsynchronousTask, 0, DELAY);
in class
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
// your code
}
});
}
};
Try to use CountDownTimer it works perfectly in UI thread. All you need is just to initiate it in your code like that:
timer = new CountDownTimer(MS_TILL_COMPLETE, TICK_OFFSET) {
#Override
public void onTick(long l) {
//Repeating every TICK_OFFSET
}
#Override
public void onFinish() {
//Called after MS_TILL_COMPLETE
}
}.start();
Instead of timer try to use CountDownTimer
new CountDownTimer(10000, 20000) {
#Override
public void onTick(long millisUntilFinished) {}
public void onFinish() {
}
}.start();
Using Android studio, I am trying to make an app that gets data from a web-service and display the data and updates the view every 5 sec or when the data on the web-service changes. With this I am trying to change the colours on some button based on an int, the int changes and the color on the button changes when I apply buttons(); to another button and then presses it but I want it to update by itself.
When I used a while loop the app gets stuck
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
buttons();
}
});
The runOnUiThread is placed in the onCreate.
using run on UI thread will cause your UI to freeze , try using a timer task instead .
example :
#Override
public void StopTimerTask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void StartTimer() {
timer = new Timer();
initializeTimerTask();
int UpdateTime = Integer.valueOf(UserSettings.getString("Update", "60000"));
timer.schedule(doAsynchronousTask, 0, YOURTIME);
}
public void initializeTimerTask() {
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
myHandler.post(new Runnable() {
public void run() {
YOUR LOGIC HERE
}
});
}
};
}
doing this where u just put another class into main activity was succesful only problem is that it have to be in my main class
public class updategui extends TimerTask {
Activity context;
Timer timer;
public updategui(Activity context, int seconds) {
this.context = context;
timer = new Timer();
timer.schedule(this,
seconds * 1000, // initial delay
seconds * 1000); // subsequent rate
}
#Override
public void run() {
if(context == null || context.isFinishing()) {
this.cancel();
return;
}
context.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
buttons();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}}
I would like the Timer to start when I turn ToggleButton ON and to cancel when I turn it OFF. It works, but when I try to start it over again after being cancelled I get an error. Where is the problem? Here is the code:
final ToggleButton btnLive = (ToggleButton)findViewById(R.id.live);
btnLive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnLive.isChecked()) {
timer = new Timer();
timer.schedule(timerTask, 5*1000, 5*1000);
} else {
timer.cancel();
timer.purge();
timer = null;
}
}
});
EDIT: It works with calling timer that way:
timer.schedule(new TimerTask(){
private Runnable runnable = new Runnable() {
public void run() {
new Something().execute();
}
};
public void run() {
handler.post(runnable);
}
}, 5*1000, 5*1000);
Can you explain me why first method is not working? Is it range problem?
Use this type of code and check.
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask()
{
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
}
}, 5000, 500);