Issue
So I have an app that tells you after 4 hours of driving have passed that you should rest. When the user goes on another activity (let's say the settings
tab) and comes back to the main activity, that timer starts over again from 0. How do I stop that?
Solution
There would be a handful of ways you can address the issue.
First, you can create a singleton class. that operates the timer. This way it does not die. Second, you can pass the object in the intent Third, you can run the timer out of the application class rather then an activity.
https://www.geeksforgeeks.org/singleton-class-java/
class Timer{ private static Timer timer=null; public get_instance(){ if(timer==null){ timer=new Timer(); } return timer; } }
Pass using intent
//To pass:
intent.putExtra("MyTimer", obj);
// To retrieve object in second Activity
getIntent().getSerializableExtra("MyTimer");
using application activity
import android.app.Application; public class MyCustomApplication extends Application { // Called when the application is starting, before any other application objects have been created. // Overriding this method is totally optional! @Override public void onCreate() { super.onCreate(); startTimer(); // This might be a better place for it // Required initialization logic here! } // Called by the system when the device configuration changes while your component is running. // Overriding this method is totally optional! @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } // This is called when the overall system is running low on memory, // and would like actively running processes to tighten their belts. // Overriding this method is totally optional! @Override public void onLowMemory() { super.onLowMemory(); } }
Answered By - Drivers Sea
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.