如何在 `onCreate()` 中只调用一次方法并在更改活动时保持 运行
How do I call a method only once in `onCreate()` and keep running it when changing activities
所以我有一个应用程序,它会在驾驶 4 小时后告诉您应该休息。当用户继续另一个 activity(比方说 settings
选项卡)并返回主 activity 时,该计时器从 0 重新开始。我如何停止它?
您可以通过多种方式解决该问题。
首先,您可以创建一个单例class。操作定时器。这样它就不会死。
二、可以在intent中传递对象
第三,您可以 运行 应用程序外的计时器 class 而不是 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;
}
}
使用意图传递
//To pass:
intent.putExtra("MyTimer", obj);
// To retrieve object in second Activity
getIntent().getSerializableExtra("MyTimer");
正在使用应用程序 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();
}
}
所以我有一个应用程序,它会在驾驶 4 小时后告诉您应该休息。当用户继续另一个 activity(比方说 settings
选项卡)并返回主 activity 时,该计时器从 0 重新开始。我如何停止它?
您可以通过多种方式解决该问题。
首先,您可以创建一个单例class。操作定时器。这样它就不会死。 二、可以在intent中传递对象 第三,您可以 运行 应用程序外的计时器 class 而不是 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; } }
使用意图传递
//To pass:
intent.putExtra("MyTimer", obj);
// To retrieve object in second Activity
getIntent().getSerializableExtra("MyTimer");
正在使用应用程序 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(); } }