我正在使用Handler在Service类中创建一个倒数计时器。 计时器通过减少剩余时间来工作 并通过更新Recyclerview项目正在运行的Texview来工作。 问题是,当应用程序关闭并重新打开时, 计时器将无法再更新Recyclerview项目正在运行的Texview。
来自Recyclerview Adapter我正在从Service调用该函数来启动计时器。 在Eventbus libray的帮助下,我能够改变Texview。
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
这是调用计时器的Service类的一部分。
...
@Override
public PageAdapter.TheViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (!EventBus.getDefault().isRegistered(this)) { //Register the EventBus library
EventBus.getDefault().register(this);
}
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_item, parent, false);
return new TheViewHolder(itemView);
}
@Override
public void onBindViewHolder(final PageAdapter.TheViewHolder holder, int position) {
holder.btn_start_countdown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new ServiceHelper().startTimer(milliseconds, holder);//Call the Function in Service to Start the Timer
}
}
}
//The Pojo that help EventBus to post the new data
public static class CounterTextPojo {
volatile private long duration;
private TheViewHolder holder;
public CounterTextPojo(long duration, TheViewHolder holder){
this.duration = duration;
this.holder = holder;
}
public long getDuration(){
return duration;
}
}
//EventBus function to change the Textview Duration
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(CounterTextPojo data) {
long duration = data.getDuration();
TheViewHolder holder = data.getHolder();
int seconds = (int) (duration / 1000) % 60 ;
int minutes = (int) ((duration / (1000*60)) % 60);
int hours = (int) ((duration / (1000*60*60)) % 24);
holder.durationTexview.setText(String.format("%02d:%02d:%02d",hours,minutes,seconds));
if(duration < 1){
//Countdown Finish... Do Some staf
}
}
实现我想要的可能方式是什么?