目录

Developing the Activity Identification Service

Overview

Your app can obtain the device activity status such as walking, running, or cycling in the following methods:

Restrictions

Ensure that you have downloaded and installed HMS Core (APK) on your device, and integrated the Location SDK into your project. For details, please refer to Preparations. This section provides only relevant code snippets. For the complete code, please refer to Sample Code.

The activity identification function requires that the phone memory being greater than 3 GB. (This condition is not applicable to mobile simulators.)

To improve the activity identification success rate, you are advised to insert a SIM card to the device and connect to the 5G, 4G, 3G, or 2G network. The IN_VEHICLE and ON_BICYCLE modes of activity identification use the cell information. Therefore, whether a mobile network is connected will affect the activity identification success rate. Currently, the activity identification service cannot identify the cycling and riding activities on devices outside the Chinese mainland.

Assigning App Permissions

The android.permission.ACTIVITY_RECOGNITION and com.huawei.hms.permission.ACTIVITY_RECOGNITION permissions are dangerous permissions and need to be dynamically applied for.

Registering a Static Broadcast Receiver

In the sample code, activity status updates identified by the activity identification service are broadcast. Therefore, you need to register a broadcast receiver in the AndroidManifest.xml file.

<!-- Register a broadcast receiver for the activity identification service. -->
<receiver
    android:name=".location.fusedlocation.LocationBroadcastReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="com.huawei.hmssample.location.LocationBroadcastReceiver.ACTION_PROCESS_LOCATION" />
    </intent-filter>
</receiver>

Initializing the Activity Identification Client

Declare an ActivityIdentificationService object in the main thread and pass parameters of the Context or Activity type.
Java
private PendingIntent pendingIntent;
private ActivityIdentificationService activityIdentificationService;
// Obtain an activityIdentificationService instance.
activityIdentificationService = ActivityIdentification.getService(this);
// Obtain a PendingIntent object.
pendingIntent = getPendingIntent();
Kotlin
private var pendingIntent: PendingIntent? = null
private var activityIdentificationService: ActivityIdentificationService? = null
// Obtain an activityIdentificationService instance.
activityIdentificationService = ActivityIdentification.getService(this)
// Obtain a PendingIntent object.
pendingIntent = getPendingIntent()

Identifying the Activity Status

To use the activity identification service, request activity identification updates to check the current user status, such as walking, cycling, or resting.

  1. Create a PendingIntent object.
    Java
    // Obtain PendingIntent associated with the custom static broadcast class LocationBroadcastReceiver.
    private PendingIntent getPendingIntent() {
        Intent intent = new Intent(this, LocationBroadcastReceiver.class);
        intent.setAction(LocationBroadcastReceiver.ACTION_PROCESS_LOCATION);
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
            return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            // For devices running Android 12 or later, you need to configure the mutability of pendingIntent. By default, the configuration is PendingIntent.FLAG_MUTABLE.
            // If compileSdkVersion is 30 or earlier, you can replace PendingIntent.FLAG_MUTABLE with 1<<25.
            // PendingIntent.FLAG_MUTABLE can be used only when buildToolsVersion is 31 or later.
            return PendingIntent.getBroadcast(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
        }
    }
    Kotlin
    // Obtain PendingIntent associated with the custom static broadcast class LocationBroadcastReceiver.
    private fun getPendingIntent(): PendingIntent? {
        val intent = Intent(this, LocationBroadcastReceiver::class.java)
        intent.action = LocationBroadcastReceiver.ACTION_PROCESS_LOCATION
        return if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
            PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        } else {
            // For devices running Android 12 or later, you need to configure the mutability of pendingIntent. By default, the configuration is PendingIntent.FLAG_MUTABLE.
            // If compileSdkVersion is 30 or earlier, you can replace PendingIntent.FLAG_MUTABLE with 1<<25.
            // PendingIntent.FLAG_MUTABLE can be used only when buildToolsVersion is 31 or later.
            PendingIntent.getBroadcast(
                this,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
            )
        }
    }
  2. Request activity identification updates.
    Call the createActivityIdentificationUpdates(long detectionIntervalMillis, PendingIntent callbackIntent) method to request activity identification updates and listen for the callback result.
    Java
    // Initiate an activity identification request.
    activityIdentificationService.createActivityIdentificationUpdates(5000, pendingIntent)
        // Define callback for request success.
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                // TODO: Define callback for success in requesting activity identification updates.
            }
        })
        // Define callback for request failure.
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                // TODO: Define callback for failure in requesting activity identification updates.
            }
        });
    Kotlin
    // Initiate an activity identification request.
    activityIdentificationService!!.createActivityIdentificationUpdates(
        5000,
        pendingIntent
    )
        // Define callback for request success.
        .addOnSuccessListener {
            // TODO: Define callback for success in requesting activity identification updates.
        }
        // Define callback for request failure.
        .addOnFailureListener { e ->
            // TODO: Define callback for failure in requesting activity identification updates.
        }

    Parameters

    Parameter

    Type

    Description

    Remarks

    detectionIntervalMillis

    long

    Interval for detecting activity updates, in milliseconds. The default value is 30000.

    A larger value will result in fewer activity detections, while a smaller value will result in more activity detections.

    callbackIntent

    PendingIntent

    PendingIntent object associated with each activity identification request. The activity identification result is broadcast to users at the specified interval.

    When building a PendingIntent object, you need to set Class and Action. Do not build an empty intent.

  3. Obtain the activity identification result.
    Call the broadcast receiver to obtain the activity identification result.
    Java
    // Activity identification broadcast receiver.
    public class LocationBroadcastReceiver extends BroadcastReceiver {
        // Activity identification service broadcast action.
        public static final String ACTION_PROCESS_LOCATION = "com.huawei.hms.location.ACTION_PROCESS_LOCATION";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                final String action = intent.getAction();
                if (ACTION_PROCESS_LOCATION.equals(action)) {
                    // Obtain ActivityIdentificationResponse and extract a detected activity status list from it.
                    ActivityIdentificationResponse activityIdentificationResponse = 
                        ActivityIdentificationResponse.getDataFromIntent(intent);
                    List<ActivityIdentificationData> list = 
                        activityIdentificationResponse.getActivityIdentificationDatas();
                    // TODO: Process the obtained activity status list.
                }
            }
        }
    }
    Kotlin
    // Activity identification broadcast receiver.
    class LocationBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent != null) {
                val action = intent.action
                if (ACTION_PROCESS_LOCATION == action) {
                    // Obtain ActivityIdentificationResponse and extract a detected activity status list from it.
                    val activityIdentificationResponse =
                        ActivityIdentificationResponse.getDataFromIntent(intent)
                    val list =
                        activityIdentificationResponse.activityIdentificationDatas
                    // TODO: Process the obtained activity status list.
                }
            }
        }
    
        companion object {
            // Activity identification service broadcast action.
            const val ACTION_PROCESS_LOCATION =
                "com.huawei.hms.location.ACTION_PROCESS_LOCATION"
        }
    }
  4. Stop requesting activity identification updates.
    If your app does not need to receive activity identification updates, call deleteActivityIdentificationUpdates(PendingIntent pendingIntent) to stop requesting activity identification updates. The PendingIntent object must be the same as that passed to createActivityIdentificationUpdates(long detectionIntervalMillis, PendingIntent callbackIntent).
    Java
    activityIdentificationService.deleteActivityIdentificationUpdates(pendingIntent)
        // Define callback for success in stopping requesting activity identification updates.
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                // TODO: Define callback for success in stopping requesting activity identification updates.
            }
        })
        // Define callback for failure in stopping requesting activity identification updates.
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                // TODO: Define callback for failure in stopping requesting activity identification updates.
            }
        });
    Kotlin
    // Stop requesting activity identification updates.
    activityIdentificationService!!.deleteActivityIdentificationUpdates(pendingIntent)
        // Define callback for success in stopping requesting activity identification updates.
        .addOnSuccessListener {
            // TODO: Define callback for success in stopping requesting activity identification updates.
    
        } // Define callback for failure in stopping requesting activity identification updates.
        .addOnFailureListener { e ->
            // TODO: Define callback for success in stopping requesting activity identification updates.
    
        }

Listening for Activity Conversion Updates

Activity conversion is a process of detecting user activity converting from one to another, for example, from walking to cycling. You can call the createActivityConversionUpdates(ActivityConversionRequest request, PendingIntent pendingIntent) method in your app to request user activity conversion updates.

  1. Set parameters for requesting activity conversion updates.
    Java
    // Create an information object for switching from the static state to the activity state.
    ActivityConversionInfo activityConversionInfoStillEnter = new ActivityConversionInfo(
        ActivityIdentificationData.STILL, ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION);
    // Create an information object for switching from the activity state to the static state. 
    ActivityConversionInfo activityConversionInfoStillExit = new ActivityConversionInfo(
        ActivityIdentificationData.STILL, ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION);
    List<ActivityConversionInfo> activityConversionInfos = new ArrayList<>();
    activityConversionInfos.add(activityConversionInfoStillEnter);
    activityConversionInfos.add(activityConversionInfoStillExit);
    // Create an activity conversion request body instance.
    ActivityConversionRequest request = new ActivityConversionRequest();
    request.setActivityConversions(activityConversionInfos);
    Kotlin
    // Create an information object for switching from the static state to the activity state.
    val activityConversionInfoStillEnter = ActivityConversionInfo(
        ActivityIdentificationData.STILL,
        ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION
    )
    // Create an information object for switching from the activity state to the static state. 
    val activityConversionInfoStillExit = ActivityConversionInfo(
        ActivityIdentificationData.STILL,
        ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION
    )
    val activityConversionInfos: MutableList<ActivityConversionInfo> =
        ArrayList()
    activityConversionInfos.add(activityConversionInfoStillEnter)
    activityConversionInfos.add(activityConversionInfoStillExit)
    // Create an activity conversion request body instance.
    val request = ActivityConversionRequest()
    request.activityConversions = activityConversionInfos
  2. Listen for activity conversion updates.
    Java
    // Listen for activity conversion updates.
    Task<Void> task = activityIdentificationService.createActivityConversionUpdates(request, pendingIntent);
    // Define callback for task success. 
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            // TODO: Define callback for success in requesting activity conversion updates.
        }
    })
        // Define callback for task failure.
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                // TODO: Define callback for failure in requesting activity conversion updates.
            }
        });
    Kotlin
    // Listen for activity conversion updates.
    val task: Task<Void> =
       activityIdentificationService!!.createActivityConversionUpdates(request, pendingIntent)
    // Define callback for task success. 
    task.addOnSuccessListener(OnSuccessListener<Void?> {
        // TODO: Define callback for success in requesting activity conversion updates.
    })
        // Define callback for task failure.
        .addOnFailureListener(OnFailureListener { e ->
            // TODO: Define callback for failure in requesting activity conversion updates.
        })

    Parameters

    Parameter

    Type

    Description

    Remarks

    request

    ActivtiyConversionRequest

    Activity conversion request parameter, which is used to set the activity status (walking or resting) to be listened for and the entering and exit status of the related activity.

    Constructed activity conversion request body.

    pendingIntent

    PendingIntent

    PendingIntent object associated with each activity conversion request. If an activity status change is detected, the detection result will be broadcast to users.

    When building a PendingIntent object, you need to set Class and Action. Do not build an empty intent.

  3. Receive the broadcasted activity conversion result.
    Java
    public class LocationBroadcastReceiver extends BroadcastReceiver {
        public static final String ACTION_PROCESS_LOCATION = "com.huawei.hms.location.ACTION_PROCESS_LOCATION";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                final String action = intent.getAction();
                if (ACTION_PROCESS_LOCATION.equals(action)) {
                    // Obtain ActivityConversionResponse from the intent and extract an activity conversion event list from the response.
                    ActivityConversionResponse activityConversionResponse = ActivityConversionResponse.getDataFromIntent(intent);
                    List<ActivityConversionData> list = activityConversionResponse.getActivityConversionDatas();
                    // TODO: Process the obtained activity conversion event list.
                }
            }
        }
    }
    Kotlin
    class LocationBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(
            context: Context,
            intent: Intent
        ) {
            if (intent != null) {
                val action = intent.action
                if (ACTION_PROCESS_LOCATION == action) {
                    // Obtain ActivityConversionResponse from the intent and extract an activity conversion event list from the response.
                    val activityConversionResponse =
                        ActivityConversionResponse.getDataFromIntent(intent)
                    val list =
                        activityConversionResponse.activityConversionDatas
                    // TODO: Process the obtained activity conversion event list.
                }
            }
        }
    
        companion object {
            const val ACTION_PROCESS_LOCATION =
                "com.huawei.hms.location.ACTION_PROCESS_LOCATION"
        }
    }
  4. (Optional) Stop requesting activity conversion updates.
    If your app does not need to receive activity conversion updates, call deleteActivityConversionUpdates(PendingIntent pendingIntent) to stop requesting activity conversion updates.
    Java
    // Stop requesting activity conversion updates through the specified pendingIntent.
    activityIdentificationService.deleteActivityConversionUpdates(pendingIntent)
        // Define callback for success in stopping requesting activity conversion updates.
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                // TODO: Define callback for success in stopping requesting activity conversion updates.
            }
        })
        // Define callback for failure in stopping requesting activity conversion updates.
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                // TODO: Define callback for failure in stopping requesting activity conversion updates.
            }
        });
    Kotlin
    // Stop requesting activity conversion updates through the specified pendingIntent.
    activityIdentificationService!!.deleteActivityConversionUpdates(pendingIntent) 
        // Define callback for success in stopping requesting activity conversion updates.
        .addOnSuccessListener {
            // TODO: Define callback for success in stopping requesting activity conversion updates.
        } 
        // Define callback for failure in stopping requesting activity conversion updates.
        .addOnFailureListener { e ->
            // TODO: Define callback for failure in stopping requesting activity conversion updates.
        }