I'm working on a game where ants collect food and I'm trying to get the amount of time that the user was offline so I can calculate the amount of food the ants should have had collected. I have tried to run a timertask and looper to count the time in onDstroy but it didn't work. I'm open to some other ideas.
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.music);
player.setLooping(true); // Set looping
player.setVolume(left,right);
SharedPreferences prefs = getSharedPreferences("prefs", Context.MODE_PRIVATE);
offlineTime = prefs.getInt("offline",0);
onTime = prefs.getInt("ont",0);
totalTime = prefs.getInt("total",0);
offlineTime = totalTime - onTime;
intent = new Intent(BackgroundSoundService.this, LandingActivity.class);
intent.putExtra("offline", offlineTime);
startActivity(intent);
offlineTime = 0;
totalTime = 0;
onTime = 0;
}
public int onStartCommand(final Intent intent, int flags, int startId) {
player.start();
stopMuOn = true;
return Service.START_STICKY;
}
public void onStart(Intent intent, int startId) {
// TO DO
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
totalTime++;
SharedPreferences prefs = getSharedPreferences("prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("total",totalTime);
editor.apply();
}
}, 100); // Millisecond 1000 = 1 sec
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
player.pause();
}
@Override
public void onDestroy() {
SharedPreferences prefs = getSharedPreferences("prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("ont",onTime);
editor.apply();
player.stop();
player.release();
}
thanks in advance,