0
我已經創建了一個在後臺統計的服務。我在我的MainActivity的onCreate()中啓動服務。需要解釋我的應用行爲
每當我重新啓動我的應用程序時,通過將計時器設置爲-1,我的服務類也是如此。但是,當我切換手機的方向時,定時器不會重置。
據我所知,殺死一個應用程序調用onDestroy()方法,然後再次啓動它,然後調用onCreate()。我已經看到,改變方向調用相同的兩種方法,那麼爲什麼這兩種行爲會導致不同的行爲,並且有什麼方法可以阻止它?我的代碼期望計時器在應用程序被終止時重置,所以當方向改變時,我的計時器就會關閉。
這裏是我的服務類的代碼:
ublic class CounterService extends Service {
private Handler handler;
private int time = -1;
private boolean isActive;
private Intent timeBroadcaster;
private Runnable counter;
private Thread serviceCounter;
private SharedPreferences.Editor editor;
public static final String EXTRA_TIME = "TIME";
@Override
public void onCreate(){
super.onCreate();
handler = new Handler();
timeBroadcaster = new Intent();
timeBroadcaster.setAction(Intent.ACTION_SEND);
SharedPreferences prefs = getSharedPreferences("SessionLogger_Preferences", MODE_PRIVATE);
editor = prefs.edit();
counter = new Runnable() {
@Override
public void run() {
isActive = ((PowerManager) getSystemService(Context.POWER_SERVICE)).isInteractive();
if (isActive) {
handler.postDelayed(this, 1000);
time += 1;
Log.i("TIME", String.valueOf(time));
} else {
editor.clear();
editor.commit();
if (time > 5) {
//log
}
time = 0;
handler.postDelayed(this, 1000);
}
timeBroadcaster.putExtra(EXTRA_TIME, time);
sendBroadcast(timeBroadcaster);
}
};
serviceCounter = new Thread(counter);
serviceCounter.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onDestroy(){
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}