android - Timer resetting again on pressing pause button and not running in background
问题描述
I have created an up count counter
for that I am running a background service so that the counter will run in the background even after the app being killed. But when the app is killed, the counter begins counting from the starting and when I press the pause button and play it again, the counter again begins counting as before from the starting. Below is the code for my service and Activity. Please help me out.
package io.funswitch.gymmon.Services;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import java.util.Locale;
import static io.funswitch.gymmon.Fragments.CheckOutFragment.running;
public class TimerService extends Service {
private Intent intent;
public static final String BROADCAST_ACTION = "com.javacodegeeks.android.androidtimerexample.MainActivity";
private Handler handler = new Handler();
private long initial_time;
long timeInMilliseconds = 0L;
@Override
public void onCreate() {
super.onCreate();
initial_time = SystemClock.uptimeMillis();
intent = new Intent(BROADCAST_ACTION);
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 1000); // 1 seconds
}
};
private void DisplayLoggingInfo() {
timeInMilliseconds = SystemClock.uptimeMillis() - initial_time;
int timer = (int) timeInMilliseconds / 1000;
intent.putExtra("time", timer);
sendBroadcast(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendUpdatesToUI);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
CheckoutActivity.java
package io.funswitch.gymmon.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
import io.funswitch.gymmon.Fragments.CheckOutFragment;
import io.funswitch.gymmon.R;
import io.funswitch.gymmon.Services.TimerService;
public class CheckOutActivity extends AppCompatActivity implements View.OnClickListener {
private Boolean exit = false;
ImageView play_pause, play;
private int milliseconds;
public boolean running;
TextView timer;
int time;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_out);
play_pause = findViewById(R.id.pause_play);
timer = findViewById(R.id.timer);
play = findViewById(R.id.play);
play_pause.setOnClickListener(this);
play.setOnClickListener(this);
time = getIntent().getIntExtra("time", 0);
// if (savedInstanceState == null) {
// FragmentManager fragmentManager = getSupportFragmentManager();
// CheckOutFragment stepsDetailActivityFragment = new CheckOutFragment();
// fragmentManager.beginTransaction()
// .add(R.id.check_out_frame, stepsDetailActivityFragment)
// .commit();
//
// }
// int time = getIntent().getIntExtra("time", 0);
// Bundle bundle = new Bundle();
// bundle.putInt("time", time);
//// set Fragmentclass Arguments
// CheckOutFragment fragobj = new CheckOutFragment();
// fragobj.setArguments(bundle);
}
@Override
public void onClick(View v) {
if (v == play_pause) {
if (running) {
// SharedPreferences sharedPreferences = getSharedPreferences("myPref", 0);
// sharedPreferences.getInt("tim", 0);
stopService(new Intent(CheckOutActivity.this, TimerService.class));
running = false;
play_pause.setImageResource(R.drawable.ic_play_button);
} else {
SharedPreferences sharedPreferences = getSharedPreferences("myPref", 0);
sharedPreferences.getInt("timee", 0);
running = true;
play_pause.setImageResource(R.drawable.ic_pause);
registerReceiver(broadcastReceiver, new IntentFilter(TimerService.BROADCAST_ACTION));
startService(new Intent(CheckOutActivity.this, TimerService.class));
}
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
runTimer(intent);
}
};
@Override
protected void onStop() {
super.onStop();
running = true;
Intent intent = new Intent(CheckOutActivity.this, TimerService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(TimerService.BROADCAST_ACTION));
// running = false;
// stopService(new Intent(CheckOutActivity.this, TimerService.class));
// unregisterReceiver(broadcastReceiver);
}
public void runTimer(Intent intent) {
time = intent.getIntExtra("time", 0);
int hour = time / 3600;
int mins = time / 60;
int secs = time % 60;
String timerTask = String.format(Locale.US, "%02d:%02d:%02d", hour, mins, secs);
timer.setText(timerTask);
SharedPreferences sharedPreferences = getSharedPreferences("myPref", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("tim", time);
editor.apply();
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (exit) {
finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 2 * 1000);
}
}
@Override
protected void onResume() {
super.onResume();
// Intent intent = new Intent(CheckOutActivity.this, TimerService.class);
// startService(intent);
// registerReceiver(broadcastReceiver, new IntentFilter(TimerService.BROADCAST_ACTION));
}
}
I have also tried to save values in sharedPreferences and retrieving it when play button clicks but it's not working. Please help me out.
解决方案
您需要将计数器保存在 sharedprefrences 中并在服务重新启动时恢复计数器值
在你的CheckOutActivity
@Override
protected void onStop() {
// save counter(time) value to sharedprefrences
running = false;
stopService(intent)
unregisterReceiver(broadcastReceiver);
}
int time;
public void runTimer(Intent intent){
time = intent.getIntExtra("time", 0);
int hour = time/3600;
int mins = time / 60;
int secs = time % 60;
timer.setText(String.format(Locale.US,"%02d:%02d:%02d", hour, mins, secs));
}
在TimerService
int counter;
@Override
public void onCreate() {
super.onCreate();
//set counter to value from sharedprefrences
}
private void DisplayLoggingInfo() {
timeInMilliseconds = SystemClock.uptimeMillis() - initial_time;
int timer = (int) timeInMilliseconds / 1000;
intent.putExtra("time", timer+counter);
sendBroadcast(intent);
}
推荐阅读
- python - 使用 Python 3 向 MySQL 或 MariaDB 发送请求
- python - 修改规范文件中的二进制文件时,Pyinstaller 无法正常工作
- java - 事务无法解决事务边界 - 休眠
- c# - WPF - 如何在 ViewModel 中实现 IDataErrorInfo 接口到复杂模型(FluentValidation)
- css - 如何从 ReactJS 的内联样式中检索纯 CSS?
- python - dask 调用图:缺少必需的位置参数
- reactjs - Kendo React Grid 编辑模式验证
- regex - 用于将先前版本与 1.11.14 匹配的正则表达式
- sql - 如何根据一列是否已在另一列中可用来为一列生成新值?
- docusignapi - 使用 curl 下载信封 pdf