【发布时间】:2021-10-11 15:54:55
【问题描述】:
所以我有一个应用程序,它会在驾驶 4 小时后告诉你应该休息。当用户进行另一个活动(比如settings 选项卡)并返回主活动时,该计时器会从 0 重新开始。我该如何停止?
【问题讨论】:
标签: java android-studio android-activity
所以我有一个应用程序,它会在驾驶 4 小时后告诉你应该休息。当用户进行另一个活动(比如settings 选项卡)并返回主活动时,该计时器会从 0 重新开始。我该如何停止?
【问题讨论】:
标签: java android-studio android-activity
有几种方法可以解决这个问题。
首先,您可以创建一个单例类。操作定时器。这样它就不会死。 二、可以在intent中传递对象 第三,您可以在应用程序类而不是活动之外运行计时器。
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");
使用应用程序活动
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();
}
}
【讨论】: