代码之家  ›  专栏  ›  技术社区  ›  Meowminator

设置倒计时以运行onDestroy()的正确方法是什么?

  •  0
  • Meowminator  · 技术社区  · 7 年前

    我正在尝试创建一个计时器,可以在后台启动一次 onDestroy() 一旦计时器达到6小时, SharedPreferences 将用于在应用程序中进行更改。

    我在想。。。正确的设置方法是什么 CountDownTimer 或者其他类似的东西 onDestroy() .

    如果需要,我会回答任何问题。非常感谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Meowminator    7 年前

    大约一周后,一个有效的答案出现了。这个答案包括与如何运行服务相关的内容。在这个场景中,我正在构建一个 CountDownTimer

    <service android:name=".TimeService"/>
    

    主活动.java

    import android.content.Intent;
    import android.support.v4.content.ContextCompat;
    
    public class MainActivity extends AppCompatActivity {
           Intent i;
    
           @Override
           protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               i = new Intent(this, TimeService.class);
    
               stopService(i); //To stop the service the next time the app is launched.
           }
    
           @Override
           protected void onDestroy() {
               launchService(); //Launches the service once when app shuts down.
               super.onDestroy();
           }
    
           public void launchService() { //How to launch the service, depending the phone's API.
                if(Build.VERSION.SDK_INT >= 26) {
                     startForegroundService(new Intent(this, TimeService.class));
                }
                else{
                    Intent i;
                    i = new Intent(this, TimeService.class);
                    ContextCompat.startForegroundService(this, i);
                }
           }
    }
    

    import android.app.Service;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.CountDownTimer;
    import android.os.IBinder;
    import android.support.annotation.Nullable;
    
    public class TimeService extends Service {
    
       CountDownTimer cdt = null;
       private SharedPreferences pref;
       //Things you want SharedPreferences to change.
       Intent i;
    
       @Override
       public void onCreate() {
           i = new Intent(this, TimeService.class);
           startService(i);
           pref = this.getSharedPreferences("myAppPref", MODE_PRIVATE);
           cdt = new CountDownTimer(3600000, 1000) { //One hour timer with one second interval.
    
               @Override
               public void onTick(long millisUntilFinished) {
    
               }
    
               @Override
               public void onFinish() {
                    //Whatever you need SharedPreferences to change here.
               }
           };
           cdt.start();
       }
    
       @Nullable
       @Override
       public IBinder onBind(Intent intent) {
           return null;
       }
    }