NearbyService super simple integration tutorial get! Help you create a more convenient social chat application

background

"People nearby", "face-to-face group building", "close point-to-point local chat"... These common functions will appear in major social software. But usually, "people nearby" can only find people hundreds of meters or even kilometers away from themselves. How can we narrow this distance and greet people within a few meters? How can "face to face group building" accurately find the people around you? How to communicate and chat with friends directly without cloud service? Nearby Service can help you achieve! Next, we will explain the Nearby Service integration tutorial in detail to help you create a more convenient social chat application.

Application scenario introduction

Here is an example application integrating Nearby Service. This application can find people nearby by using Nearby Service, and can realize functions such as face-to-face group building, group chat, private chat, migration chat records and so on.

  • people nearby

It can accurately find people several meters nearby for users, and support users to find friends in the same room, such as meeting rooms, exhibition halls, bars, cafes, etc;

  • Face to face group building

Using Nearby Service to build a group, you can complete the group building action only on the end side. The position is accurate, and only people in the same place can enter the group.

  • Chat at will

Use Nearby Service to realize group chat without adding friends in a close range. New friends can automatically join the group just by going near the range; Leave the corresponding range and exit automatically.

  • Private chat

Nearby Service can be used to realize close local point-to-point chat. Communication is only conducted between two devices, data encryption is not available in the cloud, and there is no need to worry about information leakage; Communication can also be carried out in places with poor signals such as high-speed railway and subway.

  • Migrate chat

Moreover, Nearby Service also provides powerful file transfer function. When users have multiple devices to migrate chat records, they can use the communication interface of Nearby Service to realize high-speed and traffic free data migration.

Tool preparation

  1. 2 Android phones or more

  2. Development tool Android Studio(3.X or later)

Building sample applications

  • Import the sample source code in Android Studio.

  • Register as Huawei developers.

  • reference resources Nearby Service development preparation Create your application in Huawei application market. Note: you need to download the "agconnect services. JSON" file and the reference guide to generate the signature certificate and place it in the app / directory.

  • Use the adb command to install the generated apk file into the test phone.

critical code

The interface used in the sample application is in the official document Nearby Service Guides It is described in detail in.

This sample application is built in MVP mode. If you want to view the source code, please find the corresponding class according to the code path: com\huawei\hms\nearby\im.

1. People nearby

As shown in the following code, the NearbyPeoplePresenter class needs to pass in the view object during initialization. When calling NearbyPeoplePresenter When findnearbypeople() finds people nearby, it calls the interface of view to perform subsequent actions.

Inaearbypeopleview and xxxView in the following steps are a set of interfaces. Their specific implementation is the corresponding Activity object. The code path is: com\huawei\hms\nearby\im\ui\adapter.

public NearbyPeoplePresenter(Context mContext, INearbyPeopleView view) {
    super(mContext, view);
    nearbyAgent = new NearbyAgent(mContext, new NearbyAgent.INearbyMessageView() {
 
        @Override
        public void onMessageFound(MessageBean messageBean) {
            // notify view when found someone
           view.onMemberChanged(false,messageBean);
        }
 
        @Override
        public void onMessageLost(MessageBean messageBean) {
            view.onMemberChanged(true,messageBean);
        }
 
        @Override
        public void onMsgSendResult(boolean isSucceed, MessageBean item) {
            view.onLoginResult(isSucceed,item);
            if (!isSucceed) {
                handler.postDelayed(() -> findNearbyPeople(),DURATION_RE_LOGIN);
            }
        }
    });
    handler = new Handler(Looper.getMainLooper());
}
public void findNearbyPeople() {
    nearbyAgent.broadcastMessage(null,MessageBean.ACTION_TAG_ONLINE);
    nearbyAgent.startScan();
}

2. Face to face group building

Similar to "people nearby", creategrouppresenter The Java class passes in the view object during initialization. When calling the joinGroup(groupId) interface, it will join the group, and the result will be returned by calling the view interface.

public CreateGroupPresenter(Context mContext, ICreateGroupView view) {
    super(mContext, view);
    nearbyAgent = new NearbyAgent(mContext, new NearbyAgent.INearbyMessageView() {
        @Override
        public void onMessageFound(MessageBean messageBean) {
            view.onPeopleFound(messageBean);
        }
 
        @Override
        public void onMessageLost(MessageBean messageBean) {}
 
        @Override
        public void onMsgSendResult(boolean isSucceed, MessageBean item) {
            view.onJoinGroupResult(isSucceed,item);
        }
    });
}
 
public void joinGroup(String groupId) {
    nearbyAgent.broadcastMessage(groupId,"join group");
    nearbyAgent.startScan(groupId);
}

3. Chat at will

Class groupchatpresenter Java needs to pass in the view object during initialization. When the service group ID (groupsendid) is not empty, the message sent to the specified group is not limited; Call findMessage(groupId) to find the messages of the specified group, and then call the view interface to return the messages.

public GroupChatPresenter(Context mContext, IGroupChatView view) {
    super(mContext, view);
    nearbyAgent = new NearbyAgent(mContext, new NearbyAgent.INearbyMessageView() {
        @Override
        public void onMessageFound(MessageBean messageBean) {
            view.onMessageFound(messageBean);
        }
 
        @Override
        public void onMessageLost(MessageBean messageBean) {
 
        }
 
        @Override
        public void onMsgSendResult(boolean isSucceed, MessageBean item) {
            view.onMsgSendResult(isSucceed,item);
        }
    });
}
public void broadcastMessage(String groupId, String sendContent) {
    nearbyAgent.broadcastMessage(groupId,sendContent);
}
 
public void findMessage(String groupId) {
    nearbyAgent.startScan(groupId);
}

4. Private chat

The implementation of private chat is different from the above interface. It is similar to nearbyconnectionpresenter Java provides four interfaces:

  • findNearbyPeople(): find people nearby

  • requestConnect(): establish a connection with the other party

  • sendMessage(String msgStr): send string type message

  • Sendfile (URI): send file

/**
  * scanAndBroadcasting to find nearby people
  */
 public void findNearbyPeople(){
     mDiscoveryEngine.startScan(serviceId, new ScanEndpointCallback() {
         @Override
         public void onFound(String endpointId, ScanEndpointInfo discoveryEndpointInfo) {
             Log.d(TAG, "onFound -- Nearby Connection Demo app: onFound endpoint: " + endpointId);
             view.onFound(endpointId,discoveryEndpointInfo);
         }
 
         @Override
         public void onLost(String endpointId) {
             Log.d(TAG, "onLost -- Nearby Connection Demo app: Lost endpoint: " + endpointId);
             view.onLost(endpointId);
         }
     }, scanOption);
 }
 
 /**
  * request to connect with remote device
  * @param endpointId the endpointId of remote device
  */
 public void requestConnect(String endpointId) {
     Log.d(TAG, "requestConnect -- endpoint: " + endpointId);
     mDiscoveryEngine.requestConnect(myNameStr, endpointId, connectCallback);
 }
 
 /**
  * Send message ,Data.Type.BYTES
  */
 public MessageBean sendMessage(String msgStr) {
     MessageBean item = new MessageBean();
     item.setUserName(CommonUtil.userName);
     item.setMsg(msgStr);
     item.setType(MessageBean.TYPE_SEND_TEXT);
     item.setSendTime(DateUtils.getCurrentTime(DateUtils.FORMAT));
     Data data = Data.fromBytes(gson.toJson(item).getBytes(Charset.defaultCharset()));
     mTransferEngine.sendData(mEndpointId, data);
     return item;
 }
 
 /**
  * send file ,Data.Type.FILE
  * @param uri
  */
 public Data sendFile(Uri uri) {
     Data filePayload;
     try {
         ParcelFileDescriptor pfd = mContext.getContentResolver().openFileDescriptor(uri, "r");
         filePayload = Data.fromFile(pfd);
     } catch (FileNotFoundException e) {
         Log.e(Constants.TAG, "File not found, cause: ", e);
         return null;
     }
     String fileName = FileUtil.getFileRealNameFromUri(mContext, uri);
     String filenameMessage = filePayload.getId() + ":" + fileName;
     Data filenameBytesPayload = Data.fromBytes(filenameMessage.getBytes(StandardCharsets.UTF_8));
     mTransferEngine.sendData(mEndpointId, filenameBytesPayload);
     mTransferEngine.sendData(mEndpointId, filePayload);
     return filePayload;
 }

more details

Original link:
https://developer.huawei.com/consumer/cn/forum/topic/0201415949786580446?fid=18&pid=0301415949786580897
Author: Pepper

Tags: Android

Posted by LostinSchool on Mon, 02 May 2022 10:59:12 +0300