I am trying to take the recent time and show it in a TextView. And using a Timer and timerTask to get current time every second and update the UI using post method of View object.
Below is my code:
public class MainActivity extends Activity implements OnClickListener
{
Button btnStart,btnStop;
TextView txtRcntTime;
Calendar c;
private Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize(); // method where i initialized all components
c = Calendar.getInstance();
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonStart:
start();
break;
case R.id.buttonStop:
stop();
break;
}
}
public void stop()
{
if (timer!=null){
timer.cancel();
timer = null;
}
}
private void start()
{
if(timer != null)
{ timer.cancel(); }
TimerTask task = new TimerTask() {
#Override
public void run() {
SimpleDateFormat df1 = new SimpleDateFormat("hh-mm-ss a");
String formattedDate1 = df1.format(c.getTime());
updateView(formattedDate1);
}
};
timer = new Timer(true);
timer.schedule(task, 0, 1000);
}
public void updateView(final String t)
{
txtRcntTime.post(new Runnable() {
String t2 = t;
#Override
public void run()
{ txtRcntTime.setText(t2); }
});
}
}
Result is showing the time for the first time when button is clicked but not updating.
problem:
c = Calendar.getInstance();
It is actually updating but you are only getting one instance of the calendar thus giving you the same time when the timer task is called every 1 second.
solution:
update the calendar by getting the instance of it each second
TimerTask task = new TimerTask() {
#Override
public void run() {
SimpleDateFormat df1 = new SimpleDateFormat("hh-mm-ss a");
Calendar cal = Calendar.getInstance();
String formattedDate1 = df1.format(cal.getTime());
updateView(formattedDate1);
}
};
Related
I have requirement to implement, In my activity, I receive an OTP for login, the OTP has be expired in 90 seconds.
Questions
1> Is Alarm Manager is best way to implement the 90 second time expiry?
2> If I have received OTP and same time I receive a call and when call is ended after 90 seconds and when i come back to original
activity , user should be shown a pop up saying OTP has been expired?
any help will be appreciated.
Thanks
Use CountDownTimer
new CountDownTimer(90000, 1000) {
public void onTick(long millisUntilFinished) {
Log.d("seconds remaining: " , millisUntilFinished / 1000);
}
public void onFinish() {
// Called after timer finishes
}
}.start();
You can use TimerTask like below sample :
public class AndroidTimerTaskExample extends Activity {
Timer timer;
TimerTask timerTask;
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
//onResume we start our timer so it can start when the app comes from the background
startTimer();
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
timer.schedule(timerTask, 5000, 10000); //
}
public void stoptimertask(View v) {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
//get the current timeStamp
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
//show the toast
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);
toast.show();
}
});
}
};
}}
You can change start and stop of Task as per your call and initialise too whenever you want.
I want the activity time to update every minute, not just on create. This is the code I have so far:
public class MainActivity extends ActionBarActivity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TimeZone tz = TimeZone.getTimeZone("Atlantic/St_Helena");
Calendar c = Calendar.getInstance(tz);
String timez = String.format("Year "+"%02d" , c.get(Calendar.YEAR))
// Display formattedDate value in TextView
TextView time = new TextView(this);
time.setText("Its"+timez+" PM"+"\n\n"+"Ants stretch when they wake up in the morning.");
time.setGravity(Gravity.TOP);
time.setTextSize(20);
setContentView(time);
}}
Try to use a runnable and a handler like this:
handler=new Handler();
new Runnable() {
public void run() {
c = Calendar.getInstance(tz);
timez = String.format("Year "+"%02d", c.get(Calendar.YEAR));
time.setText("Its"+timez+" PM"+"\n\n"+"Ants stretch when they wake up in the morning.");
time.setGravity(Gravity.TOP);
time.setTextSize(20);
setContentView(time);
handler.postDelayed(this, 60000);
}
}.run();
This is the code i have so far
new Timer().schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
}
},0,1000);
What i want to do is replace the ,0,1000); at the end with something like 60 minutes - current time.
I have no idea to why I am recieving this error. With all the example I've seen with the class TimerTask , this should not cause a problem.
public class CountUp extends AppCompatActivity {
EditText upText = (EditText) findViewById(R.id.Up);
int counter = 0;
float StartTime = 0;
float OffsetTime = 1000; //Offset time is the time between event. 1000 is going to be our milliseconds (1 second)
TimerTask tt = new TimerTask() {
#Override
public void run() {
upText.setText(counter);
counter++;
}
};
public void CountUp(View view){
try {
Timer timer = new Timer();
timer.scheduleAtFixedRate(tt,StartTime,OffsetTime); <--- //This is were I am receiving an error
}catch (Exception e){
}
}
Replace your whole code with this one:
public class CountUp extends AppCompatActivity {
EditText upText;
TimerTask tt;
int counter = 0;
//startTime and offsetTime must be long and not float.
long startTime = 0;
long offsetTime = 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Change this to your current layout.
setContentView(R.layout.main_activity);
upText = (EditText) findViewById(R.id.Up);
tt = new TimerTask() {
#Override
public void run() {
upText.setText(String.valueOf(counter));
counter++;
}
};
}
public void countUp(View view) {
try {
Timer timer = new Timer();
timer.scheduleAtFixedRate(tt, startTime, offsetTime);
} catch (Exception e) {
}
}
}
I'm trying to make an alarm app for android the first thing that i should do is to continuously get the current time of system so i did this but it only gets the current second and no more ,, any help ?
here is the code :
public class MainActivity extends Activity {
public Button time;
public TextView secondview;
public static int hours, mins, secs;
Handler main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (Button) findViewById(R.id.button1);
secondview = (TextView) findViewById(R.id.textView2);
new Thread(new Runnable() {
#Override
public void run() {
secondview.setText(String.valueOf(secs));
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
main = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Calendar mycal = Calendar.getInstance();
hours = mycal.get(Calendar.HOUR);
mins = mycal.get(Calendar.MINUTE);
secs = mycal.get(Calendar.SECOND);
secondview.setText(String.valueOf(secs));
}
};
}
}
Handler and Thread are bad choice for this type of problem.
To make an alarm app, use AlarmManager.
You should carefully choose which type of timer to use. (ELAPSED_REALTIME, RTC, ....)
For alarm app, RTC_WAKEUP is good choice.
And Android developer site has training how to use AlarmManager.
quote:
// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
There's another example for some use case.
Android provide two ways of service,one is bind to activity,when activity destoyed,the service also,another can achieve the same function,but it have no connoction with activity. and here we need use the second one!
public class MainActivity extends Activity {
private Button startService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.startService);
startService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CountService.class);
startService(intent);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
Intent intent = new Intent(MainActivity.this,CountService.class);
stopService(intent);
}}
public class CountService extends Service{
private int seconds=0;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
new Thread(new Runnable() {
#Override
public void run() {
while(seconds!=-1){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("TIME","Time "+seconds);
//handle seconds use Calendar and AlarmManager
seconds++;
}
}
}).start();
}
#Override
public void onDestroy() {
super.onDestroy();
}}
I found this from somewhere. It uses timertask.
public void updateTimeOnEachSecond() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
c = Calendar.getInstance();
Log.d("myapp", "time changed");
hrs = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
sec = c.get(Calendar.SECOND);
runOnUiThread(new Runnable() {
#Override
public void run() {
txt_hrs.setText(String.valueOf(hrs));
txt_mins.setText(String.valueOf(min));
txt_sec.setText(String.valueOf(sec));
}
});
}
}, 0, 1000);
}
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);
}
};
}