我想创建一个从活动中接收毫秒数的服务
当它开始时,该倒数方法开始。
而且即使关闭应用程序,该服务也会继续。
并且如果应用程序打开并且该活动开始,则服务会将剩余时间传递给活动。
我可以将数据发送到服务。
我可以开始倒数计时方法了。
但是当应用程序关闭并重新打开服务时,向活动发送0。
这是我的活动代码:
TapCommand
此服务代码:
private long verifyTime;
long DEFAULT_VERIFY_TIME = 50000;
private final int CODE_LENGTH = 5;
private ProgressDialog progressDialog;
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
verifyTime = intent.getLongExtra(Global.TIMER , verifyTime);
setTxtTimer();
}
};
@Override
protected void onResume() {
registerReceiver(receiver, new IntentFilter(Global.TIMER_KEY));
sendBroadCast();
super.onResume();
}
@Override
protected void onStop() {
Intent intent = new Intent(CodeReceiverActivity.this,CodeReceiverService.class);
intent.putExtra(Global.TIMER , verifyTime);
startService(intent);
unregisterReceiver(receiver);
super.onStop();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_code_reicever);
}
private void sendBroadCast(){
if(isMyServiceRunning(CodeReceiverService.class)){
CodeReceiverService service = new CodeReceiverService(getApplicationContext());
service.sendBroadCast();
}else {
verifyTime = DEFAULT_VERIFY_TIME;
setTxtTimer();
}
}
private void setTxtTimer(){
new CountDownTimer(verifyTime, 1000) {
public void onTick(long millisUntilFinished) {
millisUntilFinished = millisUntilFinished - 1000;
String time = String.format(Locale.ENGLISH, "%02d:%02d",
(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)) % 60,
(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)) % 60);
txtTimer.setText(time);
}
@Override
public void onFinish() {
cancel();
btnResend.setEnabled(true);
btnResend.setAlpha(1f);
}
}.start();
}
和android清单:
public class CodeReceiverService extends Service {
long timer;
long returnTime;
Context context;
public CodeReceiverService() {
}
public CodeReceiverService(Context context) {
this.context = context;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
timer = intent.getLongExtra(Global.TIMER , 0);
setTimer();
return START_REDELIVER_INTENT;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void setTimer(){
new CountDownTimer(timer, 1000) {
public void onTick(long millisUntilFinished) {
millisUntilFinished = millisUntilFinished - 1000;
returnTime = millisUntilFinished;
}
@Override
public void onFinish() {
stopSelf();
}
}.start();
}
public void sendBroadCast(){
Intent intent = new Intent(Global.TIMER_KEY);
Bundle bundle = new Bundle();
bundle.putLong(Global.TIMER , returnTime);
intent.putExtras(bundle);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
答案 0 :(得分:0)
最好将数据保存到SharePrefs。如果关闭,则无法将其发送到活动。保存到SharePref并在活动的onResume()上,从SharePrefs获取数据会更好