Getting current time continuously android - android

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

Related

How can i change a textView's content each day at specific time automatically?

I have a List of quotes and i want to show a random quote from that List each day in the morning automatically. I want to implement that in a TextView inside a fragment. I played with the Calendar class but it doesnt work automatically because the instance is created only when the user opens the app. Any suggestion or help to do that with kotlin please!
In your onCreate start a timer (https://developer.android.com/reference/java/util/Timer) with scheduleAtFixedRate(TimerTask task, long delay, long period)
set delay to the time until 00:00. And the period to one day. In the task you can update the textview. Hope that helps. If you have trouble with implementing this, I would be happy to help you.
Here is the code. Havent tested it but should work.
public class MainActivity extends AppCompatActivity {
final Timer t = new Timer();
final long ONE_DAY = 24 * 60 * 60 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateTextView();
}
#Override
protected void onStart() {
super.onStart();
// construct tomorrow midnight
Calendar date = new GregorianCalendar();
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
date.add(Calendar.DAY_OF_MONTH, 1);
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
updateTextView();
}
});
}
}, date.getTime(), ONE_DAY);
}
#Override
protected void onStop() {
super.onStop();
t.cancel();
t.purge();
}
private void updateTextView() {
//... do your update here
}
}

How to to continue update texview on countdown timer running on background?

I have this countdown timer which i modified to count up.The timer will keep on running at the same time give percentage on a textview (tvp). below are the code.
timer = new CountUpTimer(date3) {
public void onTick(int secondt) {
simpleDateFormat = new SimpleDateFormat ("HH:mm:ss");
tv_timer.setText(simpleDateFormat.format (secondt));
t1 = date3 - date;
percentage = Math.round (secondt/t1 *100);
tvp.setText ( percentage+"%" );
}
};timer.start();
The timer is running on background which i use services and broadcast receiver and it work just fine.
The problem is, the percentage textview is not updating and running and stuck on the last value after pressing back button. below are the runnable code used to update percentage textview.
getActivity ().runOnUiThread(new Runnable() {
#Override
public void run() {
tvp.setText ( percentage + "%" );
}
});
below are my timer service code
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
intent = new Intent(str_receiver);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
mHandler.post( () -> {
timerprogressupdate ();
} );
}
}
public String timerprogressupdate() {
fn_update ( IFTimer.secondt );
fn_updatep ( IFTimer.percentage );
return timerprogressupdate();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("Service finish","Finish");
}
private void fn_update(long str_time){
intent.putExtra("time",str_time);
sendBroadcast(intent);
}
}
broadcast receiver
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String strDate = intent.getStringExtra("time");
}
};
I need the percentage textview updating and running after i press back button. Anyone have a solution on this? Appreciated if anyone could help me.

Is there anything wrong with this code where i am using Timer

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

How to show toast message after a period of time in android?

I am showing toast message after every 20 seconds from current time but if I going out the app it is not working. Here is my code:
public class Main extends Activity {
final static private long ONE_SECOND = 1000;
final static private long TWENTY_SECONDS = ONE_SECOND * 20;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
Log.i("Receive message in every five seconds", "message");
}
};
registerReceiver(br, new IntentFilter("com.authorwjf.wakeywakey"));
pi = PendingIntent.getBroadcast(this, 0, new Intent(
"com.authorwjf.wakeywakey"), 0);
am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(),
TWENTY_SECONDS, pi);
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
}
My question is if the app is not running but still it can show toast message? How can it possible in android?
you must create a Class Updater which contain a Handler
it will be executed periodically (you can define this periode) like that:
import android.os.Handler;
public class Updater {
private Handler mHandler = new Handler();
private Runnable mStatusChecker;
final static private long TWENTY_SECONDS = 20000;
private int UPDATE_INTERVAL = TWENTY_SECONDS;
public Updater(final Runnable updater){
mStatusChecker = new Runnable() {
#Override
public void run() {
updater.run();
mHandler.postDelayed(this, UPDATE_INTERVAL);
}
};
}
public Updater(Runnable updater, int interval){
this(updater);
UPDATE_INTERVAL = interval;
}
public void startUpdates(){
mStatusChecker.run();
}
public void stopUpdates(){
mHandler.removeCallbacks(mStatusChecker);
}}
than create a service "ServiceOn" :
public class ServiceOn extends Service {
Updater updater = new Updater(new Runnable() {
#Override
public void run() {
// put your code here
// toast or what you want
}});
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
updater.startUpdates();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
updater.stopUpdates();
super.onDestroy();
}}
and finally in your activity you can call this service:
context.startService(new Intent(context, ServiceOn.class));
this will work for every 20 seconds even if the app stop running
Try This Code i hope its working...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Handler h=new Handler();
final Runnable r=new Runnable() {
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"Example OF Practicle 8",Toast.LENGTH_SHORT).show();
}
};
Timer t=new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
h.post(r);
}
},2000, 5000);
You can use setTimeout
setTimeout( function(){
toastr.clear(); // User to Clear the Toast Message Popup
}, 1000 ); // We can set our own time interval to disappear the popup
Hope it will help you

How to display a timer in activity in Android

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

Categories

Resources