Nearby Message allows a device that functions as a subscriber to discover a nearby device that functions as a publisher and obtain the messages registered by the publisher with the cloud server. Here are some typical use cases:

What You Will Create

In this codelab, you will use a created demo project to call Nearby Message APIs. Nearby Message supports two scenarios: app-based message publishing and subscription and beacon-based message publishing and subscription. The demo project implements beacon-based message publishing and subscription. You can have the following development experiences in the demo project:

What You Will Learn

Hardware Requirements

Software Requirements

To integrate HMS Core services, you must complete the following preparations:

For details, please refer to Preparations for Integrating HMS Core.

Sign in to HUAWEI Developer, go to Console > HMS API Services > My APIs, select the project for which you want to enable HUAWEI Nearby Service, and click Apply for new HMS API service. The API Library page is

Click Nearby Service.

On the Nearby Service page, click Enable to enable HUAWEI Nearby Service.

Adding the AppGallery Connect Configuration File

Sign in to AppGallery Connect, select My apps, and click the app you have created. Go to Develop > Overview, click , and choose Add SDK, and perform operations as instructed.

Adding Build Dependencies

Open the build.gradle file in the app directory.

Add configurations to the file header.

apply plugin: 'com.huawei.agconnect'

Set JavaVersion.

compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }

Add build dependencies to dependencies.

dependencies { implementation 'com.huawei.hms:nearby: {version}' }

The following figure shows the configuration result.

Configuring Obfuscation Scripts

Open the obfuscation configuration file of your project.

Add configurations to exclude the HMS SDK from obfuscation.

-ignorewarnings -keepattributes *Annotation* -keepattributes Exceptions -keepattributes InnerClasses -keepattributes Signature -keepattributes SourceFile,LineNumberTable -keep class**{*;} -keep class com.huawei.updatesdk.**{*;} -keep class com.huawei.hms.**{*;}

If you have used AndResGuard, add the AndResGuard whitelist to the obfuscation configuration file.

"R.string.hms*", "R.string.connect_server_fail_prompt_toast", "R.string.getting_message_fail_prompt_toast", "R.string.no_available_network_prompt_toast", "R.string.third_app_*", "R.string.upsdk_*", "R.layout.hms*", "R.layout.upsdk_*", "R.drawable.upsdk*", "R.color.upsdk*", "R.dimen.upsdk*", "*", "R.string.agc*"

Synchronizing the Project

Choose File > Sync Project with Gradle Files to start building your project.

The synchronization is successful if "synced successfully" is displayed, as shown in the following figure.

You will build a demo project by calling key APIs provided by the HMS Core Nearby Service SDK in the scenario of beacon-based message publishing and subscription simply by performing the following procedure:

Modifying the AndroidManifest.xml File

First of all, you need to modify the permissions of your app. Go to app > src > main in your project, open the AndroidManifest.xml file, and add six required permissions to the file, as shown in the following figure.

The sample code is as follows:

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- The location permission is also required for BLE scanning in Android 6.0 and later versions. --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Copying the Sample Code and Resource Files

Copy the following highlighted files to the corresponding directories of your project. Ensure that you have switched to the project view in your Android Studio.

Sample Code

The sample code applies to our demo product, which illustrates how to push promotion information of nearby canteens based on beacons.
Sample code for registering a listener for Bluetooth, GPS, or network disconnection

private void registerStatusReceiver() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); intentFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION); mContext.registerReceiver(stateChangeReceiver, intentFilter); }

Sample code for a beacon near a canteen to subscribe to messages


mMessageHandler = new MessageHandler() { @Override public void onFound(Message message) { super.onFound(message); doOnFound(message); } }; MessagePicker msgPicker = new MessagePicker.Builder().includeAllTypes().build(); Policy policy = new Policy.Builder().setTtlSeconds(Policy.POLICY_TTL_SECONDS_INFINITE).build(); GetOption getOption = new GetOption.Builder().setPicker(msgPicker).setPolicy(policy).build(); Task<Void> task = messageEngine.get(mMessageHandler, getOption);

Sample code for a nearby beacon to obtain preference Information of canteens and display the information to users


private void doOnFound(Message message) { if (message == null) { return; } String type = message.getType(); if (type == null) { return; } String messageContent = new String(message.getContent()); Log.d(TAG, "New Message:" + messageContent + " type:" + type); if (type.equalsIgnoreCase(Constant.CANTEEN)) { operateOnFoundCanteen(messageContent); } else if (type.equalsIgnoreCase(Constant.NOTICE)) { operateOnFoundNotice(messageContent); } }

Building, Loading, and Debugging the App

You can build your app after modifying the sample code based on your requirements.
After the build is complete, generate the APK. Install it on your Huawei phone, and run and debug it.

Download sample code BeaconManager to start beacon management. For details about beacon management APIs, please refer to RESTful APIs of Beacon.

Creating a Service Account

Sign in to HUAWEI Developers, go to Console > HMS API Services > Credentials, select your project, and click Service account key. The Create service account key page is displayed.

Set Name and Description, and click Generate public and private keys to generate the public and private keys. Click Create and download JSON to save the generated JSON file to your phone properly.

Running the Demo App BeaconManger

Configure and run the demo app BeaconManger following the instructions in the file.

Signing In to the App

Access My Center, tap your profile image, and use the JSON key file downloaded in Creating a Service Account to sign in.

Registering Beacons

Go to Unregistered, refresh the page to discover new beacons Beacon1 and Beacon2, and tap each beacon to register it.

Configuring Message Attachments

Go to Unregistered, tap each beacon, and configure message attachments.

The procedure is as follows:

  1. Configure message attachments for Beacon1.
  2. a. Set the message type to canteen, enter the message content {"canteenDesc":"This is the description of Canteen A.","canteenName":"Canteen A"}, and submit the configuration.

    b. Set the message type to notice, enter the message content {"canteenName":"Canteen A","notice":"Huawei employees dinning here can get a 20% discount and a free fruit platter."}, and submit the configuration.

  3. Configure message attachments for Beacon2.
  4. a. Set the message type to canteen, enter the message content {"canteenDesc":"This is the description of Canteen B.","canteenName":"Canteen B"}, and submit the configuration.

    b. Set the message type to notice, enter the message content {"canteenName":"Canteen B","notice":"12% off for all dishes on New Year's Eve. VIPs can have an extra 10% discount."}, and submit the configuration.

Now you can run your app on a Huawei phone.

Initial Screen


Finding canteens and pushing preference information

For more information, please click the following links:
Related documentation

You can download the source code in

You can also click the button below to download the source code.

Download source code

Code copied