1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.car.dialer.livedata; 18 19 import android.os.Handler; 20 import android.os.Looper; 21 22 import androidx.lifecycle.LiveData; 23 24 /** 25 * Emits a true value in a fixed periodical pace. The first beat begins when this live data becomes 26 * active. 27 * 28 * <p> Note that if this heart beat is shared, the time can be less than the given interval between 29 * observation and first beat for the second observer. 30 */ 31 public class HeartBeatLiveData extends LiveData<Boolean> { 32 private long mPulseRate; 33 private Handler mMainThreadHandler = new Handler(Looper.getMainLooper()); 34 HeartBeatLiveData(long rateInMillis)35 public HeartBeatLiveData(long rateInMillis) { 36 mPulseRate = rateInMillis; 37 } 38 39 @Override onActive()40 protected void onActive() { 41 super.onActive(); 42 mMainThreadHandler.post(mUpdateDurationRunnable); 43 } 44 45 @Override onInactive()46 protected void onInactive() { 47 super.onInactive(); 48 mMainThreadHandler.removeCallbacks(mUpdateDurationRunnable); 49 } 50 51 private final Runnable mUpdateDurationRunnable = new Runnable() { 52 @Override 53 public void run() { 54 setValue(true); 55 mMainThreadHandler.postDelayed(this, mPulseRate); 56 } 57 }; 58 } 59