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

background

"Nearby people", "face-to-face group building", "close point-to-point local chat"... These common functions will appear in major social software. But under normal circumstances, "people nearby" basically can only find people a few hundred meters or even a few kilometers away from them. How to narrow this distance and greet people within a few meters? How can "face-to-face group building" accurately discover the people around you? How to directly communicate and chat with friends without going through the cloud service? Nearby Service can do it for you! The following will explain in detail the Nearby Service integration tutorial for you to help you build a more convenient social chat application.

Application scenario introduction

Here is a sample application that integrates Nearby Service. This application can use Nearby Service to find nearby people, and based on this ability, it can realize functions such as face-to-face group building, group chat, private chat, and chat history migration.

  • People nearby

It can accurately find people a few meters nearby and support users to find friends in the same room, such as conference rooms, exhibition halls, bars, coffee shops, etc.;

Insert picture description here

  • Face to face

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

Insert picture description here

  • Free chat

Using Nearby Service, you can realize group chats without friends within a close range. New friends can join the group automatically when they are near the range; they will automatically exit when they leave the corresponding range.

Insert picture description here

  • Private chat

Use Nearby Service to realize the point-to-point chat at close range. Communication is only carried out between the two devices, and data is not encrypted on the cloud, so there is no need to worry about information leakage; communication can also be carried out in places with poor signals such as high-speed rail and subway.

Insert picture description here

  • Migrate chat history

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

Tool preparation

  1. 2 Android phones or more

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

Build a sample application

  • Import the sample source code in Android Studio.

  • Register as a Huawei developer.

  • Refer to the development of Nearby Service and prepare to create your application in the Huawei application market. Note: You need to download the "agconnect-services.json" file and refer to the instructions to generate a signed certificate and place it in the app/ directory.

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

Key code

The interfaces used in the sample application are described in detail in the official document Nearby Service Guides .

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 code below, the NearbyPeoplePresenter class needs to pass in the view object when it is initialized. When the nearby people are found by calling NearbyPeoplePresenter.findNearbyPeople(), the view interface is called to perform subsequent actions.

INearbyPeopleView 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", the CreateGroupPresenter.java class passes in the view object when it is initialized, and joins the group when the joinGroup(groupId) interface is called, and the result is 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. Talk freely

Class GroupChatPresenter.java needs to pass in the view object during initialization. The business code calls broadcastMessage(groupId, sendContent) to send a message to the specified group. When the groupId is empty, the group is not limited; calls findMessage(groupId) to find the message of the specified group, and then calls the view interface to return the message after discovery.

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 interfaces. The NearbyConnectionPresenter.java class provides 4 interfaces:

  • findNearbyPeople(): find nearby people

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

  • sendMessage(String msgStr): Send a string type message

  • sendFile (Uri uri): Transmission text
/**
  * 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

Guess you like

Origin blog.51cto.com/14772288/2562481