FORUMS

How to use HUAWEI Nearby Service to Develop a Business Card Exchange Function for APP

110 posts
Thanks Meter: 10
 
By Freemind R, Official Huawei Rep on 22nd June 2020, 07:48 AM
Post Reply Email Thread

It is a tradition to exchange business cards with new colleges or partners, but keeping physical business cards is not easy at all. To solve this problem, many apps and mini programs providing the electronic business card function have emerged. You must be wondering how to develop such a function for your app.

Try integrating HUAWEI Nearby Service and use its Nearby Message feature to quickly implement the point-to-point business card exchange function. Check out the function demo below.

https://img.xda-cdn.com/_HUbgQZ4VU4C43VQ1-nFtXjtCE0=/https%3A%2F%2Fcommunityfile-dre.op.hicloud.com%2FFileServer%2FgetFile%2Fcmtybbs%2F006%2F560%2F358%2F2640852000006560358.20200617010635.36603621642718387763407349219062%3A50510622061734%3A2800%3A888B9D3B7202C7E33E3802FDAD9A86D6EFB45B8B6520999E9349F421BEE19933.gif

If you are interested in the implementation details, download the source code from GitHub. You can optimize the code based on your app requirements.

Github demo link: https://github.com/HMS-Core/hms-near...byCardExchange

The development procedure is as follows:

1. Getting Started

If you are already a Huawei developer, skip this step. If you are new to Huawei Mobile Services (HMS), you need to configure app information in AppGallery Connect, enable Nearby Service on the HUAWEI Developers console, and integrate the HMS Core SDK. For details, please refer to the documentation.

2. Adding Permissions

Before using Nearby Message, add the network, Bluetooth, and location permissions. Add the following permissions to the AndroidManifest.xml file of your project:

Code:
<uses-permission android:name="android.permission.INTERNET " />
 <uses-permission android:name="android.permission.BLUETOOTH" />
 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
 <!-- The location permission is also required in Android 6.0 or later. -->
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
1. Code Development

2.1 Submitting a Dynamic Permission Application

Ensure that the Bluetooth and location functions are enabled and the device has been connected to the Internet properly. Then submit a dynamic permission application for the location permission.

Code:
@Override
 public void onStart() {
     super.onStart();
     getActivity().getApplication().registerActivityLifecycleCallbacks(this);
     checkPermission();
 }
  
 @Override
 public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
     for (int i = 0; i < permissions.length; ++i) {
         if (grantResults[i] != 0) {
             showWarnDialog(Constants.LOCATION_ERROR);
         }
     }
 }
  
 private void checkPermission() {
     if (!BluetoothCheckUtil.isBlueEnabled()) {
         showWarnDialog(Constants.BLUETOOTH_ERROR);
         return;
     }
  
     if (!LocationCheckUtil.isLocationEnabled(this.getActivity())) {
         showWarnDialog(Constants.LOCATION_SWITCH_ERROR);
         return;
     }
  
     if (!NetCheckUtil.isNetworkAvailable(this.getActivity())) {
         showWarnDialog(Constants.NETWORK_ERROR);
         return;
     }
  
     String[] deniedPermission = PermissionUtil.getDeniedPermissions(this.getActivity(), new String[] {
             Manifest.permission.ACCESS_COARSE_LOCATION,
             Manifest.permission.ACCESS_FINE_LOCATION
     });
     if (deniedPermission.length > 0) {
         PermissionUtil.requestPermissions(this.getActivity(), deniedPermission, 10);
     }
 }
2.2 Encapsulating the Business Card Publishing and Subscription APIs

When a subscribed business card message is detected by the onFound method, display it in the business card searching pop-up; when a business card message is no longer discoverable (onLost), delete it from the business card searching pop-up.

Code:
private MessageHandler mMessageHandler = new MessageHandler() {
     @Override
     public void onFound(Message message) {
         CardInfo cardInfo = JsonUtils.json2Object(new String(message.getContent(), Charset.forName("UTF-8")),
                 CardInfo.class);
         if (cardInfo == null) {
             return;
         }
  
         mSearchCardDialogFragment.addCardInfo(cardInfo);
     }
  
     @Override
     public void onLost(Message message) {
         CardInfo cardInfo = JsonUtils.json2Object(new String(message.getContent(), Charset.forName("UTF-8")),
                 CardInfo.class);
         if (cardInfo == null) {
             return;
         }
  
         mSearchCardDialogFragment.removeCardInfo(cardInfo);
     }
 };
  
 private void publish(String namespace, String type, int ttlSeconds, OnCompleteListener<Void> listener) {
     Message message = new Message(JsonUtils.object2Json(mCardInfo).getBytes(Charset.forName("UTF-8")), type,
             namespace);
     Policy policy = new Policy.Builder().setTtlSeconds(ttlSeconds).build();
     PutOption option = new PutOption.Builder().setPolicy(policy).build();
     Nearby.getMessageEngine(getActivity()).put(message, option).addOnCompleteListener(listener);
 }
  
 private void subscribe(String namespace, String type, int ttlSeconds, OnCompleteListener<Void> listener,
                        GetCallback callback) {
     Policy policy = new Policy.Builder().setTtlSeconds(ttlSeconds).build();
     MessagePicker picker = new MessagePicker.Builder().includeNamespaceType(namespace, type).build();
     GetOption.Builder builder = new GetOption.Builder().setPolicy(policy).setPicker(picker);
     if (callback != null) {
         builder.setCallback(callback);
     }
     Nearby.getMessageEngine(getActivity()).get(mMessageHandler, builder.build()).addOnCompleteListener(listener);
 }
2.3 Processing the Business Card Exchange Menu

When two users exchange business cards face to face, exchange the business card exchange codes. When the business card message of the remote endpoint is published, subscribe to it.

Code:
private boolean onExchangeItemSelected() {
     PinCodeDialogFragment dialogFragment = new PinCodeDialogFragment(passwrod -> {
         MyCardFragment.this.publish(passwrod, passwrod, Policy.POLICY_TTL_SECONDS_MAX, result -> {
             if (!result.isSuccessful()) {
                 String str = "Exchange card fail, because publish my card fail. exception: "
                         + result.getException().getMessage();
                 Log.e(TAG, str);
                 Toast.makeText(getActivity(), str, Toast.LENGTH_LONG).show();
                 return;
             }
             MyCardFragment.this.subscribe(passwrod, passwrod, Policy.POLICY_TTL_SECONDS_INFINITE, ret -> {
                 if (!ret.isSuccessful()) {
                     MyCardFragment.this.unpublish(passwrod, passwrod, task -> {
                         String str = "Exchange card fail, because subscribe is fail, exception("
                                 + ret.getException().getMessage() + ")";
                         if (!task.isSuccessful()) {
                             str = str + " and unpublish fail, exception(" + task.getException().getMessage()
                                     + ")";
                         }
  
                         Log.e(TAG, str);
                         Toast.makeText(getActivity(), str, Toast.LENGTH_LONG).show();
                     });
                     return;
                 }
                 mSearchCardDialogFragment.setOnCloseListener(() -> {
                     MyCardFragment.this.unpublish(passwrod, passwrod, task -> {
                         if (!task.isSuccessful()) {
                             Toast.makeText(getActivity(), "Unpublish my card fail, exception: "
                                     + task.getException().getMessage(), Toast.LENGTH_LONG).show();
                         }
                     });
                     MyCardFragment.this.unsubscribe(task -> {
                         if (!task.isSuccessful()) {
                             Toast.makeText(getActivity(), "Unsubscribe fail, exception: "
                                     + task.getException().getMessage(), Toast.LENGTH_LONG).show();
                         }
                     });
                 });
                 mSearchCardDialogFragment.show(getParentFragmentManager(), "Search Card");
             }, null);
         });
     });
     dialogFragment.show(getParentFragmentManager(), "pin code");
  
     return true;
 }
2.4 Adding a Business Card to Favorites

When a user adds a business card to favorites, add the card to the favorites list; when a user removes a business card from favorites, remote the card from the favorites list. In addition, store related data locally.

Code:
@Override
 public void onFavorite(CardInfo cardInfo, boolean isFavorite) {
     if (isFavorite) {
         mFavoriteMap.put(cardInfo.getId(), cardInfo);
     } else {
         mFavoriteMap.remove(cardInfo.getId());
     }
     Set<String> set = new HashSet<>(mFavoriteMap.size());
     for (CardInfo card : mFavoriteMap.values()) {
         set.add(JsonUtils.object2Json(card));
     }
     SharedPreferences sharedPreferences = getContext().getSharedPreferences("data", Context.MODE_PRIVATE);
     sharedPreferences.edit().putStringSet(Constants.MY_FAVORITES_KEY, set).apply();
 }
5. Conclusion

This demo uses Nearby Message feature of HUAWEI Nearby Service. What Nearby Message is capable of is more than just developing functions for exchanging business cards face-to-face. Here are some examples:

1. Face-to-face teaming in multiplayer sports games

2. Face-to-face round joining in board games

3. Near-field go-Dutch payment function

4. Music sharing

If you are interested and want to learn more, check our development guide at

https://developer.huawei.com/consume...e-introduction[/SIZE]
The Following 2 Users Say Thank You to Freemind R For This Useful Post: [ View ] Gift Freemind R Ad-Free
24th June 2020, 05:28 AM |#2  
Junior Member
Thanks Meter: 0
 
More
Hi,
NearBy connection service will work foreground/background?
24th June 2020, 05:48 AM |#3  
Junior Member
Flag Bangalore
Thanks Meter: 0
 
More
Hi,
Thanks for sharing the information. Can we use Huawei Near By Service to create a chat application. Also could be possible the chat application can work without internet on device.

Thanks
24th June 2020, 06:05 AM |#4  
Junior Member
Thanks Meter: 0
 
More
Nice article
Thanks for sharing. I have one doubt, does nearby connection supports Bluetooth low energy(BLE)?
24th June 2020, 11:39 AM |#5  
OP Official Huawei Rep
Thanks Meter: 10
 
More
Quote:
Originally Posted by sujith.e

Hi,
NearBy connection service will work foreground/background?

Hi. It can run in the background, but it may be hampered by the system for a long time in the background. For a better experience, it is recommended to run in the foreground. Nearby Service is capable of high-performance transmission, so transmission does not take too long.
24th June 2020, 11:44 AM |#6  
OP Official Huawei Rep
Thanks Meter: 10
 
More
Quote:
Originally Posted by sanghati

Hi,
Thanks for sharing the information. Can we use Huawei Near By Service to create a chat application. Also could be possible the chat application can work without internet on device.

Thanks

Yes, Nearby Service supports files, byte sequences, and streaming. You can refer to https://github.com/HMS-Core/hms-near...arbyConnection to use the byte transfer capabilities of Nearby to develop a Chat app.
The Following User Says Thank You to Freemind R For This Useful Post: [ View ] Gift Freemind R Ad-Free
24th June 2020, 11:46 AM |#7  
OP Official Huawei Rep
Thanks Meter: 10
 
More
Quote:
Originally Posted by riteshchanchal

Thanks for sharing. I have one doubt, does nearby connection supports Bluetooth low energy(BLE)?

Yeah. Nearby supports Bluetooth low energy.
Post Reply Subscribe to Thread

Tags
hms; huawei

Guest Quick Reply (no urls or BBcode)
Message:
Previous Thread Next Thread
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes