我已经实现了一个广播接收器,每秒从运行CountDownTimer的Service传递数据,剩余时间到片段。
问题是Fragment没有正确接收数据或更好地说只有当我按下某个搜索按钮,隐藏键盘或活动中的其他内容时才接收数据。
这是我的服务类:
CountDownTimer timer = new CountDownTimer(number, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished;
normalTime = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(timeLeft),
TimeUnit.MILLISECONDS.toMinutes(timeLeft) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeLeft)),
TimeUnit.MILLISECONDS.toSeconds(timeLeft) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeLeft)));
Intent timerInfoIntent = new Intent(TIME_INFO);
timerInfoIntent.putExtra("VALUE", normalTime);
LocalBroadcastManager.getInstance(NotificationService.this).sendBroadcast(timerInfoIntent);
}
这是我的片段,它应该接收数据并更新列表视图的项目。
在onCreateView中我注册了一个接收器:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mTimerStatusReceiver = new TimerStatusReceiver();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
mTimerStatusReceiver, new IntentFilter(NotificationService.TIME_INFO));
...
}
在onResume上执行相同操作:
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
mTimerStatusReceiver, new IntentFilter(NotificationService.TIME_INFO));
...
}
取消注册onPause:
@Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mTimerStatusReceiver);
}
TimerStatesReceiver类:
private class TimerStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction().equals(NotificationService.TIME_INFO)) {
if (!IS_ALREADY_EXECUTED) {
modelTimer = new ModelTimer();
if (intent.hasExtra("VALUE")) {
modelTimer.setexpirationTime(intent.getStringExtra("VALUE"));
}
listOfTimers.add(modelTimer);
mAdapter = new ListViewAdapter(getActivity(), listOfTimers);
mListView.setAdapter(mAdapter);
IS_ALREADY_EXECUTED = true;
}else{
for (ModelTimer timer: listOfTimers){
View v = mListView.getChildAt(timerPosition.get(timer.getId()));
timer.setexpirationTime(intent.getStringExtra("VALUE"));
timer.setName(intent.getStringExtra("NAME_FOOD"));
if (v == null) return;
TextView time = (TextView) v.findViewById(R.id.active_timer_timeLeft);
time.setText(timer.expirationTime);
}
mAdapter.notifyDataSetChanged();
}