Android Timer Task Issue - android

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();

Related

Can't get coundown timer to work or display in my program

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?

Button to trigger every 5 seconds

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().

Timer stop after one minute

I made a Timer and I want to stop it when it reaches to 60 seconds(1 min).
here's the code:
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
myTextView.setText("timer=" + String.valueOf(TimeCounter));
TimeCounter++;
}
});
}
}, 0, 1000);
int I=60;
if (TimeCounter == I) {
-------------- stop the timer here ----------------
}
}
how can I do it?
you will probably need to move the stopping condition inside your task... so it looks more less like this:
final Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (TimeCounter == I) {
t.cancel();
return;
}
myTextView.setText("timer=" + String.valueOf(TimeCounter));
TimeCounter++;
}
});
}
}, 0, 1000);
Remember to define earlier:
int I=60;
Also, you would probably need to mark Timer as final (just as I did in code).
try below code to stop timer :-
if (TimeCounter == I) {
t.cancel();
}
also see below link:-
How to stop immediately the task scheduled in Java.util.Timer class
You can use CountDownTimer, maybe this is a simpler solution:
int Time = 0;
public class OneMinuteCountDownTimer extends CountDownTimer {
public OneMinuteCountDownTimer (long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
myTextView.setText("timer="+Time+" time finished");
Time=0;
}
#Override
public void onTick(long millisUntilFinished) {
Time++;
myTextView.setText("timer="+Time);
}
}
}
Make the CountDownTimer global and call it when You want to start the CountDownTimer:
private OneMinuteCountDownTimer countDownTimer;
private final long startTime = 60 * 1000;
private final long interval = 1 * 1000;
inside onCreate (EDIT):
countDownTimer = new OneMinuteCountDownTimer(startTime,interval);
countDownTimer.start();
and cancel it, if You want to cancel it before one minute:
countDownTimer.cancel();

How Automatically Countdown Timer in Android?

I'm working with timer function in Android, I have the code of 1 to up timer. Please help me make it a countdown timer without clicking a button?
public class MainActivity extends Activity {
public int time = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = (TextView) findViewById(R.id.main_timer_text);
tv.setText(String.valueOf(time));
time += 1;
}
});
}
}, 0, 1000);
}
You can use CountDownTimer for this
new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilEnd) {
mTextView.setText(String.valueOf(millisUntilEnd / 1000));
}
public void onFinish() {
mTextView.setText("done");
}
}.start();
This will update your time TextView each second for 20 seconds.

Automatic Scrolling View pager page with few interval

I have used android view pager to display images and text now what i want is that smothly scrolling pages after few seconds and with animation?
Its works but not smothly viewpager pages scroll.
Timer call
mCountDownTimer = new MyCountDownTimer(4000, 1000);
mCountDownTimer.start();
.
private static MyCountDownTimer mCountDownTimer;
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
System.out.println("Time's up!");
startTimerWithAnim();
}
#Override
public void onTick(long millisUntilFinished) {
System.out.println("mill="+millisUntilFinished / 1000);
}
}
if the 'MyCountDownTimer' call then the 'startTimerWithAnim' method call
public static void startTimerWithAnim() {
if (mCountDownTimer != null)
mCountDownTimer.cancel();
mHandler = new Handler();
mRunnable = new Runnable() {
public void run() {
if (mMemberPagerAdapterList != null) {
if (mPagedGrid.getCurrentItem() == mMemberPagerAdapterList.getCount() - 1)
mPagedGrid.setCurrentItem(0, true);
else if (isFirstTimeCurrentItem) {
mPagedGrid.setCurrentItem(0, true);
isFirstTimeCurrentItem = false;
} else if (isFirstTimeCurrentItem == false)
mPagedGrid.setCurrentItem(mPagedGrid.getCurrentItem() + 1, true);
}
}
};
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(mRunnable);
}
}, 100, 4000);
}
There you go!
class UpdateTimeTask extends TimerTask {
public void run() {
viewPager1.post(new Runnable() {
public void run() {
if(viewPager1.getCurrentItem()<i){
viewPager1.setCurrentItem(viewPager1.getCurrentItem()+1,true);
String abc = String.valueOf(viewPager1.getCurrentItem());
Log.i("timer_+",abc);
}
else
{
viewPager1.setCurrentItem(0,true);
}
}
});
}
}
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(), 2000, 4000);
function doSomething() {
$(document).scrollTop($(document).height());
}
setInterval(doSomething, 5000);
This will scroll to bottom of the page every 5 seconds. This will be useful, if you have auto load content when user scroll down (like Facebook).

Categories

Resources