I want to implement a timer in my application if user click clock in button timer should start from device time and the timer should run when giving pause timer should pause when user click stop timer should stop, Please help me.
for example, now time is 13:20:10 user click means timer should run on this time not from 00, normal timer code I have, but based on the current time it should run.
you can try this. call start()/stop() when you want to start/stop timer. if you want to update UI (Main)Thread use runOnUiThread(https://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)) or handler for update UI Thread
import java.util.Calendar;
int hou=0;
int min=0;
int sec=0;
boolean stopTimer=false;
private void initTimer()
{
Date currentTime = Calendar.getInstance().getTime();
hou=currentTime.getHours();
min=currentTime.getMinutes();
sec=currentTime.getSeconds();
Log.e("Initial Timer ","hou"+hou+ " min"+min+" sec"+sec);
startTimerThread();
}
private void startTimerThread()
{
new Thread()
{
public void run()
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
updateTimer();
}
}.start();
}
private void updateTimer()
{
if(!stopTimer)
{
sec=(((++sec)%60)==0)?0:sec;
min=(sec==0)?(((++min)%60==0)?0:min):min;
hou=(min==0)?((++hou)):hou;
/*hou%=12;*/
Log.e("Update Timer ","hou"+hou+ " min"+min+" sec"+sec);
startTimerThread();
}
}
public void start()
{
initTimer();
}
public void stop()
{
stopTimer=false;
}
you can try this using by using countdowntimer like this :
CountDownTimer timer = new CountDownTimer(1000000000, 1000) {
public void onTick(long millisUntilFinished) {
Calendar c = Calendar.getInstance();
Log.v(TAG , "CountDownTimer : " + c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
}
public void onFinish() {
}
};
timer.start();
on pause you can cancel it like this:
timer.cancel();
i have take three button, first start button click on device time show in textview and it update as per device time. when click on paused button stop time update. and when click on restart time device time when start to stop.
mBtnStartTime?.setOnClickListener {
val someHandler = Handler(mainLooper)
someHandler.postDelayed(object : Runnable {
override fun run() {
mTvTime?.text = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
someHandler.postDelayed(this, 1000)
}
}, 10)
mBtnPaused?.setOnClickListener {
someHandler.removeCallbacksAndMessages(null)
}
mBtnRestart?.setOnClickListener {
someHandler.postDelayed(object : Runnable {
override fun run() {
mTvTime?.text = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
someHandler.postDelayed(this, 1000)
}
}, 10)
}
Related
I have a tune in my android app. I have added a feature that if user selects a time then the tune will repeat until the time ends. I have also added the feature of infinite time but when I run my app goes in ANR (not responding) mode.
if(tinydb.getString("timer").equals("infinity"))
{
boolean valid = true; //Here i want to play the tune for infinite time
while(valid)
{
water_player = MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.start();
}
}
else
{
while(!timerText.equals("0h: 0m: 1s")) //Here i want to play the tune until the timer gets zero
{
water_player = MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.start();
}
you can use setLooping for the first case
and for the second case
final Runnable r = new Runnable() {
public void run() {
water_player.stop();
}
};
handler.postDelayed(r, 1000); //your time in millisecond
with your code :
if(tinydb.getString("timer").equals("infinity"))
{
water_player = MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.setLooping(true);
water_player.start();
}
else
{
water_player = MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.start();
final Runnable r = new Runnable() {
public void run() {
water_player.stop();
}
};
handler.postDelayed(r, 1000); //your time in millisecond
}
Use countdownTimer to complete your goal in which you can set countdown timer till x seconds manually. when countdown finish process it will go to finish method and execute finish method code
CountDownTimer cntr_aCounter = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
mp_xmPlayer2.start();
}
public void onFinish() {
//code fire after finish
mp_xmPlayer2.stop();
}
};cntr_aCounter.start();
If you have only 2 cases, use a boolean.
boolean infinitely;
if(infinitely == true){
water_player = MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.start();
}
else {
water_player = new MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.start();
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
water_player.stop();
}
}
, 2000);
The handler method will be executed when 2sec passed. (put your own desired time).
I'm working on React Native and i want to create a never ending service that run every (n) seconds on Native Modules (on this topic is android).
I've create a simple service like this
public void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.v(TAG, "SERVICE RUN");
try{
if(haveNetworkConnection()){
db.openDB();
if(db.countRowNewStructure()>0){
//send data to server
} else{
Log.v(TAG, "No data should be send to server");
}
} else {
Log.v(TAG, "Ga ada sinyal");
}
} catch (JSONException e){
e.printStackTrace();
}
}
}, 0, 1000);
}
above code run every second to check, but i'm facing the problem when i re-run the service from React Native, the log showing me those code every 0.5 seconds
the simulation may be like :
0----------------1 //seconds
startTimer()
re-run startTimer() conscious
0----------------1 //seconds
startTimer()
//now i have two startTimer() that will run every 1 sec on different interval
I want to keep my startTimer() just running once even I trigger startService() every 0.5 sec.
how can i do that? is it possible?
this may help you. Timmer to perform the certain action in android after the particular time.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask timertaskforsynctime = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// your action here
}
});
}
};
timer.schedule(timertaskforsynctime,5000,10000);// decide the time when it will start and after how much time it will run continusly.
}`
for one time
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// your code that will run after 1 sec
}
}, 1000);
You could make use of the cancel method to cancel the previous Timer.
public class YourModule extends ReactContextBaseJavaModule {
Timer tim = new Timer();
public void startTimer() {
tim.cancel();
tim = new Timer();
tim.scheduleAtFixedRate(
new TimerTask() {
public void run() {
// Run tasks
}
},
0,
1000);
}
}
I get notification with socket.io to start a countdown timer in my android app. I use a Handler to send data from the socket.io callbacks to the UI thread. Handler messages work perfect. But starting the countdown timer from the handler doesn't work (onTick() function won't called). If I start it with the UI element, everything is ok. What is the best way to do it, when the countdown timer is operated not from the UI thread?
mHandler = new Handler(){
public void handleMessage(Message inputMessage) {
mBattle = (Battle) inputMessage.obj;
switch (inputMessage.what) {
case NO_BATTLE:
System.out.println("got message NO_BATTLE");
break;
//.................
case START_BATTLE:
startCountdownTimer(mBattle.getCountdown());
System.out.println("got message START_BATTLE");
break;
}
}
and the countdown timer function:
private void startProgressBar(final int time){
if (time != 0) {
new CountDownTimer(time, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress " + i + " " +
+ millisUntilFinished);
i++;
}
#Override
public void onFinish() {
i=0;
}
}.start();
}
Did you print out the value of time when it's not working? If time < SystemClock.elapsedRealtime() + 1000, then onFinish will be called without calling the onTick.
first of all, I'm a beginner to android world so please apologize me if it is stupid question..
I'm trying to do following:
Enable Mobile Data
Wait for 10 seconds
a. check if Mobile got IP address (data connected sucessfully)
b. if Not connected,Disable Data
c. Go to step 1
And these steps 1 to 3 are getting executed in For loop for User Given number of retries.
Now my problem is: I'm stuck at step No. 2. I'm unable to make waitfor(int seconds) function. I tried using Runnable PostDelayed method but it is not giving me required output.
for(retry = UserChoice; retry > 0 && !isDataAvailable ; retry -- ){
enableInternet()
delay(10)
isDataAvailable = GetInternetAvailibility()
if(!isDataAvailable){
disableInternet()
}
}
I tried to put isDataAvailable = GetInternetAvailibility() statement in postDelayed of handler but it is causing enableInternet() disableInternet() to execute at the same time while isDataAvailable = GetInternetAvailibility() gets executed after delay.
I can see from logs, that enableInternet() executes for UserChoice number of times without any delay.
Thread.sleep(10000) just freezes the UI for 10 seconds... How do I achieve this?
EDIT : Let me clear :
public void onClick(View v) {
// Perform action on click
for(i=0; i<3; i++ ){
System.out.println("Before..");
delay(5);
System.out.println("after..");
}
}
public void delay(int seconds){
milliseconds = seconds * 1000;
runOnUiThread(new Runnable() {
#Override
public void run() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
System.out.println("XXX"); //add your code here
}
}, milliseconds);
}
});
}
Now whenever I click button I can see in logs that System.out prints message as:
Before
afterBefore
afterBefore
after
XXXXXXXXX
But I want:
Before
XXX
After.Before
XXX
After.Before
XXX
After.
try this:
public void check() {
isDataAvailable = GetInternetAvailibility()
if (!isDataAvailable) {
disableInternet();
enableInternet();
if (retry > 0) {
retry--;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
check();
}
}, 10000);
}
}
}
This way may help you.
http://developer.android.com/reference/android/os/CountDownTimer.html
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Try Below code.Hope that it will help
int i = 0;
int j = 3;
method() {
if (i < j) {
System.out.println("Before..");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
System.out.println("XXXXXX");
i++;
System.out.println("after");
method();
}
}, 1000);
}
}
I tried to put isDataAvailable = GetInternetAvailibility() statement
in postDelayed of handler but it is causing enableInternet()
disableInternet() to execute at the same time while isDataAvailable =
GetInternetAvailibility() gets executed after delay.
Put the if statement and disableInternet() in the postDelayed. enableInternet will get called, 10 seconds later it will check to see if the internet is available, if not it will disableInternet.
I'm developing an Android 2.3.3 application and I need to run a method every X seconds.
In iOS, I have NSTimer, but in Android I don't know what to use.
Someone have recommend me Handler; another recommend me AlarmManager but I don't know which method fits better with NSTimer.
This is the code I want to implement in Android:
timer2 = [
NSTimer scheduledTimerWithTimeInterval:(1.0f/20.0f)
target:self
selector:#selector(loopTask)
userInfo:nil
repeats:YES
];
timer1 = [
NSTimer scheduledTimerWithTimeInterval:(1.0f/4.0f)
target:self
selector:#selector(isFree)
userInfo:nil
repeats:YES
];
I need something what works like NSTimer.
What do you recommend me?
The solution you will use really depends on how long you need to wait between each execution of your function.
If you are waiting for longer than 10 minutes, I would suggest using AlarmManager.
// Some time when you want to run
Date when = new Date(System.currentTimeMillis());
try {
Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched
// Note: this could be getActivity if you want to launch an activity
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0, // id (optional)
someIntent, // intent to launch
PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
);
AlarmManager alarms = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE
);
alarms.setRepeating(
AlarmManager.RTC_WAKEUP,
when.getTime(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent
);
} catch(Exception e) {
e.printStackTrace();
}
Once you have broadcasted the above Intent, you can receive your Intent by implementing a BroadcastReceiver. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter); method. For more information on BroadcastReceiver's please refer to the official documentation..
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
System.out.println("MyReceiver: here!") // Do your work here
}
}
If you are waiting for shorter than 10 minutes then I would suggest using a Handler.
final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second
handler.postDelayed(new Runnable() {
public void run() {
System.out.println("myHandler: here!"); // Do your work here
handler.postDelayed(this, delay);
}
}, delay);
Use Timer for every second...
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//your method
}
}, 0, 1000);//put here time 1000 milliseconds=1 second
You can please try this code to call the handler every 15 seconds via onResume() and stop it when the activity is not visible, via onPause().
Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000; //Delay for 15 seconds. One second = 1000 milliseconds.
#Override
protected void onResume() {
//start handler as activity become visible
handler.postDelayed( runnable = new Runnable() {
public void run() {
//do something
handler.postDelayed(runnable, delay);
}
}, delay);
super.onResume();
}
// If onPause() is not included the threads will double up when you
// reload the activity
#Override
protected void onPause() {
handler.removeCallbacks(runnable); //stop handler when activity not visible
super.onPause();
}
If you are familiar with RxJava, you can use Observable.interval(), which is pretty neat.
Observable.interval(60, TimeUnits.SECONDS)
.flatMap(new Function<Long, ObservableSource<String>>() {
#Override
public ObservableSource<String> apply(#NonNull Long aLong) throws Exception {
return getDataObservable(); //Where you pull your data
}
});
The downside of this is that you have to architect polling your data in a different way. However, there are a lot of benefits to the Reactive Programming way:
Instead of controlling your data via a callback, you create a stream of data that you subscribe to. This separates the concern of "polling data" logic and "populating UI with your data" logic so that you do not mix your "data source" code and your UI code.
With RxAndroid, you can handle threads in just 2 lines of code.
Observable.interval(60, TimeUnits.SECONDS)
.flatMap(...) // polling data code
.subscribeOn(Schedulers.newThread()) // poll data on a background thread
.observeOn(AndroidSchedulers.mainThread()) // populate UI on main thread
.subscribe(...); // your UI code
Please check out RxJava. It has a high learning curve but it will make handling asynchronous calls in Android so much easier and cleaner.
With Kotlin, we can now make a generic function for this!
object RepeatHelper {
fun repeatDelayed(delay: Long, todo: () -> Unit) {
val handler = Handler()
handler.postDelayed(object : Runnable {
override fun run() {
todo()
handler.postDelayed(this, delay)
}
}, delay)
}
}
And to use, just do:
val delay = 1000L
RepeatHelper.repeatDelayed(delay) {
myRepeatedFunction()
}
new CountDownTimer(120000, 1000) {
public void onTick(long millisUntilFinished) {
txtcounter.setText(" " + millisUntilFinished / 1000);
}
public void onFinish() {
txtcounter.setText(" TimeOut ");
Main2Activity.ShowPayment = false;
EventBus.getDefault().post("go-main");
}
}.start();
Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution
Thread t = new Thread() {
#Override
public void run() {
while (!isInterrupted()) {
try {
Thread.sleep(10000); //1000ms = 1 sec
runOnUiThread(new Runnable() {
#Override
public void run() {
SharedPreferences mPrefs = getSharedPreferences("sam", MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("chat_list", "");
GelenMesajlar model = gson.fromJson(json, GelenMesajlar.class);
String sam = "";
ChatAdapter adapter = new ChatAdapter(Chat.this, model.getData());
listview.setAdapter(adapter);
// listview.setStackFromBottom(true);
// Util.showMessage(Chat.this,"Merhabalar");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
In case it needed it can be stoped by
#Override
protected void onDestroy() {
super.onDestroy();
Thread.interrupted();
//t.interrupted();
}
I do it this way and it works fine (the code is written in Kotlin):
private lateinit var runnable: Runnable
private var handler = Handler(Looper.getMainLooper())
private val repeatPeriod: Long = 10000
Then reinit the runnable from inside your function
runnable = Runnable {
// Your code goes here
handler.postDelayed(runnable, repeatPeriod)
}
handler.postDelayed(runnable, repeatPeriod)
Note that if you don't postDelay twice the handler, the loop is not going to be intinity!
In Kotlin, you can do it this way with a Runnable:
private lateinit var runnable: Runnable
private var handler = Handler(Looper.getMainLooper())
private val interval: Long = 1000
private var isRunning = false
val runnable = object : Runnable {
override fun run() {
// Do something every second
function()
// Call your runnable again after interval
handler?.postDelayed(runnable(this, interval))
}
}
// Call your function once
if (!isRunning) {
handler?.postDelayed(runnable, interval)
isRunning = true
}
// Remove your repeatedly called function
if (isRunning) {
handler?.removeCallbacks(runnable)
isRunning = false
}