调用stopService()后,Android服务onDestroy方法会延迟运行

时间:2016-11-13 07:19:42

标签: java android service delay ondestroy

我正在使用服务来运行使用主要活动控制的计时器。但是,调用error: variable length arrays are not supported in OpenCL后出现的代码行似乎在服务中的stopService()方法之前运行。

以下是 MainActivityClass 中调用onDestroy()的代码:

stopService()

public void onClickLayoutS(View v){ //ON CLICK LAYOUT S //Behaviour stopService(intentTimerService); sharedPreferences.edit().putBoolean("isSSelected", true).apply(); updateLayout(); if(sharedPreferences.getBoolean("isPlaying", false)){ runTimerService(); } } 的位置:

runTimerService()

这是 ServiceClass 中的public void runTimerService(){ sharedPreferences.edit().putInt("intTimeOnBegin", (int) SystemClock.elapsedRealtime()).apply(); startService(intentTimerService); } 方法:

onDestroy()

@Override public void onDestroy() { super.onDestroy(); //RUNS ON SERVICE END //Behaviour handler.removeCallbacks(runnable); if(sharedPreferences.getBoolean("isSSelected", true)){ sharedPreferences.edit().putInt("intSTime", intTime).apply(); }else{ sharedPreferences.edit().putInt("intPTime", intTime).apply(); } intTime = 0; } 的位置:

runnable

因此,假设我在 MainActivity 中调用 handler = new Handler(); runnable = new Runnable() { @Override public void run() { //RUNNABLE //Behaviour if(sharedPreferences.getBoolean("isSSelected", true)){ //RUNS IF S IS SELECTED //Behaviour intTime = sharedPreferences.getInt("intSTime", 0) + ((int) SystemClock.elapsedRealtime() - sharedPreferences.getInt("intTimeOnBegin", 0)); sharedPreferences.edit().putString("stringSTime", formatTime(intTime)).apply(); sharedPreferences.edit().putString("stringPTime", formatTime(sharedPreferences.getInt("intPTime", 0))).apply(); }else{ //RUNS IF P IS SELECTED //Behaviour intTime = sharedPreferences.getInt("intPTime", 0) + ((int) SystemClock.elapsedRealtime() - sharedPreferences.getInt("intTimeOnBegin", 0)); sharedPreferences.edit().putString("stringPTime", formatTime(intTime)).apply(); sharedPreferences.edit().putString("stringSTime", formatTime(sharedPreferences.getInt("intSTime", 0))).apply(); } //Set runnable repeat interval handler.postDelayed(this, 1); } }; ,它应该将onClickLayoutS()的值保存为intTime在sharedPreferences中。但是,情况并非如此,当我运行应用并致电"intSTime"时,它会将onClickLayoutS()的值保存为intTime。为什么是这样?感谢您的帮助:)

0 个答案:

没有答案