It’s efficient to pass business cards like this! Teach you to develop a business card exchange function for the application

Time:2022-4-27

In work and life, it is a common user demand to meet new colleagues or partners and exchange business cards. Paper business cards are often forgotten and easy to lose, which is a pain point for customers. Therefore, there are many apps and small programs for exchanging electronic business cards on the market. So, how to develop a business card exchange function for your app?

We can accessHuawei short range communication service, one-to-one or one to many business card exchanges can be quickly realized through near message subscription between devices. The following figure is a function demonstration:

The specific development steps are as follows:

1. Development preparation

If you are already a developer of Huawei, you can omit this step. If you have no previous experience in integrating Huawei mobile services, you need to configure appgallery connect, open short-range communication service and integrate HMS SDK. For relevant steps, please refer toOfficial documents

2. Add permissions

Before using nearby message, you need to add network permission, Bluetooth permission and location permission. In the project’s androidmanifest Add the following permissions to the XML file:

3. Code development

3.1 dynamic permission application

Check whether the Bluetooth switch and position switch are on and whether the network is available, and apply for dynamic permission for position permission

@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);
     }
 }

3.2 encapsulate business card publishing interface and business card subscription interface

Subscribe to the business card message (onfound), and add the business card to the search business card dialog box for display; When the business card message is lost (onlost), delete the business card from the find business card dialog box

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 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 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);
 }

3.3 # business card exchange menu processing

Exchange business card exchange codes face-to-face. After successfully publishing personal business cards, subscribe to business card messages

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;
 }

3.4 collection of business cards

Add the business card to the collection list when collecting the business card, delete the business card from the parameter list when canceling the collection, and save the data to the local storage.

@Override
 public void onFavorite(CardInfo cardInfo, boolean isFavorite) {
     if (isFavorite) {
         mFavoriteMap.put(cardInfo.getId(), cardInfo);
     } else {
         mFavoriteMap.remove(cardInfo.getId());
     }
     Set 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();
 }

The demo presented to you this time uses the message subscription function between close devices of Huawei HMS nearby service. The nearby message capability can not only be used for face-to-face business card exchange, but also help developers realize many interesting functions, such as:

  • Face to face team formation function in competitive mobile games
  • Face to face game making function in chess and card hand games
  • Near field AA collection function
  • Music track sharing

For more details

Visit the official website of Huawei short range communication service
Obtain Huawei short range communication service development guidance document
Huawei short range communication service open source warehouse address:GitHubGitee
Huawei HMS core official forum
Solve integration problemsStack Overflow

Follow us and learn the latest technology of HMS core for the first time~

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]