【问题标题】:How do I call a method only once in `onCreate()` and keep running it when changing activities如何在`onCreate()`中只调用一次方法并在更改活动时继续运行它
【发布时间】:2021-10-11 15:54:55
【问题描述】:

所以我有一个应用程序,它会在驾驶 4 小时后告诉你应该休息。当用户进行另一个活动(比如settings 选项卡)并返回主活动时,该计时器会从 0 重新开始。我该如何停止?

【问题讨论】:

    标签: java android-studio android-activity


    【解决方案1】:

    有几种方法可以解决这个问题。

    首先,您可以创建一个单例类。操作定时器。这样它就不会死。 二、可以在intent中传递对象 第三,您可以在应用程序类而不是活动之外运行计时器。

    1. 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;
          }
      }
      
    2. 使用意图传递

    //To pass:
        intent.putExtra("MyTimer", obj);
    
    // To retrieve object in second Activity
        getIntent().getSerializableExtra("MyTimer");
    
    1. 使用应用程序活动

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

    【讨论】:

    • 您能帮我重新格式化代码吗?所以更容易阅读
    • 你去。抱歉,它是通过编辑错误来的。我确保它正确通过。
    • 当使用单例时,我应该把“定时器”的代码本身放在哪里?我不知道这是否有什么不同,但目前我使用一个处理程序和一个 runnable 来完成这个 4 小时的循环
    • 您将在新文件中创建一个新类
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多