Android Timer And UI Thread - android

I inflate a TableRow like this:
final TableRow tr1 = (TableRow)LayoutInflater.from(this).inflate(R.layout.attrib_row_survey, null);
tr1.setOnTouchListener(this);
tl1.addView(tr1);
This is how I do my counter:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
((TextView)tr1.findViewById(R.id.textView2)).setText("Seconds Remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
((TextView)tr1.findViewById(R.id.textView2)).setText("DONE");
}
}.start();
The problem is, when I run this timer and show it in the row, the UI is very slow and the timer lags. When I do a view.setBackGroundColor(Color.BLACK) in the onTouchListener() and I click on it, it lags.

protected static void startTimer() {
isTimerRunning = true;
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
elapsedTime += 1; //increase every sec
mHandler.obtainMessage(1).sendToTarget();
}
}, 0, 1000);
}
public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
StopWatch.time.setText(formatIntoHHMMSS(elapsedTime)); //this is the textview
}
}

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?

Sequence of actions with delays android

I'm trying to get my app to display a sequence of images, 1 second after the other. Currently my java looks like this:
arrow1.setVisibility(View.VISIBLE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
arrow1.setVisibility(View.INVISIBLE);
arrow2.setVisibility(View.VISIBLE);
}
}, 1000);
handler.postDelayed(new Runnable() {
public void run() {
arrow2.setVisibility(View.INVISIBLE);
arrow3.setVisibility(View.VISIBLE);
}
}, 1000);
I'm not getting any errors, but it's also not working as I intended. Arrow2 is not displaying at all, the app is going straight from arrow1 to arrow3 with a slight delay. Is my second handler.postDelayed(new Runnable() function being overriden? How should I best go about having a delay in this scenario?
You can try like this,
private static final int TotalLoopCount = 2;
private int count = 0;
private int mCurrentLoopCount = 0;
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Your code
}
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(runnable, 0);
}
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnable);
}
Runnable runnable = new Runnable() {
#Override
public void run() {
arrow1.setVisibility(View.INVISIBLE);
arrow2.setVisibility(View.INVISIBLE);
arrow3.setVisibility(View.INVISIBLE);
if(count == 0) {
arrow1.setVisibility(View.VISIBLE);
} else if(count == 1) {
arrow2.setVisibility(View.VISIBLE);
} else {
arrow3.setVisibility(View.VISIBLE);
}
count++;
if(count == 3) {
count = 0;
mCurrentLoopCount++;
}
if(mCurrentLoopCount < TotalLoopCount) {
handler.postDelayed(runnable, 3000);
}
}
};
You can also use CountDownTimer as below. See official doc for more details.
Set millisInFuture to countDownInterval*3 for 3 images and set countDownInterval for delay between images.
long countDownInterval = 1000; // 1sec interval
long millisInFuture = countDownInterval*10; // 10sec total time
new CountDownTimer(millisInFuture, countDownInterval) {
public void onTick(long millisUntilFinished) {
arrow1.setVisibility(millisUntilFinished < millisInFuture ? View.VISIBLE:View.INVISIBLE);
arrow2.setVisibility(millisUntilFinished > 0 ? View.VISIBLE:View.INVISIBLE);
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();

Android Timer Task Issue

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

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

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