I am trying to show a CountDownTimer to user which start decreasing immediately a user press the 'START' button, but if I'm closing the activity and reopening it, the CountDownTimer is getting reset and getting start again.
I used this link to learn how to set a CountDownTimer.
Here's how I coded it:
new CountDownTimer(ms, 1000) {
public void onTick(long millisUntilFinished) {
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % TimeUnit.MINUTES.toSeconds(1));
holder.availableFor.setText(hms);
}
public void onFinish() {
holder.linearLayout.setVisibility(View.GONE);
holder.firebaseDatabase.child(itemID).setValue(null);
holder.geoFireReference.child(itemID).setValue(null);
}
}.start();
Please let me know how to keep the Timer going even if user closes the app.
As I understand you're creating this timer in onClick method.
Try to create some global variable
CountDownTimer timer
After that create it in onclick, as you do.
and in onpause:
if (timer != null) {
timer.cancel
}
You have to use service class here
is the link which may be help you.
You need to store the timer data in some global scope so the timer once set not get altered with activity life cycle.
best practice suggest, use service like answered by #shahid17june
also if you don't want to use that, or setup variable to store counttimerdata in application class (global data), and update it appropriately.
Related
I've been trying to make an app, where after a time of 60 seconds, all the data collected by user input gets updated in firestore's existing data. However, as soon as I call the .update method of firebase, the activity gets recreated and timer starts again and it doesn't move on to the next activity. Its stuck in a loop and after every 60 seconds the activity is just recreating itself again and again. I know its because of the update method because if I comment that particular update method line, the application runs fine and normally as it should i.e after 60 seconds the app starts next activity. Also, I'm using firestore listener to get data only once and not real time update listener. I still don't get why is it happening. Please help
Edit:
new CountDownTimer(5000, 1000) {
#Override
public void onTick(long l) {
roundTimerView.setText(String.valueOf(counter));
counter--;
}
#Override
public void onFinish() {
newPlayerData.cards = cards;
GamePage.this.finish();
Intent intent = new Intent(GamePage.this,NextRoundReady.class);
Bundle bundle = new Bundle();
bundle.putString("USERNAME",Username);
bundle.putString("ROOMID",RoomID);
intent.putExtras(bundle);
startActivity(intent);
cr.document(RoomID).update(Username,newPlayerData);
}
}.start();
cr.document.update is the one giving me trouble, if I comment it out, after timer runs out, next activity starts, but if I uncomment it, after timer ends, it will just recreate the activity and run in a loop
Honestly GamePage.this.finish() seems suspicious, what happens if you remove that?
What happens when you remove startActivity?
The update method shouldn't be the real problem, unless it causes an exception which might restart the app
Also try doing the update before starting the new activity
i have code like this , i wanna make timer keep running when i close the app.
private void startStop() {
if (timerStatus == TimerStatus.STOPPED) {
setTimerValues();
setProgressBarValues();
timerStatus = TimerStatus.STARTED; startCountDownTimer();
} else {
timerStatus = TimerStatus.STOPPED;
stopCountDownTimer();
}
}
Assuming you want something like starting the timer, see the progress bar move and if you come back to your app after an hour, it should have advanced by that time.
The easiest approach would be to store the time at which the timer was started in a shared preference and update your timer periodically using System.currentTimeMillis()-startTime
All left to do is restore the shared preference in your Activity's onCreate
I`m trying to add tracking events to my android app using Mixpanel (it simply tracks what actions the user is doing in an application), and I want to add an event called "Application Started".
The question is, where should I track the event of the app starting without having it repeated. Is there a method or a function call in the life cycle that executes when the app first starts and only once ?
Do it in onCreate() of your application class.. it will be done only once when app gets started...
No, application class is different from activities.. For an application, there can be only on application class.. And that you declare in the manifest file.. Typically like this:
public class MyApplication extends Application {
#override
onCreate()
{
// Do your task here..
}
}
You can save it in as a preference value:
SharedPreferences setting = PreferenceManager.getDefaultSharedPreferences(this);
boolean firstStart = setting.getBoolean("firstStart",true);
if(firstStart == true) {
//do work first time
SharedPreferences.Editor edit = setting.edit();
edit.putBoolean("firstStart", false);
edit.commit();
}
I have following timer:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
--mTimer;
mTimeLeft.setText(String.valueOf(mTimer));
}
}, 0, 1000);
Text in the TextView will change when I touch the screen.
How can I refresh the TextView programatically?
I think this article will help you. http://android-developers.blogspot.com/2007/11/stitch-in-time.html
Basically you want to use the Handler class provided in the SDK. You shouldn't need to call invalidate like someone else suggested because setText does that for you.
Hope this helps!
The UI should be updated from the main thread. Take a look at this example that is closer to what you want.
TextView yourTextView =(TextView)findViewById(R.id.your_text_view_ID);
yourTextView.setText("your text");
If it doesn't change, try calling invalidate. Also, make sure you are calling from the UI thread, if not then use post method to send a runnable that will be executed in the UI thread (There you can change the text.)
I want to auto-schedule a thread with a particular time interval. I also need to execute this in the background continously without hangs to the device.
I have tried this with Application Manager Class but it's for application scheduling and I need to schedule thread within the application.
I would use TimerTask:
public class MyScreen extends MainScreen {
private Timer mTimer;
public MyScreen() {
mTimer = new Timer();
//start after 1 second, repeat every 5 second
mTimer.schedule(mTimerTask, 0, 5000);
}
TimerTask mTimerTask = new TimerTask() {
public void run() {
// some processing here
}
};
}
see BlackBerry API Hidden Gems (Part Two)
use UiApplication.getUiApplication().invokeLater()
it accepts a delay and repeat parameters and will perform exactly what you need.
EDIT
I know this post is old but this is by far the best option to schedule repeating events and I would like to add that to stop the scheduled event the following is required:
//Start repeating "runnable" thread every 10 seconds and save the event ID
int eventId = UiApplication.getUiApplication().invokeLater(runnable, 10000, true);
//Cancel the repetition by the saved ID
UiApplication.getUiApplication().cancelInvokeLater(eventId);
Assuming you want it to run a thread on device startup:
Create a second project and list it as an alternate entry point.
In your UiApplication or Application main(), check the argument passed to the project. Do your periodic stuff there via Thread.sleep and don't call enterEventDispatcher.
search for "autostart":
http://docs.blackberry.com/en/developers/deliverables/1076/development.pdf
Or if you want to do something once a user "starts" it, then look into creating a new thread to do your timing stuff. Override your screen's onClose() and use Application.getActivation().deactivate() to throw the screen into the background.
Or there's a other ways to do something like this like invokeLater, etc. Maybe eventlisteners may do what you need, but you didn't give a lot of details.
As long as the application is running - just create the thread and after each bit of work call Thread.sleep for as long as you need it to stay dormant.
If you need it to wake up at a particular time, rather than just sleep for a particular time, then you can do something like the following:
Date wakeUpAt = ...; // Get this however
Date now = new Date();
long millisToSleepFor = wakeUpAt.getTime() - now.getTime();
Thread.sleep(millisToSleepFor);