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.
Related
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();
I have written a program for a countdown timer but the countdown starts only on button click , but i want it to start without the button click , can anyone suggest me how to do it without the button click ?
Here is the code for countdown timer
public class MainActivity extends ActionBarActivity {
CountDownTimer countDownTimer;
boolean timehasstarted = false;
Button btnStart;
TextView timer;
long startTime = 30 * 1000;
long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.button1);
timer = (TextView) findViewById(R.id.timer);
timer.setText(timer.getText() + String.valueOf(startTime / 1000));
btnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!timehasstarted) {
countDownTimer.start();
timehasstarted = true;
timer.setText("Stop");
} else {
countDownTimer.cancel();
timehasstarted = false;
timer.setText("Restart");
}
}
});
countDownTimer = new CountDownTimer(startTime, interval) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText("" + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timer.setText("Time's Up!");
}
};
}
Move your timer code to onCreate() method of the Activity instead of the onClick() method
This will start the timer on activity start.
And also you can use timer.cancel() to cancel the timer when the activity is stopped or not currently active
if you want to turn on the countdown after a particular time say after 2 sec then you can use TimerTask for this for exmaple :
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
}
}, 2000);
I want to show timer, with every second. After 20 seconds I want that activity to call itself.
But when I don't display the timer it waits for 20 seconds as I wish to do but as soon as I implement code to display timer it just starts and suddenly stops suddenly.
Here is my code. Please help me out.
public class MainActivity extends Activity {
public int time=20;
Button end;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread timerdisp = new Thread(){
TextView tv = (TextView) findViewById(R.id.timer);
public void run(){
try{
sleep(1000); // sleep for 1 seconds
tv.setText(String.valueOf(time));
time-=1;
if(time==0){
startActivity(new Intent(MainActivity.this,MainActivity.class));
}
run();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
};
timerdisp.start();
);
}
Android provides a better facility of CountDownTimer, may be you should use that. As it provides many inbuilt methods and runs on background thread by default.
You can use onFinish() method to execute your call to the activity.
Here is an example of the same.
Try Below Code:
private long ms=0;
private long splashTime=2000;
private boolean splashActive = true;
private boolean paused=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hides the titlebar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
Thread mythread = new Thread() {
public void run() {
try {
while (splashActive && ms < splashTime) {
if(!paused)
ms=ms+100;
sleep(100);
}
} catch(Exception e) {}
finally {
Intent intent = new Intent(Splash.this, Home.class);
startActivity(intent);
}
}
};
mythread.start();
}
and you can try this also
public class MainActivity extends Activity {
private CountDownTimer countDownTimer;
public TextView text;
private final long startTime = 20 * 1000;
private final long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView1);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(String.valueOf(startTime / 1000));
countDownTimer.start();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Intent intent = new Intent();
intent.setClass(getApplicationContext(),xxxx.class);
startActivity(intent);
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1000);
}
}
}
Use runOnUiThread
This acts as a normal Thread and will not allow your UI to sleep.
and the system will not hang.
or you can also use AsyncTask. I will prefer you using AsyncTask.
Use below code to call the function for every 20 seconds.
private Timer timer;
TimerTask refresher;
timer = new Timer();
refresher = new TimerTask() {
public void run() {
// your code to call every 20 seconds.
};
};
// first event immediately, following after 20 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000*20);
Use below lines to show the time :
package com.example.test;
public class MainActivity extends Activity {
private Long startTime;
public native String getLastShotName();
public native String colorNormal();
public native String flipImage();
public native String forceInvertColor();
public native String getLastTitle();
public native String myMethod();
boolean mbFlip = false;
private Timer timer;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TimerTask refresher;
startTime = System.currentTimeMillis();
handler.removeCallbacks(updateTimer);
handler.postDelayed(updateTimer, 1000);
}
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(updateTimer, 1000);
}
private Runnable updateTimer = new Runnable() {
public void run() {
final TextView time = (TextView) findViewById(R.id.textView1);
Long spentTime = System.currentTimeMillis() - startTime;
Long minius = (spentTime/1000)/60;
Long seconds = (spentTime/1000) % 60;
time.setText(minius+":"+seconds);
handler.postDelayed(this, 1000);
}
};
}
I am trying to change image after 1 second for image view.but its doesn't show any image on screen. following is code.please help.thank you.
code-
public class Shapes extends Activity {
Timer timer = new Timer();
int flag;
String images[]={};
ImageView iv;
static int v[]={R.drawable.round,R.drawable.rectangle};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.shapes);
iv=(ImageView) findViewById(R.id.imageView1);
timer.schedule(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (flag > 1) {
timer.cancel();
timer = null;
} else
iv.setImageResource(v[flag++]);
}
});
}
}, System.currentTimeMillis(), 1000);
}
}
how can i check resource image and change it
Use Handler instead of Timer
Handler handler = new Handler();
Runnable changeImage = new Runnable(){
#Override
public void run(){
if(flag>1)
handler.removeCallbacks(changeImage);
else{
iv.setImageResource(v[flag++]);
handler.postDelayed(changeImage, 1000);
}
}
};
start the first time from oncreate()
public void onCreate(Bundle b){
handler.postDelayed(changeImage, 1000);
}
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
flag++;
if (flag > 1) {
timer.cancel();
timer = null;
}
else
iv.setImageResource(v[flag]);
}
});
}
}, 1000, 1000); // wait 1 second before start.. then repeat every second..
It's because you put System.currentTimeMillis() as delay.
Try replacing that with 0, because the time should start after 0 ms.