目录

ActivityRecordsController Development

Creating ActivityRecords in Real Time

Create ActivityRecords for ongoing workout activities. The workout data during an active ActivityRecord is implicitly associated with the ActivityRecord on the Health platform.

  1. Start an ActivityRecord.

    The app uses the ActivityRecordsController.beginActivityRecord method to start an active ActivityRecord. The following is an example:

    HiHealthOptions hihealthOptions = HiHealthOptions.builder().build();
    AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(hihealthOptions);
    ActivityRecordsController mActivityRecordsController = HuaweiHiHealth.getActivityRecordsController(context, signInHuaweiId);
    
    long startTime = Calendar.getInstance().getTimeInMillis();
    // Build an ActivityRecord object.
    ActivityRecord activityRecord = new ActivityRecord.Builder()
            .setId("MyBeginActivityRecordId")
            .setName("BeginActivityRecord")
            .setDesc("This is ActivityRecord begin test!")
            .setActivityTypeId(HiHealthActivities.RUNNING)
            .setStartTime(startTime, TimeUnit.MILLISECONDS)
            .build();
    
    Task<Void> task1 = mActivityRecordsController.beginActivityRecord(activityRecord);
    // Add a listener for the ActivityRecord start success.
    task1.addOnSuccessListener(new OnSuccessListener<Void>() {
    	@Override
    	public void onSuccess(Void aVoid) {
    		Log.i("ActivityRecords","MyActivityRecord begin success");
    	}
    // Add a listener for the ActivityRecord start failure.
    }).addOnFailureListener(new OnFailureListener() {
    	@Override
    	public void onFailure(Exception e) {
    		String errorCode = e.getMessage();
                    String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
                    Log.i("ActivityRecords",errorCode + ": " + errorMsg);
    	}
    });
  2. Stop the ActivityRecord.

    The app uses the ActivityRecordsController.endActivityRecord method to stop a specified ActivityRecord. The following is an example:

    HiHealthOptions hihealthOptions = HiHealthOptions.builder().build();
    AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(hihealthOptions);
    ActivityRecordsController mActivityRecordsController = HuaweiHiHealth.getActivityRecordsController(context, signInHuaweiId);
    
    // Call the related method of ActivityRecordsController to stop activity records. The input parameter can be the ID string of ActivityRecord or null.
    // Stop an activity record of the current app by specifying the ID string as the input parameter.
    // Stop activity records of the current app by specifying null as the input parameter.
    Task<List<ActivityRecord>> endTask = mActivityRecordsController.endActivityRecord("MyBeginActivityRecordId");
    endTask.addOnSuccessListener(new OnSuccessListener<List<ActivityRecord>>() {
    	@Override
    	public void onSuccess(List<ActivityRecord> activityRecords) {
    		Log.i("ActivityRecords","MyActivityRecord End success");
    		// Return the list of activity records that have stopped.
    		if (activityRecords.size() > 0) {
    			for (ActivityRecord activityRecord : activityRecords) {
    				dumpActivityRecord(activityRecord);
    			}
    		} else {
    			// Null will be returned if none of the activity records has stopped.
    			Log.i("ActivityRecords","MyActivityRecord End response is null");
    		}
    	}}).addOnFailureListener(new OnFailureListener() {
    	@Override
    	public void onFailure(Exception e) {
                    String errorCode = e.getMessage();
                    String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
                    Log.i("ActivityRecords",errorCode + ": " + errorMsg);
    	}
    }); 

Inserting ActivityRecords to the Health Platform

To insert ActivityRecords with data that has been previously collected to the Health platform, perform the following:
  1. Create an ActivityRecord by specifying a time period and other necessary information.
  2. Create an ActivityRecordInsertOptions using the ActivityRecord, optional dataset, and grouped sampling points.
  3. Use the ActivityRecordsController.addActivityRecord method to insert an ActivityRecordInsertOptions.

The app uses the ActivityRecordsController.addActivityRecord method to insert the ActivityRecord and associated data to the Health platform.

HiHealthOptions hihealthOptions = HiHealthOptions.builder().build();
AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(hihealthOptions);
ActivityRecordsController mActivityRecordsController = HuaweiHiHealth.getActivityRecordsController(context, signInHuaweiId);

// 1. Build the time range of the request object: start time and end time.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.HOUR_OF_DAY, -1);
long startTime = cal.getTimeInMillis();

// 2. Build the activity record request object.
ActivityRecord activityRecord = new ActivityRecord.Builder()
		.setName("AddActivityRecord")
		.setDesc("This is ActivityRecord add test!")
		.setId("MyAddActivityRecordId")
		.setActivityTypeId(HiHealthActivities.RUNNING)
		.setStartTime(startTime, TimeUnit.MILLISECONDS)
		.setEndTime(endTime, TimeUnit.MILLISECONDS)
		.build();

// 3. Build the data collector object.
DataCollector dataSource = new com.huawei.hms.hihealth.data.DataCollector.Builder()
		.setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
		.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
		.setPackageName(mContext)
		.setDataCollectorName("AddActivityRecord")
		.build();
// 4. Build the sampling dataset based on the data collector.
SampleSet dataSet = SampleSet.create(dataSource);

// 5. Build the DT_CONTINUOUS_STEPS_DELTA sampling point object and add it to the sampling dataset.
SamplePoint dataPoint = dataSet.createSamplePoint().setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
dataPoint.getFieldValue(Field.FIELD_STEPS_DELTA).setIntValue(1024);
dataSet.addSample(dataPoint);

// 6. Build the activity record addition request object.
ActivityRecordInsertOptions insertRequest =
		new ActivityRecordInsertOptions.Builder().setActivityRecord(activityRecord).addSampleSet(dataSet).build();

// 7. Call the related method in the ActivityRecordsController to add activity records.
Task<Void> addTask = mActivityRecordsController.addActivityRecord(insertRequest);
addTask.addOnSuccessListener(new OnSuccessListener<Void>() {
	@Override
	public void onSuccess(Void aVoid) {
		 Log.i("ActivityRecords","ActivityRecord add was successful!");
	}
}).addOnFailureListener(new OnFailureListener() {
	@Override
	public void onFailure(Exception e) {
                String errorCode = e.getMessage();
                String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
                Log.i("ActivityRecords",errorCode + ": " + errorMsg);
	}
});

Reading ActivityRecords and Associated Data from the Health Platform

The user can obtain a list of ActivityRecords and associated data that meets certain criteria from the Health platform. For example, you can obtain all ActivityRecords within a specific period of time for particular data, or obtain a specific ActivityRecord by name or ID. You can also obtain ActivityRecords created by other apps.

Read ActivityRecords

  1. To obtain a list of ActivityRecords that meet the criteria, create an ActivityRecordReadOptions instance first.
  2. Use the ActivityRecordsController.getActivityRecord method to obtain data.
HiHealthOptions hihealthOptions = HiHealthOptions.builder().build();
AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(hihealthOptions);
ActivityRecordsController mActivityRecordsController = HuaweiHiHealth.getActivityRecordsController(context, signInHuaweiId);

// 1. Build the time range of the request object: start time and end time.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();

// 2. Build the request body for reading activity records.
ActivityRecordReadOptions readRequest =new ActivityRecordReadOptions.Builder().setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
				.readActivityRecordsFromAllApps()
				.read(DataType.DT_CONTINUOUS_STEPS_DELTA)
				.build();

checkConnect();
// 3. Call the read method of the ActivityRecordsController to obtain activity records from the Health platform based on the conditions in the request body.
Task<ActivityRecordReply> getTask = mActivityRecordsController.getActivityRecord(readRequest);
getTask.addOnSuccessListener(new OnSuccessListener<ActivityRecordReply>() {
	@Override
	public void onSuccess(ActivityRecordReply activityRecordReply) {
		 Log.i("ActivityRecords","Get ActivityRecord was successful!");
		//Print ActivityRecord and corresponding activity data in the result.
		List<ActivityRecord> activityRecordList = activityRecordReply.getActivityRecords();
		for (ActivityRecord activityRecord : activityRecordList) {
			printActivityRecord(activityRecord);
			for (SampleSet sampleSet : activityRecordReply.getSampleSet(activityRecord)) {
				printSampleSet(sampleSet);
			}
		}
	}
}).addOnFailureListener(new OnFailureListener() {
	@Override
	public void onFailure(Exception e) {
                String errorCode = e.getMessage();
                String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
                Log.i("ActivityRecords",errorCode + ": " + errorMsg);
	}
});

Registering/Unregistering a Listener to Monitor the Status Changes of Activity Records

The user can use addActrivityRecordsMonitor to register a listener to monitor the status changes of activity records. When an activity record starts or stops, the caller will be notified via a broadcast. The user can use removeActivityRecordsMonitor to unregister the listener for activity records they no longer wish to monitor.

  1. Register a listener to monitor the status changes of activity records.
HiHealthOptions hihealthOptions = HiHealthOptions.builder().build();
AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(hihealthOptions);
ActivityRecordsController mActivityRecordsController = HuaweiHiHealth.getActivityRecordsController(context, signInHuaweiId);

// 1. Build the pendingIntent request body. ActivityRecordsMonitorReceiver is the broadcast receiving class created in advance.
pendingIntent = PendingIntent.getBroadcast(this, 0,
		new Intent(this, ActivityRecordsMonitorReceiver.class),
		PendingIntent.FLAG_UPDATE_CURRENT);
// 2. Call the related method in the ActivityRecordsController to register a listener.
Task<Void> addMonitorTask = mActivityRecordsController.addActivityRecordsMonitor(pendingIntent);
addMonitorTask.addOnSuccessListener(new OnSuccessListener<Void>() {
	@Override
	public void onSuccess(Void aVoid) {
		Log.i("ActivityRecords","addActivityRecordsMonitor is successful");
	}
}).addOnFailureListener(new OnFailureListener() {
	@Override
	public void onFailure(Exception e) {
                String errorCode = e.getMessage();
                String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
                Log.i("ActivityRecords",errorCode + ": " + errorMsg);
		pendingIntent = null;
	}
});                
  1. Unregister a listener to monitor the status changes of activity records.
HiHealthOptions hihealthOptions = HiHealthOptions.builder().build();
AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(hihealthOptions);
ActivityRecordsController mActivityRecordsController = HuaweiHiHealth.getActivityRecordsController(context, signInHuaweiId);

// 1. Build the pendingIntent request body. ActivityRecordsMonitorReceiver is the broadcast receiving class created in advance.
pendingIntent = PendingIntent.getBroadcast(this, 0,
		new Intent(this, ActivityRecordsMonitorReceiver.class),
		PendingIntent.FLAG_UPDATE_CURRENT);
// 2. Call the related method in the ActivityRecordsController to unregister a listener.
Task<Void> removeMonitorTask = mActivityRecordsController.removeActivityRecordsMonitor(pendingIntent);
removeMonitorTask.addOnSuccessListener(new OnSuccessListener<Void>() {
	@Override
	public void onSuccess(Void aVoid) {
		Log.i("ActivityRecords","removeActivityRecordsMonitor is successful");
		pendingIntent = null;
	}
}).addOnFailureListener(new OnFailureListener() {
	@Override
	public void onFailure(Exception e) {
                String errorCode = e.getMessage();
                String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
                Log.i("ActivityRecords",errorCode + ": " + errorMsg);
		pendingIntent = null;
	}
});