本文介绍Android互动SDK的支持系统、集成方式以及部分功能的使用。

支持系统

支持Android4.1及以上版本,minSDKVersion为16。

基于NDK18b编译。

SDK下载

配置环境

  1. 解压下载的Android SDK压缩包,将aar依赖添加到项目中的libs目录。
  2. 更改build.gradle中的依赖。
    dependencies {
        implementation fileTree(dir: "libs", include: ["*.jar", "*.aar"])
    }

    此时执行sync,项目未报错即表示依赖添加成功。

  3. 配置AndroidManifest.xml权限。
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  4. 添加混淆配置。
    proguard-rules.pro中增加如下keep项。
    -keep class com.alibaba.dingpaas.** { *; }
    -keep class com.alipay.mars.** { *; }
    -keep class com.alipay.bifrost.** { *; }
    -keep class com.alipay.mobile.** { *; }
    -keep class org.android.spdy.** { *; }

公共部分工程接入

  1. 加载so依赖。
    System.loadLibrary("dmojo_support");
    System.loadLibrary("interaction");
    System.loadLibrary("sqlite3");
    System.loadLibrary("GaeaLwp");
    System.loadLibrary("openssl");
    System.loadLibrary("GaeaLwpOverBifrost");
    System.loadLibrary("fml_shared");
    System.loadLibrary("dps");
  2. 初始化引擎。
    // 创建DPS引擎
    DPSPubEngine engine = DPSPubEngine.CreateDPSEngine();
    DPSPubEngine.SetLogHandler(DPSLogLevel.DPS_LOG_LEVEL_DEBUG, new DPSLogHandler() {
        @Override
        public void onLog(DPSLogLevel aimLogLevel, String msg) {
            switch (aimLogLevel) {
                case DPS_LOG_LEVEL_DEBUG:
                    Log.d("InteractionManager", msg);
                    break;
                case DPS_LOG_LEVEL_WARNING:
                    Log.w("InteractionManager", msg);
                    break;
                case DPS_LOG_LEVEL_INFO:
                    Log.i("InteractionManager", msg);
                    break;
                default:
                    Log.e("InteractionManager", msg);
            }
        }
    });
    // 获取配置服务
    DPSPubSettingService setting = engine.getSettingService();
    initService(context, setting, config);
    // 初始化模块
    DPSModuleInfo moduleInfo = InteractionModule.getModuleInfo();
    engine.registerModule(moduleInfo);
    // 启动引擎
    engine.start(listener);
    其中initService做各种信息配置。
    说明 以下供参考。
    private void initService(final Context context, DPSPubSettingService setting, InteractionConfig config) {
        File externalCacheDir = context.getExternalCacheDir();
        if (externalCacheDir == null) {
            throw new RuntimeException("Access external cache dir failure.");
        }
        String dataPath = externalCacheDir.getPath() + "/uid";
        // Set data path where database will be created in this folder
        setting.setDataPath(dataPath);
        File file = new File(dataPath);
        if (!file.exists()) {
            // noinspection ResultOfMethodCallIgnored
            file.mkdir();
        }
        // App Key
        setting.setAppKey(config.appKey);
        // App ID
        setting.setAppID(config.appId);
        // App Name
        setting.setAppName(context.getResources().getString(R.string.app_name));
        // App version
        setting.setAppVersion(BuildConfig.VERSION_NAME);
        // Device id (Simple way below)
        @SuppressLint("HardwareIds")
        String deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        setting.setDeviceId(deviceId);
        // Device name
        setting.setDeviceName(android.os.Build.MODEL);
        // Device type
        setting.setDeviceType(android.os.Build.BRAND);
        // Local
        setting.setDeviceLocale(Locale.getDefault().getLanguage());
        // OS Name
        setting.setOSName("Android");
        // OS version
        setting.setOSVersion(android.os.Build.VERSION.RELEASE);
        // Long link conn type,
          setting.setLongLinkConnectionType(DPSConnectionType.CONNECTION_TYPE_BIFROST);
        // Long link addr
        setting.setLonglinkServerAddress(config.longLinkUrl);
        // File upload server addr, provide when needed
        setting.setFileUploadServerAddress(config.fileUploadUrl);
        // Media host
        ArrayList<DPSMediaHost> mediaHosts = new ArrayList<>();
        mediaHosts.add(new DPSMediaHost(DPSMediaHostType.MEDIA_HOST_TYPE_AUTH, config.mediaHost));
        setting.setMediaHost(mediaHosts);
        // File upload connection type.
          setting.setFileUploadConnectionType(DPSConnectionType.CONNECTION_TYPE_DINGTALK_FILE);
        setting.setDisableSslVerify(true);
        // Auth Token callback
        setting.setAuthTokenCallback(new DPSPubAuthTokenCallback() {
            @Override
            public void onCallback(String userId, DPSAuthTokenGotCallback onGot, DPSAuthTokenExpiredReason reason) {
                Auth.getToken(context, userId, onGot);
            }
        });
    }
  3. 创建Manager。
    DPSUserId dpsUserId = new DPSUserId();
    dpsUserId.uid = getInputValue("userId");
    dpsUserId.domain = Environments.APP_ID;
    InteractionManager.instance().getDPSManager(dpsUserId, new Callback<InteractionModule, String>() {
        @Override
        public void onSuccess(InteractionModule data) {
            T("创建Manager成功");
            // 此处暂存该变量, 后面获取服务会用到
            InteractionModule manager = InteractionModule.getInteractionManager(dpsUserId);
        }
        @Override
        public void onFailure(String msg) {
            T("创建Manager失败: " + msg, true);
        }
    });
  4. 登录认证。
    DPSPubEngine engine = DPSPubEngine.GetDPSEngine();
    if (engine == null) {
        callback.onFailure("engine is null");
        return;
    }
    DPSPubManager manager = engine.getDPSManager(uid);
    if (manager == null) {
        callback.onFailure("manager is null");
        return;
    }
    DPSAuthService authService = manager.getAuthService();
    if (authService == null) {
        callback.onFailure("authService is null");
        return;
    }
    DPSConnectionStatus status = authService.getConnectionStatus();
    if (status == DPSConnectionStatus.CS_AUTHED) {
        callback.onFailure("Already authed, no need login");
        return;
    }
    authService.removeAllListeners();
    authService.addListener(new DPSAuthListener() {
        @Override
        public void onConnectionStatusChanged(DPSConnectionStatus aimConnectionStatus) {
                  Logger.i("OnConnectionStatusChanged " + aimConnectionStatus.toString())  ;
                    if (aimConnectionStatus == DPSConnectionStatus.CS_AUTHED) {
                            authService.removeListener(this);
                        callback.onSuccess(null);
                    }
        }
        @Override
        public void onGetAuthCodeFailed(int i, String s) {
            authService.removeListener(this);
                    callback.onFailure(errorMsg);
        }
        @Override
        public void onLocalLogin() {
            Logger.i("local login succeed");
        }
        @Override
        public void onKickout(String s) {
            Logger.i("OnKickout " + s);
        }
        /**
         * 其他端设备在(离)线情况
         * @param type 事件类型(1:事件通知,包括上下线,2:状态通知,在线状态)
         * @param deviceType 设备类型
         * (0:default,1:web,2:Android,3:iOS,4:Mac,5:Windows,6:iPad)
         * @param status      设备状态(1:上线或在线,2:下线或离线)
         * @param time        时间(上线或下线时间)
         */
        @Override
        public void onDeviceStatus(int type, int deviceType, int status, long time) {
            Logger.i("OnDeviceStatus changed:");
        }
        /**
         * 下载资源cookie变更事件
         * @param cookie      新cookie
         */
        @Override
        public void onMainServerCookieRefresh(String cookie) {
            Logger.i("Cookie refreshed: " + cookie);
        }
    });
    Logger.i("Start login");
    authService.login();

服务部分工程接入

服务部分包括房间服务和消息服务。

房间部分
  1. 获取房间服务。
    InteractionRoomServiceInterface roomService = manager.getRoomService();
    if (roomService != null) {
        roomService.setListener(new InteractionRoomNotificationListener() {
            @Override
            public void onViewersCountNtf(DPSUserId dpsUserId, String var2, InteractionRoomViewerCountNtf var3) {
                Logger.i("房间数量发生变化: " + var3.onlineCount);
            }
            @Override
            public void onRoomNoticeNtf(DPSUserId dpsUserId, String var2, InteractionRoomNoticeNtf var3) {
                Logger.i("房间公告发生变化: " + var3.notice);
            }
        });
    }
  2. 进入房间。
    final String roomId = getInputValue("enterRoomId");
    final InteractionEnterRoomReq request = new InteractionEnterRoomReq();
    request.roomId = roomId;
    request.nick = "PKTest";
    roomService.enterRoom(request, new InteractionCommonCb() {
        @Override
        public void onSuccess() {
            MainActivity.this.roomId = roomId;
            T("进房间成功");
        }
        @Override
        public void onFailure(DPSError error) {
            T("进房间失败: " + error.toString(), true);
        }
    });
  3. 查询房间详情。
    InteractionGetRoomDetailReq request = new InteractionGetRoomDetailReq();
    request.roomId = getInputValue("detailRoomId");
    roomService.getRoomDetail(request, new InteractionGetRoomDeitalCb() {
        @Override
        public void onSuccess(InteractionGetRoomDetailRsp rsp) {
            T("查询房间成功: " + rsp.toString());
        }
        @Override
        public void onFailure(DPSError error) {
            T("查询房间失败: " + error.toString(), true);
        }
    });
  4. 发布房间公告。
    final InteractionPublishNoticeReq request = new InteractionPublishNoticeReq();
    request.roomId = getInputValue("publishNoticeRoomId");
    request.notice = getInputValue("publishNotice") + UUID.randomUUID().toString().substring(0, 5);
    roomService.publishRoomNotice(request, new InteractionCommonCb() {
        @Override
        public void onSuccess() {
            T("发布房间公告成功");
        }
        @Override
        public void onFailure(DPSError error) {
            T("发布房间公告失败: " + error.toString(), true);
        }
    });
  5. 离开房间。
    final InteractionLeaveRoomReq request = new InteractionLeaveRoomReq();
    request.roomId = getInputValue("leaveRoomId");
    roomService.leaveRoom(request, new InteractionCommonCb() {
        @Override
        public void onSuccess() {
            roomId = null;
            T("离开房间成功");
        }
        @Override
        public void onFailure(DPSError error) {
            T("离开房间失败: " + error.toString(), true);
        }
    });
消息部分
  1. 获取消息服务。
    InteractionMessageServiceInterface messageService = manager.getMessageService();
    if (messageService != null) {
        messageService.setListener(new InteractionMessageNotificationListener() {
            @Override
            public void onCommentNtf(DPSUserId dpsUserId, String var2, InteractionCommentNtf var3) {
                Logger.i("接收评论: " + var3.nick + ": " + var3.content);
            }
            @Override
            public void onLikesCountNtf(DPSUserId dpsUserId, String var2, InteractionLikesNtf var3) {
                Logger.i("接收点赞数: " + var3.likeCount);
            }
            @Override
            public void onCustomMessageNtf(DPSUserId dpsUserId, String var2, InteractionCustomMsgNtf var3) {
                Logger.i("接收自定义消息: " + var3.body);
            }
        });
    }
    return messageService;
  2. 点赞。
    InteractionSendLikesReq request = new InteractionSendLikesReq();
    request.roomId = roomId;
    request.count = 1;
    messageService.sendLikes(request, new InteractionSendLikesCb() {
        @Override
        public void onSuccess(InteractionSendLikesRsp data) {
            T("点赞成功: " + data.toString());
        }
        @Override
        public void onFailure(DPSError error) {
            T("点赞失败: " + error.toString(), true);
        }
    });
  3. 发文本消息。
    InteractionSendCommentReq request = new InteractionSendCommentReq();
    request.roomId = roomId;
    request.content = getInputValue("normalMessageText");
    messageService.sendComment(request, new InteractionSendCommentCb() {
        @Override
        public void onSuccess(InteractionSendCommentRsp data) {
            T("发消息成功: " + data.toString());
        }
        @Override
        public void onFailure(DPSError error) {
            T("发消息失败: " + error.toString(), true);
        }
    });
  4. 发自定义消息。
    InteractionSendCustomMessageReq request = new InteractionSendCustomMessageReq();
    request.roomId = roomId;
    request.subType = Integer.parseInt(getInputValue("customMessageSubType"));
    request.body = getInputValue("customMessageText");
    messageService.sendCustomMessage(request, new InteractionSendCustomMessageCb() {
        @Override
        public void onSuccess(InteractionSendCustomMessageRsp data) {
            T("发送自定义消息成功: " + data.toString());
        }
        @Override
        public void onFailure(DPSError error) {
            T("发送自定义消息失败: " + error.toString(), true);
        }
    });