How to keep timer running when closing the app? - java

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

Related

How to finish an application when it goes to the background

I need to finish an application when it goes to the background, I'm using method finishAffinity() but it seems it does not work, someone can tell me another alternative
#Override
protected void onPause() {
finishAffinity()
super.onPause();
}
Here's answer
finishAffinity() is not used to "shutdown an application". It is used to remove a number of Activitys belonging to a specific application from the current task (which may contain Activitys belonging to multiple applications).
Even if you finish all of the Activitys in your application, the OS process hosting your app does not automatically go away (as it does when you call System.exit()). Android will eventually kill your process when it gets around to it. You have no control over this (and that is intentional).
you can use this
public void endTask() {
// Is the user running Lollipop or above?
if (Build.VERSION.SDK_INT >= 21) {
// If yes, run the fancy new function to end the app and
// remove it from the task list.
finishAndRemoveTask();
} else {
// If not, then just end the app without removing it from
// the task list.
finish();
}
}
Source and read more

Libgdx controller unresponsive after making application fullscreen

When making the application full screen with the following call:
Gdx.graphics.setFullscreenMode(Gdx.graphics.getDisplayMode());
I no longer have signals from my controller. The issue is not solved by changing the display back from full screen like:
Gdx.graphics.setWindowedMode(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
I'm using Gdx version: 1.9.8. It appears this was an issue fixed in a previous version, but I'm not sure what the necessary steps are to get the work around functioning.
Here's some posts I found about the issue:
https://github.com/libgdx/libgdx/issues/4723
https://github.com/GoranM/bdx/issues/518
(this one is old) http://www.badlogicgames.com/forum/viewtopic.php?f=11&t=10692
Any help is much appreciated.
*Edit: This is using the controller extension that can be checked from the libgdx set up application. *
Edit2: I can get a responsive controller if I re-poll the controllers like the following:
Array<Controller> controllers = Controllers.getControllers();
However, this cannot be done instantly after changing the display mode; I have to wait some amount of time after. I'm not sure what I need to poll to determine how long I have to wait until the controller instances are valid (also, when it is valid to assign a listener).
Edit3: The only solution I've been able to come up with is to set a flag inside the resize callback like the following
#Override
public void resize(int width, int height) {
resizeDirty = true;
resizeTimestamp = System.currentTimeMillis();
}
Then in my main loop call:
private void controllerCheck() {
if (resizeDirty) {
long currentTime = System.currentTimeMillis();
if (currentTime > resizeTimestamp + controllerResetDelay) {
resizeDirty = false;
//get new controller instance | re-add a controller listener
}
}
}
This isn't ideal, I'd rather find a way to listen to when the change in context is done initializing then update the controllers. But I haven't been able to find a hook for that. I'd appreciate it if anyone knows a better way to go about maintaining controllers with change in display mode.
Why don't you try to use the immersive fullscreen?
If the objective is to set the fullscreen mode, I think this is the better way to.

CountDownTimer getting restarted after closing and reopening the app

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.

Doing an action exactly once

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

How can I schedule a particular thread in Blackberry

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

Categories