public abstract class HealthDataObserver extends Object
onChange(String)
In case that you add an observer for the data type that updates too frequently in short time like step count, it can send too many events to your application and it can bring degradation of your application's performance. Check that your application needs to update data with real-time from Samsung Health again before adding an observer.
A health data observer can be defined as below.
public class HealthDataObserverExample { // The state of connection private HealthDataStore mStore; public static final String APP_TAG = "MyApp"; private final HealthDataObserver mObserver = new HealthDataObserver(null) { // Checks notification for changed health data @Override public void onChange(String dataTypeName) { Log.d(APP_TAG, "Health data is changed."); readChangedData(dataTypeName); } };
When you add an observer for the specific health data type, specify the data type name as below. Only data type is allowed to be observed.
public void start() { // Adds an observer for change of the weight HealthDataObserver.addObserver(mStore, HealthConstants.Weight.HEALTH_DATA_TYPE, mObserver); }
The change notification is received in onChange(String) and you can check updated health data as below.
private void readChangedData(String dataTypeName) { HealthDataResolver resolver = new HealthDataResolver(mStore, null); HealthDataResolver.ReadRequest rdRequest = new HealthDataResolver.ReadRequest.Builder() .setDataType(dataTypeName) .build(); try { // Make an asynchronous request to read health data resolver.read(rdRequest).setResultListener(mRdListener); } catch (Exception e) { Log.d(APP_TAG, "HealthDataResolver.read() fails."); } } private final HealthResultHolder.ResultListener<HealthDataResolver.ReadResult> mRdListener = new HealthResultHolder.ResultListener<HealthDataResolver.ReadResult>() { @Override public void onResult(HealthDataResolver.ReadResult result) { try { Iterator<HealthData> iterator = result.iterator(); if (iterator.hasNext()) { HealthData data = iterator.next(); // Check the result } } finally { result.close(); } } }; }
HealthDataObserver(Handler handler)
static void
addObserver(HealthDataStore store, String dataTypeName, HealthDataObserver observer)
abstract void
onChange(String dataTypeName)
removeObserver(HealthDataStore store, HealthDataObserver observer)
public HealthDataObserver(Handler handler)
handler
null
public abstract void onChange(String dataTypeName)
dataTypeName
public static void addObserver(HealthDataStore store, String dataTypeName, HealthDataObserver observer)
store
observer
IllegalArgumentException
IllegalStateException
public static void removeObserver(HealthDataStore store, HealthDataObserver observer)