├── .gitignore ├── .npmignore ├── LICENSE ├── LICENSE_EN ├── README.assets ├── 微信图片_20201002151638.jpg └── 微信图片_20201002151644-1601623124924.jpg ├── README.md ├── android ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── yunchao │ │ └── tencentim │ │ ├── IMApplication.java │ │ ├── TencentImUiPackage.java │ │ ├── activity │ │ ├── BaseActivity.java │ │ └── ChatActivity.java │ │ ├── common │ │ └── Constants.java │ │ ├── fragment │ │ └── ChatFragment.java │ │ ├── model │ │ ├── TencentIMConversationModel.java │ │ └── TencentIMModel.java │ │ └── utils │ │ ├── Foreground.java │ │ └── IMLog.java │ └── res │ └── layout │ ├── chat_activity.xml │ ├── chat_fragment.xml │ └── conversation.xml ├── demo ├── .buckconfig ├── .eslintrc.js ├── .flowconfig ├── .gitattributes ├── .gitignore ├── .prettierrc.js ├── .watchmanconfig ├── App.js ├── __tests__ │ └── App-test.js ├── android │ ├── app │ │ ├── _BUCK │ │ ├── build.gradle │ │ ├── build_defs.bzl │ │ ├── debug.keystore │ │ ├── proguard-rules.pro │ │ └── src │ │ │ └── main │ │ │ ├── AndroidManifest.xml │ │ │ ├── java │ │ │ └── com │ │ │ │ ├── huawei │ │ │ │ └── android │ │ │ │ │ └── hms │ │ │ │ │ └── agent │ │ │ │ │ ├── HMSAgent.java │ │ │ │ │ ├── common │ │ │ │ │ ├── ActivityMgr.java │ │ │ │ │ ├── ApiClientMgr.java │ │ │ │ │ ├── BaseAgentActivity.java │ │ │ │ │ ├── BaseApiAgent.java │ │ │ │ │ ├── CallbackCodeRunnable.java │ │ │ │ │ ├── CallbackResultRunnable.java │ │ │ │ │ ├── CheckUpdateApi.java │ │ │ │ │ ├── EmptyConnectCallback.java │ │ │ │ │ ├── HMSAgentActivity.java │ │ │ │ │ ├── HMSAgentLog.java │ │ │ │ │ ├── IActivityDestroyedCallback.java │ │ │ │ │ ├── IActivityPauseCallback.java │ │ │ │ │ ├── IActivityResumeCallback.java │ │ │ │ │ ├── IClientConnectCallback.java │ │ │ │ │ ├── INoProguard.java │ │ │ │ │ ├── IOUtils.java │ │ │ │ │ ├── StrUtils.java │ │ │ │ │ ├── ThreadUtil.java │ │ │ │ │ ├── UIUtils.java │ │ │ │ │ └── handler │ │ │ │ │ │ ├── CheckUpdateHandler.java │ │ │ │ │ │ ├── ConnectHandler.java │ │ │ │ │ │ ├── ICallbackCode.java │ │ │ │ │ │ └── ICallbackResult.java │ │ │ │ │ └── push │ │ │ │ │ ├── DeleteTokenApi.java │ │ │ │ │ ├── EnableReceiveNormalMsgApi.java │ │ │ │ │ ├── EnableReceiveNotifyMsgApi.java │ │ │ │ │ ├── GetPushStateApi.java │ │ │ │ │ ├── GetTokenApi.java │ │ │ │ │ ├── QueryAgreementApi.java │ │ │ │ │ └── handler │ │ │ │ │ ├── DeleteTokenHandler.java │ │ │ │ │ ├── EnableReceiveNormalMsgHandler.java │ │ │ │ │ ├── EnableReceiveNotifyMsgHandler.java │ │ │ │ │ ├── GetPushStateHandler.java │ │ │ │ │ ├── GetTokenHandler.java │ │ │ │ │ └── QueryAgreementHandler.java │ │ │ │ └── yunchao │ │ │ │ └── tencentim │ │ │ │ └── demo │ │ │ │ ├── DemoModule.java │ │ │ │ ├── DemoPackage.java │ │ │ │ ├── GenerateTestUserSig.java │ │ │ │ ├── MainActivity.java │ │ │ │ ├── MainApplication.java │ │ │ │ ├── thirdpush │ │ │ │ └── HUAWEIPushReceiver.java │ │ │ │ ├── thridpush │ │ │ │ └── MessageNotification.java │ │ │ │ └── utils │ │ │ │ ├── IMLog.java │ │ │ │ ├── PrivateConstants.java │ │ │ │ └── ThirdPushTokenMgr.java │ │ │ └── res │ │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ └── values │ │ │ ├── strings.xml │ │ │ └── styles.xml │ ├── build.gradle │ ├── gradle.properties │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ └── settings.gradle ├── app.json ├── babel.config.js ├── index.js ├── ios │ ├── Podfile │ ├── Podfile.lock │ ├── demo-tvOS │ │ └── Info.plist │ ├── demo-tvOSTests │ │ └── Info.plist │ ├── demo.xcodeproj │ │ ├── project.pbxproj │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ ├── demo-tvOS.xcscheme │ │ │ └── demo.xcscheme │ ├── demo.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ ├── demo │ │ ├── AppDelegate.h │ │ ├── AppDelegate.m │ │ ├── DemoModule.h │ │ ├── DemoModule.m │ │ ├── GenerateTestUserSig.h │ │ ├── GenerateTestUserSig.m │ │ ├── Images.xcassets │ │ │ ├── AppIcon.appiconset │ │ │ │ └── Contents.json │ │ │ └── Contents.json │ │ ├── Info.plist │ │ ├── LaunchScreen.storyboard │ │ └── main.m │ └── demoTests │ │ ├── Info.plist │ │ └── demoTests.m ├── metro.config.js ├── package.json ├── readme.md ├── src │ ├── conView.js │ └── genSig.js └── yarn.lock ├── index.js ├── ios ├── TxImUi │ ├── Controller │ │ ├── ChatViewController.h │ │ ├── ChatViewController.m │ │ ├── ConversationController.h │ │ └── ConversationController.m │ ├── Custom │ │ ├── MyCustomCell.h │ │ ├── MyCustomCell.m │ │ ├── MyCustomCellData.h │ │ └── MyCustomCellData.m │ ├── TencentIMConversationModel.h │ ├── TencentIMConversationModel.m │ ├── TencentIMModel.h │ ├── TencentIMModel.m │ ├── Util │ │ ├── PAirSandbox.h │ │ ├── PAirSandbox.m │ │ ├── TCConstants.h │ │ ├── TCUtil.h │ │ ├── TCUtil.m │ │ ├── TencentIMManager.h │ │ └── TencentIMManager.m │ └── model │ │ ├── ConversationView.h │ │ └── ConversationView.m ├── TximUi.xcodeproj │ └── project.pbxproj └── TximUi.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ └── IDEWorkspaceChecks.plist ├── lib ├── ConversationView.js └── TencentIMModel.js ├── package.json ├── react-native-tencent-im-ui.podspec └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # node.js 6 | # 7 | node_modules/ 8 | npm-debug.log 9 | yarn-error.log 10 | 11 | # Xcode 12 | # 13 | build/ 14 | *.pbxuser 15 | !default.pbxuser 16 | *.mode1v3 17 | !default.mode1v3 18 | *.mode2v3 19 | !default.mode2v3 20 | *.perspectivev3 21 | !default.perspectivev3 22 | xcuserdata 23 | *.xccheckout 24 | *.moved-aside 25 | DerivedData 26 | *.hmap 27 | *.ipa 28 | *.xcuserstate 29 | project.xcworkspace 30 | 31 | # Android/IntelliJ 32 | # 33 | build/ 34 | .idea 35 | .gradle 36 | local.properties 37 | *.iml 38 | 39 | # BUCK 40 | buck-out/ 41 | \.buckd/ 42 | *.keystore 43 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | *.iml 3 | .idea 4 | .gradle 5 | build 6 | local.properties 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 版权所有(c)<年份><版权持有人> 2 | 3 | 反996许可证版本1.0 4 | 5 | 在符合下列条件的情况下,特此免费向任何得到本授权作品的副本(包括源代码、文件和/或相关内容,以 6 | 下统称为“授权作品”)的个人和法人实体授权:被授权个人或法人实体有权以任何目的处置授权作品,包括 7 | 但不限于使用、复制,修改,衍生利用、散布,发布和再许可: 8 | 9 | 1. 个人或法人实体必须在许可作品的每个再散布或衍生副本上包含以上版权声明和本许可证,不得自行修 10 | 改。 11 | 2. 个人或法人实体必须严格遵守与个人实际所在地或个人出生地或归化地、或法人实体注册地或经营地( 12 | 以较严格者为准)的司法管辖区所有适用的与劳动和就业相关法律、法规、规则和标准。如果该司法管辖区 13 | 没有此类法律、法规、规章和标准或其法律、法规、规章和标准不可执行,则个人或法人实体必须遵守国际 14 | 劳工标准的核心公约。 15 | 3. 个人或法人不得以任何方式诱导、暗示或强迫其全职或兼职员工或其独立承包人以口头或书面形式同意 16 | 直接或间接限制、削弱或放弃其所拥有的,受相关与劳动和就业有关的法律、法规、规则和标准保护的权利 17 | 或补救措施,无论该等书面或口头协议是否被该司法管辖区的法律所承认,该等个人或法人实体也不得以任 18 | 何方法限制其雇员或独立承包人向版权持有人或监督许可证合规情况的有关当局报告或投诉上述违反许可证 19 | 的行为的权利。 20 | 21 | 该授权作品是"按原样"提供,不做任何明示或暗示的保证,包括但不限于对适销性、特定用途适用性和非侵 22 | 权性的保证。在任何情况下,无论是在合同诉讼、侵权诉讼或其他诉讼中,版权持有人均不承担因本软件或 23 | 本软件的使用或其他交易而产生、引起或与之相关的任何索赔、损害或其他责任。 24 | -------------------------------------------------------------------------------- /LICENSE_EN: -------------------------------------------------------------------------------- 1 | Copyright (c) 2 | 3 | "Anti 996" License Version 1.0 (Draft) 4 | 5 | Permission is hereby granted to any individual or legal entity 6 | obtaining a copy of this licensed work (including the source code, 7 | documentation and/or related items, hereinafter collectively referred 8 | to as the "licensed work"), free of charge, to deal with the licensed 9 | work for any purpose, including without limitation, the rights to use, 10 | reproduce, modify, prepare derivative works of, distribute, publish 11 | and sublicense the licensed work, subject to the following conditions: 12 | 13 | 1. The individual or the legal entity must conspicuously display, 14 | without modification, this License and the notice on each redistributed 15 | or derivative copy of the Licensed Work. 16 | 17 | 2. The individual or the legal entity must strictly comply with all 18 | applicable laws, regulations, rules and standards of the jurisdiction 19 | relating to labor and employment where the individual is physically 20 | located or where the individual was born or naturalized; or where the 21 | legal entity is registered or is operating (whichever is stricter). In 22 | case that the jurisdiction has no such laws, regulations, rules and 23 | standards or its laws, regulations, rules and standards are 24 | unenforceable, the individual or the legal entity are required to 25 | comply with Core International Labor Standards. 26 | 27 | 3. The individual or the legal entity shall not induce, suggest or force 28 | its employee(s), whether full-time or part-time, or its independent 29 | contractor(s), in any methods, to agree in oral or written form, to 30 | directly or indirectly restrict, weaken or relinquish his or her 31 | rights or remedies under such laws, regulations, rules and standards 32 | relating to labor and employment as mentioned above, no matter whether 33 | such written or oral agreements are enforceable under the laws of the 34 | said jurisdiction, nor shall such individual or the legal entity 35 | limit, in any methods, the rights of its employee(s) or independent 36 | contractor(s) from reporting or complaining to the copyright holder or 37 | relevant authorities monitoring the compliance of the license about 38 | its violation(s) of the said license. 39 | 40 | THE LICENSED WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 41 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 42 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 43 | IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, 44 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 45 | OTHERWISE, ARISING FROM, OUT OF OR IN ANY WAY CONNECTION WITH THE 46 | LICENSED WORK OR THE USE OR OTHER DEALINGS IN THE LICENSED WORK. 47 | -------------------------------------------------------------------------------- /README.assets/微信图片_20201002151638.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/README.assets/微信图片_20201002151638.jpg -------------------------------------------------------------------------------- /README.assets/微信图片_20201002151644-1601623124924.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/README.assets/微信图片_20201002151644-1601623124924.jpg -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-native-tencent-im-ui 腾讯云即时通信 IM 服务的react-native,使用原生ui版本得sdk 2 | 3 | 起因,项目中需要用到基础的im功能(聊天和聊天列表),晚上搜了一圈也没有找到,技术栈已经定好,也只能硬着头皮搞了。 4 | 5 | 直接给大家分享出来,目前功能简单,如果有简单需求的可以直接使用。 6 | 7 | 当前基于 TIMSDK UI版本 标准版 5.0.6 @2020.09.18 8 | 9 | 项目地址:[https://github.com/mengyou658/react-native-tencent-im-ui](https://github.com/mengyou658/react-native-tencent-im-ui) 10 | 11 | ## 一、支持功能 12 | 13 | 1. 聊天列表功能 14 | 15 | 1. 聊天功能 16 | 17 | ## 二、待支持的功能 18 | 19 | 1. 不支持自定义界面(可以yarn install 后,在node_models/react-native-tencent-im-ui/更改里面的代码或者直接clone项目复制先来粘贴过去改吧,虽然不方便,但是也能实现,一个个封装代码都不够项目成本的😂) 20 | 21 | 1. 离线消息 22 | 23 | 1. 用户信息编辑 24 | 25 | 1. 加好友 26 | 27 | 1. 等等。。。 28 | 29 | ## 三、支持版本 30 | 31 | react-native 0.60 以上版本 32 | 33 | ## 四、如何安装 34 | 35 | ### 4.1.安装包 36 | 37 | 注意需要 --save 参数,react-native会自动link 38 | 39 | `$ npm install react-native-tencent-im-ui --save` 40 | 41 | `$ yarn add react-native-tencent-im-ui ` 42 | 43 | ### 4.2. link 44 | 45 | react-native 0.60以上 使用的autolink,注意需要 --save 参数,react-native会自动link 46 | 47 | #### 4.2.1 android 特别处理 48 | 49 | 1. **需要在AndroidManifest.xml增加 activity** 50 | 51 | `` 52 | 53 | 1. **在你自己的项目中的,android/app/src/main/java/<你的包名>/MainApplication.java 中onCreate()方法中增加如下** 54 | 55 | ```java 56 | 57 | @Override 58 | 59 | public void onCreate() { 60 | 61 | super.onCreate(); 62 | 63 | SoLoader.init(this, /* native exopackage */ false); 64 | 65 | ... 66 | 67 | // 然后添加这一行,这里很重要,initSdk中使用到这个,初始化必须在主Application中初始化,否则会出现线程错误问题 68 | 69 | IMApplication.setContext(this, MainActivity.class); 70 | 71 | ... 72 | 73 | } 74 | 75 | ``` 76 | 77 | 1. demo 中增加的有华为push的示例(使用的低版本的push,高版本的总是提示安装hms-core,有点烦),完整的请参考腾讯im-sdk内的demo 78 | 79 | #### 4.2.2 ios 特别处理 80 | 81 | 1. **在你自己的项目中的,AppDelegate.m** 82 | 83 | ```object 84 | 85 | ... 86 | 87 | // 引入头文件 88 | 89 | #import "ConversationController.h" 90 | 91 | ... 92 | 93 | // 方法 didFinishLaunchingWithOptions 中修改 94 | 95 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 96 | 97 | ... 98 | 99 | // 下面一行更改为 100 | 101 | // self.window.rootViewController = rootViewController; 102 | 103 | UINavigationController *nv = [[UINavigationController alloc] initWithRootViewController:rootViewController]; 104 | 105 | nv.navigationBar.hidden = YES; 106 | 107 | nv.delegate = self; 108 | 109 | self.window.rootViewController = nv; 110 | 111 | ConversationController *c = [ConversationController getInstance]; 112 | 113 | [c initNc: nv]; 114 | 115 | ... 116 | 117 | ``` 118 | 119 | ## 五、示例 请参考 demo 文件夹 120 | 注意,LiteAVSDK_TRTC不支持模拟器运行,请使用真机运行 121 | 122 | android demo 截图 123 | 124 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20201002214658908.jpg#pic_center) 125 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20201002214658906.jpg#pic_center) 126 | 127 | ios demo 截图(同上,忘记截图了) 128 | 129 | ## 六、接口 130 | 131 | ```javascript 132 | 133 | /** 134 | 135 | * 初始化 136 | 137 | * @param sdkAppId 138 | 139 | */ 140 | 141 | export function TIMInitSdk(sdkAppId); 142 | 143 | /** 144 | 145 | * 登录 146 | 147 | * @param userId 用户id 148 | 149 | * @param userSig 用户sig 150 | 151 | * @returns {*|PromiseLike<*>|Promise<*>} 152 | 153 | */ 154 | 155 | export function TIMLogin(userId, userSig); 156 | 157 | /** 158 | 159 | * 登出 160 | 161 | * @returns {Promise<*>} 162 | 163 | */ 164 | 165 | export async function TIMLogout(); 166 | 167 | /** 168 | 169 | * 从其他界面跳转到聊天界面 170 | 171 | * @param userId im用户id 172 | 173 | * @param conTitle 聊天标题 174 | 175 | * @param type: 176 | 177 | * 1 = 用户会话 178 | 179 | * 2 = 分组会话 180 | 181 | */ 182 | 183 | export function TIMStartChat(userId, conTitle, type = 1); 184 | 185 | ``` 186 | 187 | ## 七、使用示例 188 | 189 | 先初始化 190 | 191 | ```javascript 192 | 193 | import {TIMConversationModel, TIMInitSdk, TIMLogin, TIMLogout, TIMStartChat} from 'react-native-tencent-im-ui'; 194 | 195 | // 先初始化 196 | 197 | TIMInitSdk(sdkAppId); 198 | 199 | ``` 200 | 201 | 调用登录 202 | 203 | ```javascript 204 | 205 | import {TIMConversationModel, TIMInitSdk, TIMLogin, TIMLogout, TIMStartChat} from 'react-native-tencent-im-ui'; 206 | 207 | // 调用登录 208 | 209 | TIMLogin(userId, userSig).then(res=>{ 210 | 211 | console.log(res); 212 | 213 | }).catch(e => { 214 | 215 | }); 216 | 217 | ``` 218 | 219 | 从其他界面跳转打开会话 220 | 221 | ```javascript 222 | 223 | import {TIMConversationModel, TIMInitSdk, TIMLogin, TIMLogout, TIMStartChat} from 'react-native-tencent-im-ui'; 224 | 225 | // 从其他界面跳转打开会话 226 | 227 | TIMStartChat(userId, "xxx聊天", 1); 228 | 229 | ``` 230 | 231 | 展示聊天列表界面 232 | 233 | ```javascript 234 | 235 | // 展示聊天列表界面 236 | 237 | import {TIMConversationModel, TIMInitSdk, TIMLogin, TIMLogout, TIMStartChat} from 'react-native-tencent-im-ui'; 238 | 239 | import React from "react"; 240 | 241 | import { 242 | 243 | SafeAreaView, 244 | 245 | StatusBar, 246 | 247 | } from 'react-native'; 248 | 249 | export default class Conversation extends React.Component{ 250 | 251 | render() { 252 | 253 | return 254 | 255 | 256 | 257 | } 258 | 259 | } 260 | 261 | ``` 262 | 263 | ### 参考鸣谢项目 264 | 265 | 1. [https://github.com/yz1311/react-native-txim/](https://github.com/yz1311/react-native-txim/) 266 | 267 | 1. [https://github.com/kurisu994/react-native-txim](https://github.com/kurisu994/react-native-txim) 268 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | // android/build.gradle 2 | 3 | // based on: 4 | // 5 | // * https://github.com/facebook/react-native/blob/0.60-stable/template/android/build.gradle 6 | // original location: 7 | // - https://github.com/facebook/react-native/blob/0.58-stable/local-cli/templates/HelloWorld/android/build.gradle 8 | // 9 | // * https://github.com/facebook/react-native/blob/0.60-stable/template/android/app/build.gradle 10 | // original location: 11 | // - https://github.com/facebook/react-native/blob/0.58-stable/local-cli/templates/HelloWorld/android/app/build.gradle 12 | 13 | def DEFAULT_COMPILE_SDK_VERSION = 28 14 | def DEFAULT_BUILD_TOOLS_VERSION = '28.0.3' 15 | def DEFAULT_MIN_SDK_VERSION = 19 16 | def DEFAULT_TARGET_SDK_VERSION = 28 17 | 18 | def safeExtGet(prop, fallback) { 19 | rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback 20 | } 21 | 22 | apply plugin: 'com.android.library' 23 | apply plugin: 'maven' 24 | 25 | buildscript { 26 | // The Android Gradle plugin is only required when opening the android folder stand-alone. 27 | // This avoids unnecessary downloads and potential conflicts when the library is included as a 28 | // module dependency in an application project. 29 | // ref: https://docs.gradle.org/current/userguide/tutorial_using_tasks.html#sec:build_script_external_dependencies 30 | if (project == rootProject) { 31 | repositories { 32 | google() 33 | jcenter() 34 | } 35 | dependencies { 36 | classpath 'com.android.tools.build:gradle:3.4.1' 37 | } 38 | } 39 | } 40 | 41 | apply plugin: 'com.android.library' 42 | apply plugin: 'maven' 43 | 44 | android { 45 | compileSdkVersion safeExtGet('compileSdkVersion', DEFAULT_COMPILE_SDK_VERSION) 46 | buildToolsVersion safeExtGet('buildToolsVersion', DEFAULT_BUILD_TOOLS_VERSION) 47 | defaultConfig { 48 | minSdkVersion safeExtGet('minSdkVersion', DEFAULT_MIN_SDK_VERSION) 49 | targetSdkVersion safeExtGet('targetSdkVersion', DEFAULT_TARGET_SDK_VERSION) 50 | versionCode 1 51 | versionName "1.0" 52 | multiDexEnabled true 53 | } 54 | lintOptions { 55 | abortOnError false 56 | } 57 | 58 | packagingOptions { 59 | pickFirst "**/libc++_shared.so" 60 | doNotStrip '*/armeabi/libYTCommon.so' 61 | doNotStrip '*/armeabi-v7a/libYTCommon.so' 62 | doNotStrip '*/x86/libYTCommon.so' 63 | doNotStrip '*/arm64-v8a/libYTCommon.so' 64 | } 65 | compileOptions { 66 | sourceCompatibility JavaVersion.VERSION_1_8 67 | targetCompatibility JavaVersion.VERSION_1_8 68 | } 69 | } 70 | 71 | repositories { 72 | // ref: https://www.baeldung.com/maven-local-repository 73 | mavenLocal() 74 | maven { 75 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 76 | url "$rootDir/../node_modules/react-native/android" 77 | } 78 | maven { 79 | // Android JSC is installed from npm 80 | url "$rootDir/../node_modules/jsc-android/dist" 81 | } 82 | google() 83 | jcenter() 84 | } 85 | 86 | dependencies { 87 | //noinspection GradleDynamicVersion 88 | implementation 'com.facebook.react:react-native:+' // From node_modules 89 | implementation 'com.tencent.imsdk:tuikit:5.0.6' 90 | implementation group: 'com.tencent.liteav', name: 'LiteAVSDK_TRTC', version: '7.2.8949' 91 | implementation 'com.google.code.gson:gson:2.8.6' 92 | implementation 'androidx.appcompat:appcompat:1.0.0' 93 | implementation 'androidx.recyclerview:recyclerview:1.0.0' 94 | 95 | // Optional, if you use support library fragments: 96 | debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.2' 97 | debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.2' 98 | releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.2' 99 | } 100 | 101 | def configureReactNativePom(def pom) { 102 | def packageJson = new groovy.json.JsonSlurper().parseText(file('../package.json').text) 103 | 104 | pom.project { 105 | name packageJson.title 106 | artifactId packageJson.name 107 | version = packageJson.version 108 | group = "com.yunchao.tencentim" 109 | description packageJson.description 110 | url packageJson.repository.baseUrl 111 | 112 | licenses { 113 | license { 114 | name packageJson.license 115 | url packageJson.repository.baseUrl + '/blob/master/' + packageJson.licenseFilename 116 | distribution 'repo' 117 | } 118 | } 119 | 120 | developers { 121 | developer { 122 | id packageJson.author.username 123 | name packageJson.author.name 124 | } 125 | } 126 | } 127 | } 128 | 129 | afterEvaluate { project -> 130 | // some Gradle build hooks ref: 131 | // https://www.oreilly.com/library/view/gradle-beyond-the/9781449373801/ch03.html 132 | task androidJavadoc(type: Javadoc) { 133 | source = android.sourceSets.main.java.srcDirs 134 | classpath += files(android.bootClasspath) 135 | classpath += files(project.getConfigurations().getByName('compile').asList()) 136 | include '**/*.java' 137 | } 138 | 139 | task androidJavadocJar(type: Jar, dependsOn: androidJavadoc) { 140 | classifier = 'javadoc' 141 | from androidJavadoc.destinationDir 142 | } 143 | 144 | task androidSourcesJar(type: Jar) { 145 | classifier = 'sources' 146 | from android.sourceSets.main.java.srcDirs 147 | include '**/*.java' 148 | } 149 | 150 | android.libraryVariants.all { variant -> 151 | def name = variant.name.capitalize() 152 | def javaCompileTask = variant.javaCompileProvider.get() 153 | 154 | task "jar${name}"(type: Jar, dependsOn: javaCompileTask) { 155 | from javaCompileTask.destinationDir 156 | } 157 | } 158 | 159 | artifacts { 160 | archives androidSourcesJar 161 | archives androidJavadocJar 162 | } 163 | 164 | task installArchives(type: Upload) { 165 | configuration = configurations.archives 166 | repositories.mavenDeployer { 167 | // Deploy to react-native-event-bridge/maven, ready to publish to npm 168 | repository url: "file://${projectDir}/../android/maven" 169 | configureReactNativePom pom 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | 88 | @rem Execute Gradle 89 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 90 | 91 | :end 92 | @rem End local scope for the variables with windows NT shell 93 | if "%ERRORLEVEL%"=="0" goto mainEnd 94 | 95 | :fail 96 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 97 | rem the _cmd.exe /c_ return code! 98 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 99 | exit /b 1 100 | 101 | :mainEnd 102 | if "%OS%"=="Windows_NT" endlocal 103 | 104 | :omega 105 | -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /android/src/main/java/com/yunchao/tencentim/IMApplication.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | import com.yunchao.tencentim.utils.Foreground; 6 | 7 | public class IMApplication { 8 | 9 | private static Context context; 10 | 11 | private static Class mainActivityClass; 12 | 13 | public static void setContext(final Context context, Class mainActivityClass) { 14 | Foreground.init((Application)context); 15 | IMApplication.context = context.getApplicationContext(); 16 | IMApplication.mainActivityClass = mainActivityClass; 17 | } 18 | 19 | public static Context getContext() { 20 | return context; 21 | } 22 | 23 | public static Class getMainActivityClass() { 24 | return mainActivityClass; 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /android/src/main/java/com/yunchao/tencentim/TencentImUiPackage.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim; 2 | 3 | import com.facebook.react.ReactPackage; 4 | import com.facebook.react.bridge.NativeModule; 5 | import com.facebook.react.bridge.ReactApplicationContext; 6 | import com.facebook.react.uimanager.ViewManager; 7 | import com.yunchao.tencentim.model.TencentIMConversationModel; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | public class TencentImUiPackage implements ReactPackage { 13 | 14 | @Override 15 | public List createNativeModules(ReactApplicationContext reactContext) { 16 | List list = new ArrayList<>(); 17 | list.add(new com.yunchao.tencentim.model.TencentIMModel(reactContext)); 18 | return list; 19 | } 20 | 21 | 22 | @Override 23 | public List createViewManagers(ReactApplicationContext reactContext) { 24 | List modules = new ArrayList<>(); 25 | modules.add(new TencentIMConversationModel()); 26 | return modules; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /android/src/main/java/com/yunchao/tencentim/activity/BaseActivity.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.activity; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.SharedPreferences; 7 | import android.os.Build; 8 | import android.os.Bundle; 9 | import android.view.View; 10 | import android.view.WindowManager; 11 | import com.tencent.qcloud.tim.uikit.TUIKit; 12 | import com.tencent.qcloud.tim.uikit.base.IMEventListener; 13 | import com.tencent.qcloud.tim.uikit.utils.ToastUtil; 14 | import com.yunchao.tencentim.R; 15 | import com.yunchao.tencentim.common.Constants; 16 | import com.yunchao.tencentim.utils.IMLog; 17 | 18 | 19 | /** 20 | * 登录状态的Activity都要集成该类,来完成被踢下线等监听处理。 21 | */ 22 | public class BaseActivity extends Activity { 23 | 24 | private static final String TAG = BaseActivity.class.getSimpleName(); 25 | 26 | public static void logout(Context context, boolean autoLogin) { 27 | SharedPreferences shareInfo = context.getSharedPreferences(Constants.USERINFO, Context.MODE_PRIVATE); 28 | SharedPreferences.Editor editor = shareInfo.edit(); 29 | editor.putBoolean(Constants.AUTO_LOGIN, autoLogin); 30 | editor.commit(); 31 | } 32 | 33 | @Override 34 | protected void onCreate( Bundle savedInstanceState) { 35 | IMLog.i(TAG, "onCreate"); 36 | super.onCreate(savedInstanceState); 37 | 38 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 39 | getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); 40 | getWindow().setStatusBarColor(getResources().getColor(R.color.status_bar_color)); 41 | getWindow().setNavigationBarColor(getResources().getColor(R.color.navigation_bar_color)); 42 | int vis = getWindow().getDecorView().getSystemUiVisibility(); 43 | vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; 44 | vis |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; 45 | getWindow().getDecorView().setSystemUiVisibility(vis); 46 | } 47 | 48 | TUIKit.addIMEventListener(new IMEventListener() { 49 | @Override 50 | public void onForceOffline() { 51 | ToastUtil.toastLongMessage("您的帐号已在其它终端登录"); 52 | logout(BaseActivity.this.getApplicationContext(), false); 53 | } 54 | }); 55 | } 56 | 57 | @Override 58 | protected void onStart() { 59 | IMLog.i(TAG, "onStart"); 60 | super.onStart(); 61 | SharedPreferences shareInfo = getSharedPreferences(Constants.USERINFO, Context.MODE_PRIVATE); 62 | boolean login = shareInfo.getBoolean(Constants.AUTO_LOGIN, false); 63 | if (!login) { 64 | BaseActivity.logout(getApplicationContext(), false); 65 | } 66 | } 67 | 68 | @Override 69 | protected void onResume() { 70 | IMLog.i(TAG, "onResume"); 71 | super.onResume(); 72 | } 73 | 74 | @Override 75 | protected void onPause() { 76 | IMLog.i(TAG, "onPause"); 77 | super.onPause(); 78 | } 79 | 80 | @Override 81 | protected void onStop() { 82 | IMLog.i(TAG, "onStop"); 83 | super.onStop(); 84 | } 85 | 86 | @Override 87 | protected void onDestroy() { 88 | IMLog.i(TAG, "onDestroy"); 89 | super.onDestroy(); 90 | } 91 | 92 | @Override 93 | protected void onNewIntent(Intent intent) { 94 | IMLog.i(TAG, "onNewIntent"); 95 | super.onNewIntent(intent); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /android/src/main/java/com/yunchao/tencentim/activity/ChatActivity.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.activity; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo; 6 | import com.yunchao.tencentim.R; 7 | import com.yunchao.tencentim.common.Constants; 8 | import com.yunchao.tencentim.fragment.ChatFragment; 9 | import com.yunchao.tencentim.utils.IMLog; 10 | 11 | public class ChatActivity extends com.yunchao.tencentim.activity.BaseActivity { 12 | 13 | private static final String TAG = ChatActivity.class.getSimpleName(); 14 | 15 | private ChatFragment mChatFragment; 16 | public static ChatInfo mChatInfo; 17 | 18 | @Override 19 | protected void onCreate( Bundle savedInstanceState) { 20 | super.onCreate(savedInstanceState); 21 | setContentView(R.layout.chat_activity); 22 | chat(getIntent()); 23 | } 24 | 25 | @Override 26 | protected void onNewIntent(Intent intent) { 27 | IMLog.i(TAG, "onNewIntent"); 28 | super.onNewIntent(intent); 29 | chat(intent); 30 | } 31 | 32 | @Override 33 | protected void onResume() { 34 | IMLog.i(TAG, "onResume"); 35 | super.onResume(); 36 | } 37 | 38 | private void chat(Intent intent) { 39 | final Bundle bundle = intent.getExtras(); 40 | if (bundle == null) { 41 | return; 42 | } else { 43 | mChatInfo = (ChatInfo) bundle.getSerializable(Constants.CHAT_INFO); 44 | if (mChatInfo == null) { 45 | return; 46 | } 47 | mChatFragment = new ChatFragment(); 48 | mChatFragment.setArguments(bundle); 49 | getFragmentManager().beginTransaction().replace(R.id.empty_view, mChatFragment).commitAllowingStateLoss(); 50 | } 51 | } 52 | 53 | 54 | } 55 | -------------------------------------------------------------------------------- /android/src/main/java/com/yunchao/tencentim/common/Constants.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.common; 2 | 3 | 4 | public class Constants { 5 | 6 | // 存储 7 | public static final String USERINFO = "userInfo"; 8 | public static final String ACCOUNT = "account"; 9 | public static final String PWD = "password"; 10 | public static final String ROOM = "room"; 11 | public static final String AUTO_LOGIN = "auto_login"; 12 | public static final String LOGOUT = "logout"; 13 | public static final String ICON_URL = "icon_url"; 14 | 15 | public static final String CHAT_INFO = "chatInfo"; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /android/src/main/java/com/yunchao/tencentim/fragment/ChatFragment.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.fragment; 2 | 3 | import android.graphics.Color; 4 | import android.graphics.drawable.ColorDrawable; 5 | import android.os.Bundle; 6 | import android.util.Log; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import com.tencent.imsdk.TIMConversationType; 11 | import com.tencent.qcloud.tim.uikit.base.BaseFragment; 12 | import com.tencent.qcloud.tim.uikit.component.AudioPlayer; 13 | import com.tencent.qcloud.tim.uikit.component.TitleBarLayout; 14 | import com.tencent.qcloud.tim.uikit.modules.chat.ChatLayout; 15 | import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo; 16 | import com.tencent.qcloud.tim.uikit.modules.chat.layout.input.InputLayout; 17 | import com.tencent.qcloud.tim.uikit.modules.chat.layout.message.MessageLayout; 18 | import com.tencent.qcloud.tim.uikit.modules.message.MessageInfo; 19 | import com.yunchao.tencentim.R; 20 | import com.yunchao.tencentim.common.Constants; 21 | 22 | 23 | public class ChatFragment extends BaseFragment { 24 | 25 | private View mBaseView; 26 | public static ChatLayout mChatLayout; 27 | private TitleBarLayout mTitleBar; 28 | private InputLayout mInputLayout; 29 | private ChatInfo mChatInfo; 30 | 31 | 32 | @Override 33 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 34 | mBaseView = inflater.inflate(R.layout.chat_fragment, container, false); 35 | return mBaseView; 36 | } 37 | 38 | private void initView() { 39 | //从布局文件中获取聊天面板组件 40 | mChatLayout = mBaseView.findViewById(R.id.chat_layout); 41 | //单聊组件的默认UI和交互初始化 42 | mChatLayout.initDefault(); 43 | 44 | /* 45 | * 需要聊天的基本信息 46 | */ 47 | mChatLayout.setChatInfo(mChatInfo); 48 | 49 | 50 | //获取单聊面板的标题栏 51 | mTitleBar = mChatLayout.getTitleBar(); 52 | //隐藏右侧title显示按钮 53 | mTitleBar.getRightGroup().setVisibility(View.INVISIBLE); 54 | mTitleBar.setBackground(new ColorDrawable(Color.parseColor("#FFFFFF"))); 55 | 56 | // 从 ChatLayout 里获取 InputLayout 57 | mInputLayout = mChatLayout.getInputLayout(); 58 | mInputLayout.setBackground(new ColorDrawable(Color.parseColor("#FFFFFF"))); 59 | 60 | 61 | // 从ChatLayout 里获取 MessageLayout 62 | MessageLayout messageLayout = mChatLayout.getMessageLayout(); 63 | // 设置头像圆角,不设置则默认不做圆角处理 64 | messageLayout.setAvatarRadius(50); 65 | // 设置聊天背景 66 | // messageLayout.setBackground(new ColorDrawable(Color.parseColor("#F7F9F8"))); 67 | // 设置自己聊天气泡的背景 68 | // messageLayout.setRightBubble(getResources().getDrawable(R.drawable.chat_opposite_bg)); 69 | // 设置朋友聊天气泡的背景 70 | // messageLayout.setLeftBubble(getResources().getDrawable(R.drawable.chat_self_bg)); 71 | 72 | //单聊面板标记栏返回按钮点击事件,这里需要开发者自行控制 73 | mTitleBar.setOnLeftClickListener(new View.OnClickListener() { 74 | @Override 75 | public void onClick(View view) { 76 | getActivity().finish(); 77 | } 78 | }); 79 | if (mChatInfo.getType() == TIMConversationType.C2C.value()) { 80 | mTitleBar.setOnRightClickListener(new View.OnClickListener() { 81 | @Override 82 | public void onClick(View v) { 83 | // Intent intent = new Intent(MyApplication.instance(), FriendProfileActivity.class); 84 | // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 85 | // intent.putExtra(TUIKitConstants.ProfileType.CONTENT, mChatInfo); 86 | // MyApplication.instance().startActivity(intent); 87 | } 88 | }); 89 | } 90 | 91 | mChatLayout.getMessageLayout().setOnItemClickListener(new MessageLayout.OnItemClickListener() { 92 | @Override 93 | public void onMessageLongClick(View view, int position, MessageInfo messageInfo) { 94 | //因为adapter中第一条为加载条目,位置需减1 95 | mChatLayout.getMessageLayout().showItemPopMenu(position - 1, messageInfo, view); 96 | } 97 | 98 | @Override 99 | public void onUserIconClick(View view, int position, MessageInfo messageInfo) { 100 | if (null == messageInfo) { 101 | return; 102 | } 103 | // ChatInfo info = new ChatInfo(); 104 | // info.setId(messageInfo.getFromUser()); 105 | // Intent intent = new Intent(MyApplication.instance(), FriendProfileActivity.class); 106 | // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 107 | // intent.putExtra(TUIKitConstants.ProfileType.CONTENT, info); 108 | // MyApplication.instance().startActivity(intent); 109 | } 110 | }); 111 | } 112 | 113 | @Override 114 | public void onResume() { 115 | super.onResume(); 116 | 117 | Bundle bundle = getArguments(); 118 | mChatInfo = (ChatInfo) bundle.getSerializable(Constants.CHAT_INFO); 119 | if (mChatInfo == null) { 120 | return; 121 | } 122 | initView(); 123 | 124 | } 125 | 126 | @Override 127 | public void onPause() { 128 | super.onPause(); 129 | AudioPlayer.getInstance().stopPlay(); 130 | } 131 | 132 | @Override 133 | public void onDestroy() { 134 | super.onDestroy(); 135 | if (mChatLayout != null) { 136 | mChatLayout.exitChat(); 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /android/src/main/java/com/yunchao/tencentim/model/TencentIMConversationModel.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.model; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.graphics.Color; 6 | import android.graphics.drawable.ColorDrawable; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import com.facebook.react.uimanager.SimpleViewManager; 10 | import com.facebook.react.uimanager.ThemedReactContext; 11 | import com.tencent.imsdk.TIMConversationType; 12 | import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo; 13 | import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationLayout; 14 | import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationListLayout; 15 | import com.tencent.qcloud.tim.uikit.modules.conversation.base.ConversationInfo; 16 | import com.yunchao.tencentim.R; 17 | import com.yunchao.tencentim.activity.ChatActivity; 18 | import com.yunchao.tencentim.common.Constants; 19 | 20 | public class TencentIMConversationModel extends SimpleViewManager { 21 | 22 | private ConversationLayout mConversationLayout; 23 | 24 | @Override 25 | public String getName() { 26 | return "TencentIMConversationModel"; 27 | } 28 | 29 | @Override 30 | protected View createViewInstance(ThemedReactContext reactContext) { 31 | return createConversationView(reactContext); 32 | } 33 | 34 | private View createConversationView(ThemedReactContext reactContext) { 35 | View conversationView = LayoutInflater.from(reactContext).inflate(R.layout.conversation, null); 36 | initConversationView(conversationView, reactContext); 37 | return conversationView; 38 | } 39 | 40 | private void initConversationView(View conversationView, final Context context) { 41 | // 从布局文件中获取会话列表面板 42 | mConversationLayout = conversationView.findViewById(R.id.conversation_layout); 43 | // 会话列表面板的默认UI和交互初始化 44 | mConversationLayout.initDefault(); 45 | mConversationLayout.getTitleBar().getMiddleTitle().setText("会话列表"); 46 | mConversationLayout.getTitleBar().setVisibility(View.GONE); 47 | //隐藏titleBar 48 | mConversationLayout.setBackground(new ColorDrawable(Color.parseColor("#F7F9F8"))); 49 | // 设置adapter item头像圆角大小 50 | mConversationLayout.getConversationList().setItemAvatarRadius(100); 51 | mConversationLayout.getConversationList().setOnItemClickListener(new ConversationListLayout.OnItemClickListener() { 52 | @Override 53 | public void onItemClick(View view, int position, ConversationInfo conversationInfo) { 54 | //此处为demo的实现逻辑,更根据会话类型跳转到相关界面,开发者可根据自己的应用场景灵活实现 55 | startChatView(conversationInfo, context); 56 | } 57 | }); 58 | } 59 | 60 | private void startChatView(ConversationInfo conversationInfo, Context context) { 61 | ChatInfo chatInfo = new ChatInfo(); 62 | chatInfo.setType(conversationInfo.isGroup() ? TIMConversationType.Group.value(): TIMConversationType.C2C.value()); 63 | chatInfo.setId(conversationInfo.getId()); 64 | chatInfo.setChatName(conversationInfo.getTitle()); 65 | Intent intent = new Intent(context, ChatActivity.class); 66 | intent.putExtra(Constants.CHAT_INFO, chatInfo); 67 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 68 | context.startActivity(intent); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /android/src/main/java/com/yunchao/tencentim/model/TencentIMModel.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.model; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.os.Handler; 6 | import android.util.Log; 7 | import com.facebook.react.bridge.Promise; 8 | import com.facebook.react.bridge.ReactApplicationContext; 9 | import com.facebook.react.bridge.ReactContextBaseJavaModule; 10 | import com.facebook.react.bridge.ReactMethod; 11 | import com.tencent.imsdk.TIMCallBack; 12 | import com.tencent.imsdk.TIMConversationType; 13 | import com.tencent.imsdk.TIMManager; 14 | import com.tencent.qcloud.tim.uikit.TUIKit; 15 | import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack; 16 | import com.tencent.qcloud.tim.uikit.config.GeneralConfig; 17 | import com.tencent.qcloud.tim.uikit.config.TUIKitConfigs; 18 | import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo; 19 | import com.yunchao.tencentim.IMApplication; 20 | import com.yunchao.tencentim.activity.ChatActivity; 21 | import com.yunchao.tencentim.common.Constants; 22 | 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | import java.util.logging.LogRecord; 26 | 27 | 28 | public class TencentIMModel extends ReactContextBaseJavaModule { 29 | 30 | public TencentIMModel(ReactApplicationContext reactContext) { 31 | super(reactContext); 32 | } 33 | 34 | 35 | @Override 36 | public String getName() { 37 | return "TencentIMModel"; 38 | } 39 | 40 | public TUIKitConfigs getConfigs() { 41 | GeneralConfig config = new GeneralConfig(); 42 | // 显示对方是否已读的view将会展示 43 | config.setShowRead(true); 44 | config.setAppCacheDir(IMApplication.getContext().getFilesDir().getPath()); 45 | TUIKit.getConfigs().setGeneralConfig(config); 46 | return TUIKit.getConfigs(); 47 | } 48 | 49 | @ReactMethod 50 | public void initSdk(final int sdkAppId) { 51 | final Activity activity = getCurrentActivity(); 52 | if (null != activity) { 53 | activity.runOnUiThread(new Runnable() { 54 | @Override 55 | public void run() { 56 | TUIKit.init(IMApplication.getContext(), sdkAppId, getConfigs()); 57 | } 58 | }); 59 | } 60 | } 61 | 62 | @ReactMethod 63 | public void logout(final Promise promise) { 64 | final String loginUser = TIMManager.getInstance().getLoginUser(); 65 | TIMManager.getInstance().logout(new TIMCallBack() { 66 | @Override 67 | public void onError(int i, String s) { 68 | Map result = new HashMap<>(3); 69 | result.put("module", "onError"); 70 | result.put("code", -9999); 71 | result.put("desc", "登出失败"); 72 | promise.reject(result.toString(), new RuntimeException(s)); 73 | } 74 | 75 | @Override 76 | public void onSuccess() { 77 | Map result = new HashMap<>(3); 78 | result.put("module", "onSuccess"); 79 | result.put("code", 0); 80 | result.put("desc", "登出成功"); 81 | promise.resolve(result); 82 | } 83 | }); 84 | } 85 | 86 | 87 | @ReactMethod 88 | public void login(final String userId, String userSig, final Promise promise) { 89 | TUIKit.login(userId, userSig, new IUIKitCallBack() { 90 | @Override 91 | public void onError(String module, final int code, final String desc) { 92 | Map result = new HashMap<>(3); 93 | result.put("module", module); 94 | result.put("code", code); 95 | result.put("desc", desc); 96 | promise.reject(result.toString(), new RuntimeException(desc)); 97 | } 98 | 99 | @Override 100 | public void onSuccess(Object data) { 101 | Map result = new HashMap<>(3); 102 | result.put("module", "success"); 103 | result.put("code", 0); 104 | result.put("desc", "登录成功"); 105 | promise.resolve(data); 106 | } 107 | }); 108 | } 109 | 110 | @ReactMethod 111 | public void startChatView(String userId, String conTitle, int type) { 112 | final Activity activity = getCurrentActivity(); 113 | if (activity != null) { 114 | 115 | ChatInfo chatInfo = new ChatInfo(); 116 | if (type == 2) { 117 | chatInfo.setType(TIMConversationType.Group.value()); 118 | } else { 119 | chatInfo.setType(TIMConversationType.C2C.value()); 120 | } 121 | chatInfo.setId(userId); 122 | chatInfo.setChatName(conTitle); 123 | final Intent intent = new Intent(activity, ChatActivity.class); 124 | intent.putExtra(Constants.CHAT_INFO, chatInfo); 125 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 126 | activity.startActivity(intent); 127 | } 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /android/src/main/java/com/yunchao/tencentim/utils/Foreground.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.utils; 2 | 3 | 4 | import android.app.Activity; 5 | import android.app.Application; 6 | import android.os.Bundle; 7 | import android.os.Handler; 8 | import android.util.Log; 9 | 10 | public class Foreground implements Application.ActivityLifecycleCallbacks { 11 | 12 | //单例 13 | private static Foreground instance = new Foreground(); 14 | 15 | private static String TAG = Foreground.class.getSimpleName(); 16 | private final int CHECK_DELAY = 500; 17 | 18 | //用于判断是否程序在前台 19 | private boolean foreground = false, paused = true; 20 | //handler用于处理切换activity时的短暂时期可能出现的判断错误 21 | private Handler handler = new Handler(); 22 | private Runnable check; 23 | 24 | public static void init(Application app) { 25 | app.registerActivityLifecycleCallbacks(instance); 26 | } 27 | 28 | public static Foreground get() { 29 | return instance; 30 | } 31 | 32 | private Foreground() { 33 | } 34 | 35 | @Override 36 | public void onActivityCreated(Activity activity, Bundle savedInstanceState) { 37 | // TODO Auto-generated method stub 38 | 39 | } 40 | 41 | @Override 42 | public void onActivityDestroyed(Activity activity) { 43 | // TODO Auto-generated method stub 44 | 45 | } 46 | 47 | @Override 48 | public void onActivityPaused(Activity activity) { 49 | paused = true; 50 | if (check != null) { 51 | handler.removeCallbacks(check); 52 | } 53 | handler.postDelayed(check = () -> { 54 | if (foreground && paused) { 55 | foreground = false; 56 | Log.i(TAG, "went background"); 57 | } else { 58 | Log.i(TAG, "still foreground"); 59 | } 60 | }, CHECK_DELAY); 61 | 62 | } 63 | 64 | @Override 65 | public void onActivityResumed(Activity activity) { 66 | paused = false; 67 | foreground = true; 68 | if (check != null) { 69 | handler.removeCallbacks(check); 70 | } 71 | 72 | } 73 | 74 | @Override 75 | public void onActivitySaveInstanceState(Activity activity, Bundle outState) { 76 | // TODO Auto-generated method stub 77 | 78 | } 79 | 80 | @Override 81 | public void onActivityStarted(Activity activity) { 82 | // TODO Auto-generated method stub 83 | 84 | } 85 | 86 | @Override 87 | public void onActivityStopped(Activity activity) { 88 | // TODO Auto-generated method stub 89 | 90 | } 91 | 92 | public boolean isForeground() { 93 | return foreground; 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /android/src/main/java/com/yunchao/tencentim/utils/IMLog.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.utils; 2 | 3 | import com.tencent.imsdk.log.QLog; 4 | 5 | public class IMLog extends QLog { 6 | 7 | public static final String TAG = "TencentIM"; 8 | 9 | private static final String PRE = "TencentIM-TUIKit-"; 10 | 11 | private static String mixTag(String tag) { 12 | return PRE + tag; 13 | } 14 | 15 | /** 16 | * 打印INFO级别日志 17 | * 18 | * @param strTag TAG 19 | * @param strInfo 消息 20 | */ 21 | public static void v(String strTag, String strInfo) { 22 | QLog.v(mixTag(strTag), strInfo); 23 | } 24 | 25 | /** 26 | * 打印DEBUG级别日志 27 | * 28 | * @param strTag TAG 29 | * @param strInfo 消息 30 | */ 31 | public static void d(String strTag, String strInfo) { 32 | QLog.d(mixTag(strTag), strInfo); 33 | } 34 | 35 | /** 36 | * 打印INFO级别日志 37 | * 38 | * @param strTag TAG 39 | * @param strInfo 消息 40 | */ 41 | public static void i(String strTag, String strInfo) { 42 | QLog.i(mixTag(strTag), strInfo); 43 | } 44 | 45 | /** 46 | * 打印WARN级别日志 47 | * 48 | * @param strTag TAG 49 | * @param strInfo 消息 50 | */ 51 | public static void w(String strTag, String strInfo) { 52 | QLog.w(mixTag(strTag), strInfo); 53 | } 54 | 55 | /** 56 | * 打印ERROR级别日志 57 | * 58 | * @param strTag TAG 59 | * @param strInfo 消息 60 | */ 61 | public static void e(String strTag, String strInfo) { 62 | QLog.e(mixTag(strTag), strInfo); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /android/src/main/res/layout/chat_activity.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /android/src/main/res/layout/chat_fragment.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /android/src/main/res/layout/conversation.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /demo/.buckconfig: -------------------------------------------------------------------------------- 1 | 2 | [android] 3 | target = Google Inc.:Google APIs:23 4 | 5 | [maven_repositories] 6 | central = https://repo1.maven.org/maven2 7 | -------------------------------------------------------------------------------- /demo/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | extends: '@react-native-community', 4 | }; 5 | -------------------------------------------------------------------------------- /demo/.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | ; We fork some components by platform 3 | .*/*[.]android.js 4 | 5 | ; Ignore "BUCK" generated dirs 6 | /\.buckd/ 7 | 8 | ; Ignore polyfills 9 | node_modules/react-native/Libraries/polyfills/.* 10 | 11 | ; These should not be required directly 12 | ; require from fbjs/lib instead: require('fbjs/lib/warning') 13 | node_modules/warning/.* 14 | 15 | ; Flow doesn't support platforms 16 | .*/Libraries/Utilities/LoadingView.js 17 | 18 | [untyped] 19 | .*/node_modules/@react-native-community/cli/.*/.* 20 | 21 | [include] 22 | 23 | [libs] 24 | node_modules/react-native/interface.js 25 | node_modules/react-native/flow/ 26 | 27 | [options] 28 | emoji=true 29 | 30 | esproposal.optional_chaining=enable 31 | esproposal.nullish_coalescing=enable 32 | 33 | module.file_ext=.js 34 | module.file_ext=.json 35 | module.file_ext=.ios.js 36 | 37 | munge_underscores=true 38 | 39 | module.name_mapper='^react-native/\(.*\)$' -> '/node_modules/react-native/\1' 40 | module.name_mapper='^@?[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> '/node_modules/react-native/Libraries/Image/RelativeImageStub' 41 | 42 | suppress_type=$FlowIssue 43 | suppress_type=$FlowFixMe 44 | suppress_type=$FlowFixMeProps 45 | suppress_type=$FlowFixMeState 46 | 47 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(\\)? *\\(site=[a-z,_]*react_native\\(_ios\\)?_\\(oss\\|fb\\)[a-z,_]*\\)?)\\) 48 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(\\)? *\\(site=[a-z,_]*react_native\\(_ios\\)?_\\(oss\\|fb\\)[a-z,_]*\\)?)\\)?:? #[0-9]+ 49 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError 50 | 51 | [lints] 52 | sketchy-null-number=warn 53 | sketchy-null-mixed=warn 54 | sketchy-number=warn 55 | untyped-type-import=warn 56 | nonstrict-import=warn 57 | deprecated-type=warn 58 | unsafe-getters-setters=warn 59 | unnecessary-invariant=warn 60 | signature-verification-failure=warn 61 | deprecated-utility=error 62 | 63 | [strict] 64 | deprecated-type 65 | nonstrict-import 66 | sketchy-null 67 | unclear-type 68 | unsafe-getters-setters 69 | untyped-import 70 | untyped-type-import 71 | 72 | [version] 73 | ^0.122.0 74 | -------------------------------------------------------------------------------- /demo/.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | -------------------------------------------------------------------------------- /demo/.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | 24 | # Android/IntelliJ 25 | # 26 | build/ 27 | .idea 28 | .gradle 29 | local.properties 30 | *.iml 31 | 32 | # node.js 33 | # 34 | node_modules/ 35 | npm-debug.log 36 | yarn-error.log 37 | 38 | # BUCK 39 | buck-out/ 40 | \.buckd/ 41 | *.keystore 42 | !debug.keystore 43 | 44 | # fastlane 45 | # 46 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 47 | # screenshots whenever they are needed. 48 | # For more information about the recommended setup visit: 49 | # https://docs.fastlane.tools/best-practices/source-control/ 50 | 51 | */fastlane/report.xml 52 | */fastlane/Preview.html 53 | */fastlane/screenshots 54 | 55 | # Bundle artifact 56 | *.jsbundle 57 | 58 | # CocoaPods 59 | /ios/Pods/ 60 | -------------------------------------------------------------------------------- /demo/.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | bracketSpacing: false, 3 | jsxBracketSameLine: true, 4 | singleQuote: true, 5 | trailingComma: 'all', 6 | }; 7 | -------------------------------------------------------------------------------- /demo/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /demo/App.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Sample React Native App 3 | * https://github.com/facebook/react-native 4 | * 5 | * @format 6 | * @flow strict-local 7 | */ 8 | 9 | import React, { Component } from "react"; 10 | import { 11 | SafeAreaView, 12 | StyleSheet, 13 | ScrollView, 14 | View, 15 | Text, 16 | StatusBar, 17 | Button 18 | } from 'react-native'; 19 | 20 | import { 21 | Header, 22 | LearnMoreLinks, 23 | Colors, 24 | DebugInstructions, 25 | ReloadInstructions, 26 | } from 'react-native/Libraries/NewAppScreen'; 27 | 28 | import {Toast, TabView} from 'teaset'; 29 | import {TIMInitSdk, TIMLogin, TIMLogout, TIMStartChat} from 'react-native-tencent-im-ui'; 30 | 31 | import {SDKAPPID, SECRETKEY, genTestUserSig} from './src/genSig'; 32 | import Conversation from './src/conView'; 33 | let userId = '游子'; 34 | let userIdTo = '梦游'; 35 | 36 | class App extends Component { 37 | 38 | async componentDidMount() { 39 | // 先初始化 40 | try { 41 | TIMInitSdk(SDKAPPID); 42 | Toast.success("初始化成功"); 43 | // var userSig = await genTestUserSig(userId); // 这样写ios一直卡住,没有深入研究,换成then则没问题了 44 | genTestUserSig(userId).then(userSig => { 45 | console.log('genTestUserSig', userSig); 46 | TIMLogin(userId, userSig).then(res=>{ 47 | Toast.success(userId + "登录成功"); 48 | }).catch(e => { 49 | Toast.fail(userId + "登录失败"); 50 | }); 51 | }) 52 | 53 | 54 | } catch (e) { 55 | console.log('fail', e) 56 | Toast.fail("初始化失败,请检查SDKAPPID"); 57 | } 58 | } 59 | 60 | openChat() { 61 | try { 62 | TIMStartChat(userIdTo, userId + "和" + userIdTo, 1); 63 | } catch (e) { 64 | console.error(e); 65 | } 66 | } 67 | 68 | render() { 69 | return ( 70 | <> 71 | 72 | 73 | 76 | 77 | 78 | 79 | 80 | 当前登录用户:{userId},聊天用户:{userIdTo} 81 | 82 | 83 | 84 | 85 | 88 | 89 | 90 | 91 | 92 | ); 93 | } 94 | } 95 | 96 | const styles = StyleSheet.create({ 97 | scrollView: { 98 | backgroundColor: Colors.lighter, 99 | }, 100 | engine: { 101 | position: 'absolute', 102 | right: 0, 103 | }, 104 | body: { 105 | backgroundColor: Colors.white, 106 | }, 107 | sectionContainer: { 108 | marginTop: 32, 109 | paddingHorizontal: 24, 110 | }, 111 | sectionTitle: { 112 | fontSize: 24, 113 | fontWeight: '600', 114 | color: Colors.black, 115 | }, 116 | sectionDescription: { 117 | marginTop: 8, 118 | fontSize: 18, 119 | fontWeight: '400', 120 | color: Colors.dark, 121 | }, 122 | highlight: { 123 | fontWeight: '700', 124 | }, 125 | footer: { 126 | color: Colors.dark, 127 | fontSize: 12, 128 | fontWeight: '600', 129 | padding: 4, 130 | paddingRight: 12, 131 | textAlign: 'right', 132 | }, 133 | }); 134 | 135 | export default App; 136 | -------------------------------------------------------------------------------- /demo/__tests__/App-test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import 'react-native'; 6 | import React from 'react'; 7 | import App from '../App'; 8 | 9 | // Note: test renderer must be required after react-native. 10 | import renderer from 'react-test-renderer'; 11 | 12 | it('renders correctly', () => { 13 | renderer.create(); 14 | }); 15 | -------------------------------------------------------------------------------- /demo/android/app/_BUCK: -------------------------------------------------------------------------------- 1 | # To learn about Buck see [Docs](https://buckbuild.com/). 2 | # To run your application with Buck: 3 | # - install Buck 4 | # - `npm start` - to start the packager 5 | # - `cd android` 6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` 7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck 8 | # - `buck install -r android/app` - compile, install and run application 9 | # 10 | 11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets") 12 | 13 | lib_deps = [] 14 | 15 | create_aar_targets(glob(["libs/*.aar"])) 16 | 17 | create_jar_targets(glob(["libs/*.jar"])) 18 | 19 | android_library( 20 | name = "all-libs", 21 | exported_deps = lib_deps, 22 | ) 23 | 24 | android_library( 25 | name = "app-code", 26 | srcs = glob([ 27 | "src/main/java/**/*.java", 28 | ]), 29 | deps = [ 30 | ":all-libs", 31 | ":build_config", 32 | ":res", 33 | ], 34 | ) 35 | 36 | android_build_config( 37 | name = "build_config", 38 | package = "com.yunchao.tencentim.demo", 39 | ) 40 | 41 | android_resource( 42 | name = "res", 43 | package = "com.yunchao.tencentim.demo", 44 | res = "src/main/res", 45 | ) 46 | 47 | android_binary( 48 | name = "app", 49 | keystore = "//android/keystores:debug", 50 | manifest = "src/main/AndroidManifest.xml", 51 | package_type = "debug", 52 | deps = [ 53 | ":app-code", 54 | ], 55 | ) 56 | -------------------------------------------------------------------------------- /demo/android/app/build_defs.bzl: -------------------------------------------------------------------------------- 1 | """Helper definitions to glob .aar and .jar targets""" 2 | 3 | def create_aar_targets(aarfiles): 4 | for aarfile in aarfiles: 5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")] 6 | lib_deps.append(":" + name) 7 | android_prebuilt_aar( 8 | name = name, 9 | aar = aarfile, 10 | ) 11 | 12 | def create_jar_targets(jarfiles): 13 | for jarfile in jarfiles: 14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")] 15 | lib_deps.append(":" + name) 16 | prebuilt_jar( 17 | name = name, 18 | binary_jar = jarfile, 19 | ) 20 | -------------------------------------------------------------------------------- /demo/android/app/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/debug.keystore -------------------------------------------------------------------------------- /demo/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/BaseAgentActivity.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.os.Bundle; 6 | import android.view.Window; 7 | import android.view.WindowManager; 8 | 9 | /** 10 | * 基础activity,用来处理公共的透明参数 11 | */ 12 | public class BaseAgentActivity extends Activity { 13 | 14 | public static final String EXTRA_IS_FULLSCREEN = "should_be_fullscreen"; 15 | 16 | @Override 17 | protected void onCreate(Bundle savedInstanceState) { 18 | super.onCreate(savedInstanceState); 19 | requestActivityTransparent(); 20 | } 21 | 22 | /** 23 | * 启用透明的跳板Activity 24 | */ 25 | private void requestActivityTransparent() { 26 | try { 27 | Intent intent = getIntent(); 28 | if (intent != null && intent.getBooleanExtra(EXTRA_IS_FULLSCREEN, false)) { 29 | getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 30 | } 31 | requestWindowFeature(Window.FEATURE_NO_TITLE); 32 | Window window = getWindow(); 33 | if (window != null) { 34 | window.addFlags(0x04000000); 35 | } 36 | } catch (Exception e) { 37 | HMSAgentLog.w("requestActivityTransparent exception:" + e.getMessage()); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/BaseApiAgent.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | /** 4 | * API 实现类基类,用于处理公共操作 5 | * 目前实现的是client的连接及回调 6 | */ 7 | public abstract class BaseApiAgent implements IClientConnectCallback { 8 | protected void connect() { 9 | HMSAgentLog.d("connect"); 10 | ApiClientMgr.INST.connect(this, true); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/CallbackCodeRunnable.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import com.huawei.android.hms.agent.common.handler.ICallbackCode; 4 | 5 | /** 6 | * 回调线程 7 | */ 8 | public class CallbackCodeRunnable implements Runnable { 9 | 10 | private ICallbackCode handlerInner; 11 | private int rtnCodeInner; 12 | 13 | public CallbackCodeRunnable(ICallbackCode handler, int rtnCode) { 14 | handlerInner = handler; 15 | rtnCodeInner = rtnCode; 16 | } 17 | 18 | @Override 19 | public void run() { 20 | if (handlerInner != null) { 21 | handlerInner.onResult(rtnCodeInner); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/CallbackResultRunnable.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import com.huawei.android.hms.agent.common.handler.ICallbackResult; 4 | 5 | /** 6 | * 回调线程 7 | */ 8 | public class CallbackResultRunnable implements Runnable { 9 | 10 | private ICallbackResult handlerInner; 11 | private int rtnCodeInner; 12 | private R resultInner; 13 | 14 | public CallbackResultRunnable(ICallbackResult handler, int rtnCode, R payInfo) { 15 | handlerInner = handler; 16 | rtnCodeInner = rtnCode; 17 | resultInner = payInfo; 18 | } 19 | 20 | @Override 21 | public void run() { 22 | if (handlerInner != null) { 23 | handlerInner.onResult(rtnCodeInner, resultInner); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/CheckUpdateApi.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import android.app.Activity; 4 | import android.os.Handler; 5 | import android.os.Looper; 6 | 7 | import com.huawei.android.hms.agent.HMSAgent; 8 | import com.huawei.android.hms.agent.common.handler.CheckUpdateHandler; 9 | import com.huawei.hms.api.CheckUpdatelistener; 10 | import com.huawei.hms.api.HuaweiApiClient; 11 | 12 | /** 13 | * 应用自升级 14 | */ 15 | public class CheckUpdateApi extends BaseApiAgent implements CheckUpdatelistener { 16 | 17 | /** 18 | * 应用自升级回调接口 19 | */ 20 | private CheckUpdateHandler handler; 21 | 22 | /** 23 | * 升级传入的activity 24 | */ 25 | private Activity activity; 26 | 27 | /** 28 | * Huawei Api Client 连接回调 29 | * @param rst 结果码 30 | * @param client HuaweiApiClient 实例 31 | */ 32 | @Override 33 | public void onConnect(int rst, HuaweiApiClient client) { 34 | 35 | HMSAgentLog.d("onConnect:" + rst); 36 | 37 | Activity activityCur = ActivityMgr.INST.getLastActivity(); 38 | 39 | if (activityCur != null && client != null) { 40 | client.checkUpdate(activityCur, this); 41 | } else if (activity != null && client != null){ 42 | client.checkUpdate(activity, this); 43 | } else { 44 | // 跟SE确认:activity 为 null , 不处理 | Activity is null and does not need to be processed 45 | HMSAgentLog.e("no activity to checkUpdate"); 46 | onCheckUpdateResult(HMSAgent.AgentResultCode.NO_ACTIVITY_FOR_USE); 47 | return; 48 | } 49 | } 50 | 51 | @Override 52 | public void onResult(int resultCode) { 53 | onCheckUpdateResult(resultCode); 54 | } 55 | 56 | private void onCheckUpdateResult(int retCode){ 57 | HMSAgentLog.i("checkUpdate:callback=" + StrUtils.objDesc(handler) +" retCode=" + retCode); 58 | if (handler != null) { 59 | new Handler(Looper.getMainLooper()).post(new CallbackCodeRunnable(handler, retCode)); 60 | handler = null; 61 | } 62 | 63 | activity = null; 64 | } 65 | 66 | /** 67 | * 应用自升级接口 68 | * @param handler 应用自升级结果回调 69 | */ 70 | public void checkUpdate(Activity activity, CheckUpdateHandler handler) { 71 | HMSAgentLog.i("checkUpdate:handler=" + StrUtils.objDesc(handler)); 72 | this.handler = handler; 73 | this.activity = activity; 74 | connect(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/EmptyConnectCallback.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import com.huawei.hms.api.HuaweiApiClient; 4 | 5 | /** 6 | * 连接client空回调 7 | */ 8 | public class EmptyConnectCallback implements IClientConnectCallback { 9 | 10 | private String msgPre; 11 | 12 | public EmptyConnectCallback(String msgPre){ 13 | this.msgPre = msgPre; 14 | } 15 | 16 | /** 17 | * HuaweiApiClient 连接结果回调 18 | * 19 | * @param rst 结果码 20 | * @param client HuaweiApiClient 实例 21 | */ 22 | @Override 23 | public void onConnect(int rst, HuaweiApiClient client) { 24 | HMSAgentLog.d(msgPre + rst); 25 | } 26 | } -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/HMSAgentActivity.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.os.Bundle; 6 | 7 | import com.huawei.android.hms.agent.HMSAgent; 8 | import com.huawei.hms.api.HuaweiApiAvailability; 9 | 10 | /** 11 | * 代理Activity,用于弹出解决问题的引导 12 | */ 13 | public class HMSAgentActivity extends BaseAgentActivity { 14 | 15 | /** 16 | * 参数标签,用于取得要解决的错误码 17 | */ 18 | public static final String CONN_ERR_CODE_TAG = "HMSConnectionErrorCode"; 19 | 20 | /** 21 | * 解决错误后结果的标签,用来取得解决的结果 22 | */ 23 | public static final String EXTRA_RESULT = "intent.extra.RESULT"; 24 | 25 | /** 26 | * 解决错误的requestCode 27 | */ 28 | private static final int REQUEST_HMS_RESOLVE_ERROR = 1000; 29 | 30 | @Override 31 | protected void onCreate(Bundle savedInstanceState) { 32 | super.onCreate(savedInstanceState); 33 | ApiClientMgr.INST.onActivityLunched(); 34 | 35 | Intent intent = getIntent(); 36 | if (intent != null) { 37 | int rstCode = intent.getIntExtra(CONN_ERR_CODE_TAG, 0); 38 | HMSAgentLog.d("dispose code:" + rstCode); 39 | HuaweiApiAvailability.getInstance().resolveError(this, rstCode, REQUEST_HMS_RESOLVE_ERROR); 40 | } else { 41 | HMSAgentLog.e("intent is null"); 42 | finish(); 43 | } 44 | } 45 | 46 | @Override 47 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 48 | super.onActivityResult(requestCode, resultCode, data); 49 | 50 | if(requestCode == REQUEST_HMS_RESOLVE_ERROR) { 51 | if(resultCode == Activity.RESULT_OK) { 52 | int result = data.getIntExtra(EXTRA_RESULT, -1); 53 | HMSAgentLog.d("dispose result:" + result); 54 | ApiClientMgr.INST.onResolveErrorRst(result); 55 | } else { 56 | HMSAgentLog.e("dispose error:" + resultCode); 57 | ApiClientMgr.INST.onResolveErrorRst(HMSAgent.AgentResultCode.ON_ACTIVITY_RESULT_ERROR); 58 | } 59 | finish(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/HMSAgentLog.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | 4 | import android.util.Log; 5 | 6 | /** 7 | * 日志打印类,对打印日志进行封装,方便根据日志定位问题 8 | */ 9 | public final class HMSAgentLog { 10 | 11 | /** 12 | * 日志回调,将要打印的日志回调给开发者,由开发者将日志输出 13 | */ 14 | public interface IHMSAgentLogCallback { 15 | void logD(String tag, String log); 16 | 17 | void logV(String tag, String log); 18 | 19 | void logI(String tag, String log); 20 | 21 | void logW(String tag, String log); 22 | 23 | void logE(String tag, String log); 24 | } 25 | 26 | private static final int START_STACK_INDEX = 4; 27 | private static final int PRINT_STACK_COUTN = 2; 28 | 29 | private static IHMSAgentLogCallback logCallback = null; 30 | 31 | public static void setHMSAgentLogCallback(IHMSAgentLogCallback callback) { 32 | logCallback = callback; 33 | } 34 | 35 | public static void d(String log) { 36 | StringBuilder sb = new StringBuilder(); 37 | appendStack(sb); 38 | sb.append(log); 39 | 40 | if (logCallback != null) { 41 | logCallback.logD("HMSAgent", sb.toString()); 42 | } else { 43 | Log.d("HMSAgent", sb.toString()); 44 | } 45 | } 46 | 47 | public static void v(String log) { 48 | StringBuilder sb = new StringBuilder(); 49 | appendStack(sb); 50 | sb.append(log); 51 | if (logCallback != null) { 52 | logCallback.logV("HMSAgent", sb.toString()); 53 | } else { 54 | Log.v("HMSAgent", sb.toString()); 55 | } 56 | } 57 | 58 | public static void i(String log) { 59 | StringBuilder sb = new StringBuilder(); 60 | appendStack(sb); 61 | sb.append(log); 62 | if (logCallback != null) { 63 | logCallback.logI("HMSAgent", sb.toString()); 64 | } else { 65 | Log.i("HMSAgent", sb.toString()); 66 | } 67 | } 68 | 69 | public static void w(String log) { 70 | StringBuilder sb = new StringBuilder(); 71 | appendStack(sb); 72 | sb.append(log); 73 | if (logCallback != null) { 74 | logCallback.logW("HMSAgent", sb.toString()); 75 | } else { 76 | Log.w("HMSAgent", sb.toString()); 77 | } 78 | } 79 | 80 | public static void e(String log) { 81 | StringBuilder sb = new StringBuilder(); 82 | appendStack(sb); 83 | sb.append(log); 84 | 85 | if (logCallback != null) { 86 | logCallback.logE("HMSAgent", sb.toString()); 87 | } else { 88 | Log.e("HMSAgent", sb.toString()); 89 | } 90 | } 91 | 92 | private static void appendStack(StringBuilder sb) { 93 | StackTraceElement[] stacks = Thread.currentThread().getStackTrace(); 94 | if (stacks.length > START_STACK_INDEX) { 95 | int lastIndex = Math.min(stacks.length - 1, START_STACK_INDEX + PRINT_STACK_COUTN); 96 | for (int i = lastIndex; i >= START_STACK_INDEX; i--) { 97 | if (stacks[i] == null) { 98 | continue; 99 | } 100 | 101 | String fileName = stacks[i].getFileName(); 102 | if (fileName != null) { 103 | int dotIndx = fileName.indexOf('.'); 104 | if (dotIndx > 0) { 105 | fileName = fileName.substring(0, dotIndx); 106 | } 107 | } 108 | 109 | sb.append(fileName); 110 | sb.append('('); 111 | sb.append(stacks[i].getLineNumber()); 112 | sb.append(")"); 113 | sb.append("->"); 114 | } 115 | sb.append(stacks[START_STACK_INDEX].getMethodName()); 116 | } 117 | sb.append('\n'); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/IActivityDestroyedCallback.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import android.app.Activity; 4 | 5 | /** 6 | * Activity onDestroyed 事件回调接口 7 | */ 8 | public interface IActivityDestroyedCallback { 9 | 10 | /** 11 | * Activity onPause回调 12 | * @param activityDestroyed 发生 onDestroyed 事件的activity 13 | * @param activityNxt 下个要显示的activity 14 | */ 15 | void onActivityDestroyed(Activity activityDestroyed, Activity activityNxt); 16 | } 17 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/IActivityPauseCallback.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import android.app.Activity; 4 | 5 | /** 6 | * Activity onPause 事件回调接口 7 | */ 8 | public interface IActivityPauseCallback { 9 | 10 | /** 11 | * Activity onPause回调 12 | * @param activity 发生 onPause 事件的activity 13 | */ 14 | void onActivityPause(Activity activity); 15 | } 16 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/IActivityResumeCallback.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import android.app.Activity; 4 | 5 | /** 6 | * Activity onResume 事件回调接口 7 | */ 8 | public interface IActivityResumeCallback { 9 | 10 | /** 11 | * Activity onResume回调 12 | * @param activity 发生 onResume 事件的activity 13 | */ 14 | void onActivityResume(Activity activity); 15 | } 16 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/IClientConnectCallback.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import com.huawei.hms.api.HuaweiApiClient; 4 | 5 | /** 6 | * HuaweiApiClient 连接结果回调 7 | */ 8 | public interface IClientConnectCallback { 9 | /** 10 | * HuaweiApiClient 连接结果回调 11 | * @param rst 结果码 12 | * @param client HuaweiApiClient 实例 13 | */ 14 | void onConnect(int rst, HuaweiApiClient client); 15 | } 16 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/INoProguard.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | /** 4 | * 不混淆类 5 | */ 6 | public interface INoProguard { 7 | } 8 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/IOUtils.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import java.io.Closeable; 4 | import java.io.IOException; 5 | 6 | /** 7 | * 工具类 8 | */ 9 | public final class IOUtils { 10 | public static void close(Closeable object) { 11 | if (object != null) { 12 | try { 13 | object.close(); 14 | } catch (IOException e) { 15 | HMSAgentLog.d("close fail"); 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/StrUtils.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | /** 4 | * 工具类 5 | */ 6 | public final class StrUtils { 7 | /** 8 | * 返回对象的描述,这里为了避免用户数据隐私的泄露,只是返回对象本身的描述 类名@hashcode 9 | * @param object 对象 10 | * @return 对象的描述 11 | */ 12 | public static String objDesc(Object object) { 13 | return object == null ? "null" : (object.getClass().getName()+'@'+Integer.toHexString(object.hashCode())); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/ThreadUtil.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | import java.util.concurrent.ExecutorService; 7 | import java.util.concurrent.Executors; 8 | 9 | /** 10 | * 线程工具,用于执行线程等 11 | */ 12 | public final class ThreadUtil { 13 | public static final ThreadUtil INST = new ThreadUtil(); 14 | 15 | private ExecutorService executors; 16 | 17 | private ThreadUtil(){ 18 | } 19 | 20 | /** 21 | * 在线程中执行 22 | * @param runnable 要执行的runnable 23 | */ 24 | public void execute(Runnable runnable) { 25 | ExecutorService executorService = getExecutorService(); 26 | if (executorService != null) { 27 | // 优先使用线程池,提高效率 28 | executorService.execute(runnable); 29 | } else { 30 | // 线程池获取失败,则直接使用线程 31 | new Thread(runnable).start(); 32 | } 33 | } 34 | 35 | /** 36 | * 在主线程中执行 37 | * @param runnable 要执行的runnable 38 | */ 39 | public void excuteInMainThread(Runnable runnable){ 40 | new Handler(Looper.getMainLooper()).post(runnable); 41 | } 42 | 43 | /** 44 | * 获取缓存线程池 45 | * @return 缓存线程池服务 46 | */ 47 | private ExecutorService getExecutorService(){ 48 | if (executors == null) { 49 | try { 50 | executors = Executors.newCachedThreadPool(); 51 | } catch (Exception e) { 52 | HMSAgentLog.e("create thread service error:" + e.getMessage()); 53 | } 54 | } 55 | 56 | return executors; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/UIUtils.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common; 2 | 3 | import android.app.Activity; 4 | import android.view.WindowManager; 5 | 6 | /** 7 | * 工具类 8 | */ 9 | public final class UIUtils { 10 | /** 11 | * 判断当前activity是否为全屏 12 | * @param activity 当前activity 13 | * @return 是否全屏 14 | */ 15 | public static boolean isActivityFullscreen(Activity activity) 16 | { 17 | WindowManager.LayoutParams attrs = activity.getWindow().getAttributes(); 18 | return (attrs.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/handler/CheckUpdateHandler.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common.handler; 2 | 3 | /** 4 | * 应用自升级回调 5 | */ 6 | public interface CheckUpdateHandler extends ICallbackCode { 7 | } 8 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/handler/ConnectHandler.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common.handler; 2 | 3 | /** 4 | * HuaweiApiClient 连接结果回调 5 | */ 6 | public interface ConnectHandler { 7 | /** 8 | * HuaweiApiClient 连接结果回调 9 | * @param rst 结果码 10 | */ 11 | void onConnect(int rst); 12 | } 13 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/handler/ICallbackCode.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common.handler; 2 | 3 | /** 4 | * 回调接口 5 | */ 6 | public interface ICallbackCode { 7 | /** 8 | * 回调接口 9 | * @param rst 结果码 10 | */ 11 | void onResult(int rst); 12 | } 13 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/common/handler/ICallbackResult.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.common.handler; 2 | 3 | /** 4 | * 回调接口 5 | */ 6 | public interface ICallbackResult { 7 | /** 8 | * 回调接口 9 | * @param rst 结果码 10 | * @param result 结果信息 11 | */ 12 | void onResult(int rst, R result); 13 | } 14 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/DeleteTokenApi.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | import android.text.TextUtils; 6 | 7 | import com.huawei.android.hms.agent.HMSAgent; 8 | import com.huawei.android.hms.agent.common.ApiClientMgr; 9 | import com.huawei.android.hms.agent.common.BaseApiAgent; 10 | import com.huawei.android.hms.agent.common.CallbackCodeRunnable; 11 | import com.huawei.android.hms.agent.common.HMSAgentLog; 12 | import com.huawei.android.hms.agent.common.StrUtils; 13 | import com.huawei.android.hms.agent.common.ThreadUtil; 14 | import com.huawei.android.hms.agent.push.handler.DeleteTokenHandler; 15 | import com.huawei.hms.api.HuaweiApiClient; 16 | import com.huawei.hms.support.api.push.HuaweiPush; 17 | 18 | /** 19 | * 删除pushtoken的接口。 20 | */ 21 | public class DeleteTokenApi extends BaseApiAgent { 22 | 23 | /** 24 | * 待删除的push token 25 | */ 26 | private String token; 27 | 28 | /** 29 | * 调用接口回调 30 | */ 31 | private DeleteTokenHandler handler; 32 | 33 | /** 34 | * HuaweiApiClient 连接结果回调 35 | * 36 | * @param rst 结果码 37 | * @param client HuaweiApiClient 实例 38 | */ 39 | @Override 40 | public void onConnect(final int rst, final HuaweiApiClient client) { 41 | //需要在子线程中执行删除TOKEN操作 42 | ThreadUtil.INST.execute(new Runnable() { 43 | @Override 44 | public void run() { 45 | //调用删除TOKEN需要传入通过getToken接口获取到TOKEN,并且需要对TOKEN进行非空判断 46 | if (!TextUtils.isEmpty(token)) { 47 | if (client == null || !ApiClientMgr.INST.isConnect(client)) { 48 | HMSAgentLog.e("client not connted"); 49 | onDeleteTokenResult(rst); 50 | } else { 51 | try { 52 | HuaweiPush.HuaweiPushApi.deleteToken(client, token); 53 | onDeleteTokenResult(HMSAgent.AgentResultCode.HMSAGENT_SUCCESS); 54 | } catch (Exception e) { 55 | HMSAgentLog.e("删除TOKEN失败:" + e.getMessage()); 56 | onDeleteTokenResult(HMSAgent.AgentResultCode.CALL_EXCEPTION); 57 | } 58 | } 59 | } else { 60 | HMSAgentLog.e("删除TOKEN失败: 要删除的token为空"); 61 | onDeleteTokenResult(HMSAgent.AgentResultCode.EMPTY_PARAM); 62 | } 63 | } 64 | }); 65 | } 66 | 67 | void onDeleteTokenResult(int rstCode) { 68 | HMSAgentLog.i("deleteToken:callback=" + StrUtils.objDesc(handler) + " retCode=" + rstCode); 69 | if (handler != null) { 70 | new Handler(Looper.getMainLooper()).post(new CallbackCodeRunnable(handler, rstCode)); 71 | handler = null; 72 | } 73 | } 74 | 75 | /** 76 | * 删除指定的pushtoken 77 | * 该接口只在EMUI5.1以及更高版本的华为手机上调用该接口后才不会收到PUSH消息。 78 | * 79 | * @param token 要删除的token 80 | */ 81 | public void deleteToken(String token, DeleteTokenHandler handler) { 82 | HMSAgentLog.i("deleteToken:token:" + StrUtils.objDesc(token) + " handler=" + StrUtils.objDesc(handler)); 83 | this.token = token; 84 | this.handler = handler; 85 | connect(); 86 | } 87 | } -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/EnableReceiveNormalMsgApi.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | import com.huawei.android.hms.agent.HMSAgent; 7 | import com.huawei.android.hms.agent.common.ApiClientMgr; 8 | import com.huawei.android.hms.agent.common.BaseApiAgent; 9 | import com.huawei.android.hms.agent.common.CallbackCodeRunnable; 10 | import com.huawei.android.hms.agent.common.HMSAgentLog; 11 | import com.huawei.android.hms.agent.common.StrUtils; 12 | import com.huawei.android.hms.agent.common.ThreadUtil; 13 | import com.huawei.android.hms.agent.push.handler.EnableReceiveNormalMsgHandler; 14 | import com.huawei.hms.api.HuaweiApiClient; 15 | import com.huawei.hms.support.api.push.HuaweiPush; 16 | 17 | /** 18 | * 打开透传消息开关的接口。 19 | */ 20 | public class EnableReceiveNormalMsgApi extends BaseApiAgent { 21 | 22 | /** 23 | * 是否打开开关 24 | */ 25 | boolean enable; 26 | 27 | /** 28 | * 调用接口回调 29 | */ 30 | private EnableReceiveNormalMsgHandler handler; 31 | 32 | /** 33 | * HuaweiApiClient 连接结果回调 34 | * 35 | * @param rst 结果码 36 | * @param client HuaweiApiClient 实例 37 | */ 38 | @Override 39 | public void onConnect(final int rst, final HuaweiApiClient client) { 40 | //需要在子线程中执行开关的操作 41 | ThreadUtil.INST.execute(new Runnable() { 42 | @Override 43 | public void run() { 44 | if (client == null || !ApiClientMgr.INST.isConnect(client)) { 45 | HMSAgentLog.e("client not connted"); 46 | onEnableReceiveNormalMsgResult(rst); 47 | } else { 48 | // 开启/关闭透传消息 49 | HuaweiPush.HuaweiPushApi.enableReceiveNormalMsg(client, enable); 50 | onEnableReceiveNormalMsgResult(HMSAgent.AgentResultCode.HMSAGENT_SUCCESS); 51 | } 52 | } 53 | }); 54 | } 55 | 56 | void onEnableReceiveNormalMsgResult(int rstCode) { 57 | HMSAgentLog.i("enableReceiveNormalMsg:callback=" + StrUtils.objDesc(handler) + " retCode=" + rstCode); 58 | if (handler != null) { 59 | new Handler(Looper.getMainLooper()).post(new CallbackCodeRunnable(handler, rstCode)); 60 | handler = null; 61 | } 62 | } 63 | 64 | /** 65 | * 打开/关闭透传消息 66 | * 67 | * @param enable 打开/关闭 68 | */ 69 | public void enableReceiveNormalMsg(boolean enable, EnableReceiveNormalMsgHandler handler) { 70 | HMSAgentLog.i("enableReceiveNormalMsg:enable=" + enable + " handler=" + StrUtils.objDesc(handler)); 71 | this.enable = enable; 72 | this.handler = handler; 73 | connect(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/EnableReceiveNotifyMsgApi.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | import com.huawei.android.hms.agent.HMSAgent; 7 | import com.huawei.android.hms.agent.common.ApiClientMgr; 8 | import com.huawei.android.hms.agent.common.BaseApiAgent; 9 | import com.huawei.android.hms.agent.common.CallbackCodeRunnable; 10 | import com.huawei.android.hms.agent.common.HMSAgentLog; 11 | import com.huawei.android.hms.agent.common.StrUtils; 12 | import com.huawei.android.hms.agent.common.ThreadUtil; 13 | import com.huawei.android.hms.agent.push.handler.EnableReceiveNotifyMsgHandler; 14 | import com.huawei.hms.api.HuaweiApiClient; 15 | import com.huawei.hms.support.api.push.HuaweiPush; 16 | 17 | /** 18 | * 打开自呈现消息开关的接口。 19 | */ 20 | public class EnableReceiveNotifyMsgApi extends BaseApiAgent { 21 | 22 | /** 23 | * 是否打开开关 24 | */ 25 | boolean enable; 26 | 27 | /** 28 | * 调用接口回调 29 | */ 30 | private EnableReceiveNotifyMsgHandler handler; 31 | 32 | /** 33 | * HuaweiApiClient 连接结果回调 34 | * 35 | * @param rst 结果码 36 | * @param client HuaweiApiClient 实例 37 | */ 38 | @Override 39 | public void onConnect(final int rst, final HuaweiApiClient client) { 40 | //需要在子线程中执行开关的操作 41 | ThreadUtil.INST.execute(new Runnable() { 42 | @Override 43 | public void run() { 44 | if (client == null || !ApiClientMgr.INST.isConnect(client)) { 45 | HMSAgentLog.e("client not connted"); 46 | onEnableReceiveNotifyMsgResult(rst); 47 | } else { 48 | // 开启/关闭自呈现消息 49 | HuaweiPush.HuaweiPushApi.enableReceiveNotifyMsg(client, enable); 50 | onEnableReceiveNotifyMsgResult(HMSAgent.AgentResultCode.HMSAGENT_SUCCESS); 51 | } 52 | } 53 | }); 54 | } 55 | 56 | void onEnableReceiveNotifyMsgResult(int rstCode) { 57 | HMSAgentLog.i("enableReceiveNotifyMsg:callback=" + StrUtils.objDesc(handler) + " retCode=" + rstCode); 58 | if (handler != null) { 59 | new Handler(Looper.getMainLooper()).post(new CallbackCodeRunnable(handler, rstCode)); 60 | handler = null; 61 | } 62 | } 63 | 64 | /** 65 | * 打开/关闭自呈现消息 66 | * 67 | * @param enable 打开/关闭 68 | */ 69 | public void enableReceiveNotifyMsg(boolean enable, EnableReceiveNotifyMsgHandler handler) { 70 | HMSAgentLog.i("enableReceiveNotifyMsg:enable=" + enable + " handler=" + StrUtils.objDesc(handler)); 71 | this.enable = enable; 72 | this.handler = handler; 73 | connect(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/GetPushStateApi.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | import com.huawei.android.hms.agent.HMSAgent; 7 | import com.huawei.android.hms.agent.common.ApiClientMgr; 8 | import com.huawei.android.hms.agent.common.BaseApiAgent; 9 | import com.huawei.android.hms.agent.common.CallbackCodeRunnable; 10 | import com.huawei.android.hms.agent.common.HMSAgentLog; 11 | import com.huawei.android.hms.agent.common.StrUtils; 12 | import com.huawei.android.hms.agent.common.ThreadUtil; 13 | import com.huawei.android.hms.agent.push.handler.GetPushStateHandler; 14 | import com.huawei.hms.api.HuaweiApiClient; 15 | import com.huawei.hms.support.api.push.HuaweiPush; 16 | 17 | /** 18 | * 获取push状态的接口。 19 | */ 20 | public class GetPushStateApi extends BaseApiAgent { 21 | 22 | /** 23 | * 调用接口回调 24 | */ 25 | private GetPushStateHandler handler; 26 | 27 | /** 28 | * HuaweiApiClient 连接结果回调 29 | * 30 | * @param rst 结果码 31 | * @param client HuaweiApiClient 实例 32 | */ 33 | @Override 34 | public void onConnect(final int rst, final HuaweiApiClient client) { 35 | //需要在子线程中执行获取push状态的操作 36 | ThreadUtil.INST.execute(new Runnable() { 37 | @Override 38 | public void run() { 39 | if (client == null || !ApiClientMgr.INST.isConnect(client)) { 40 | HMSAgentLog.e("client not connted"); 41 | onGetPushStateResult(rst); 42 | } else { 43 | HuaweiPush.HuaweiPushApi.getPushState(client); 44 | onGetPushStateResult(HMSAgent.AgentResultCode.HMSAGENT_SUCCESS); 45 | } 46 | } 47 | }); 48 | } 49 | 50 | void onGetPushStateResult(int rstCode) { 51 | HMSAgentLog.i("getPushState:callback=" + StrUtils.objDesc(handler) + " retCode=" + rstCode); 52 | if (handler != null) { 53 | new Handler(Looper.getMainLooper()).post(new CallbackCodeRunnable(handler, rstCode)); 54 | handler = null; 55 | } 56 | } 57 | 58 | /** 59 | * 获取push状态,push状态的回调通过广播发送。 60 | * 要监听的广播,请参见HMS-SDK开发准备中PushReceiver的注册 61 | */ 62 | public void getPushState(GetPushStateHandler handler) { 63 | HMSAgentLog.i("getPushState:handler=" + StrUtils.objDesc(handler)); 64 | this.handler = handler; 65 | connect(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/GetTokenApi.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | import com.huawei.android.hms.agent.HMSAgent; 7 | import com.huawei.android.hms.agent.common.ApiClientMgr; 8 | import com.huawei.android.hms.agent.common.BaseApiAgent; 9 | import com.huawei.android.hms.agent.common.CallbackCodeRunnable; 10 | import com.huawei.android.hms.agent.common.HMSAgentLog; 11 | import com.huawei.android.hms.agent.common.StrUtils; 12 | import com.huawei.android.hms.agent.push.handler.GetTokenHandler; 13 | import com.huawei.hms.api.HuaweiApiClient; 14 | import com.huawei.hms.support.api.client.PendingResult; 15 | import com.huawei.hms.support.api.client.ResultCallback; 16 | import com.huawei.hms.support.api.client.Status; 17 | import com.huawei.hms.support.api.entity.core.CommonCode; 18 | import com.huawei.hms.support.api.push.HuaweiPush; 19 | import com.huawei.hms.support.api.push.TokenResult; 20 | 21 | /** 22 | * 获取token的push接口,token的结果通过广播进行接收。 23 | */ 24 | public class GetTokenApi extends BaseApiAgent { 25 | 26 | /** 27 | * client 无效最大尝试次数 28 | */ 29 | private static final int MAX_RETRY_TIMES = 1; 30 | 31 | /** 32 | * 结果回调 33 | */ 34 | private GetTokenHandler handler; 35 | 36 | /** 37 | * 当前剩余重试次数 38 | */ 39 | private int retryTimes = MAX_RETRY_TIMES; 40 | 41 | /** 42 | * HuaweiApiClient 连接结果回调 43 | * 44 | * @param rst 结果码 45 | * @param client HuaweiApiClient 实例 46 | */ 47 | @Override 48 | public void onConnect(int rst, HuaweiApiClient client) { 49 | if (client == null || !ApiClientMgr.INST.isConnect(client)) { 50 | HMSAgentLog.e("client not connted"); 51 | onPushTokenResult(rst, null); 52 | return; 53 | } 54 | 55 | PendingResult tokenResult = HuaweiPush.HuaweiPushApi.getToken(client); 56 | tokenResult.setResultCallback(new ResultCallback() { 57 | @Override 58 | public void onResult(TokenResult result) { 59 | if (result == null) { 60 | HMSAgentLog.e("result is null"); 61 | onPushTokenResult(HMSAgent.AgentResultCode.RESULT_IS_NULL, null); 62 | return; 63 | } 64 | 65 | Status status = result.getStatus(); 66 | if (status == null) { 67 | HMSAgentLog.e("status is null"); 68 | onPushTokenResult(HMSAgent.AgentResultCode.STATUS_IS_NULL, null); 69 | return; 70 | } 71 | 72 | int rstCode = status.getStatusCode(); 73 | HMSAgentLog.d("status=" + status); 74 | // 需要重试的错误码,并且可以重试 75 | if ((rstCode == CommonCode.ErrorCode.SESSION_INVALID 76 | || rstCode == CommonCode.ErrorCode.CLIENT_API_INVALID) && retryTimes > 0) { 77 | retryTimes--; 78 | connect(); 79 | } else { 80 | onPushTokenResult(rstCode, result); 81 | } 82 | } 83 | }); 84 | } 85 | 86 | /** 87 | * 获取pushtoken接口调用回调 88 | * pushtoken通过广播下发,要监听的广播,请参见HMS-SDK开发准备中PushReceiver的注册 89 | * 90 | * @param rstCode 结果码 91 | * @param result 调用获取pushtoken接口的结果 92 | */ 93 | void onPushTokenResult(int rstCode, TokenResult result) { 94 | HMSAgentLog.i("getToken:callback=" + StrUtils.objDesc(handler) + " retCode=" + rstCode); 95 | if (handler != null) { 96 | new Handler(Looper.getMainLooper()).post(new CallbackCodeRunnable(handler, rstCode)); 97 | handler = null; 98 | } 99 | retryTimes = MAX_RETRY_TIMES; 100 | } 101 | 102 | /** 103 | * 获取pushtoken接口 104 | * pushtoken通过广播下发,要监听的广播,请参见HMS-SDK开发准备中PushReceiver的注册 105 | * 106 | * @param handler pushtoken接口调用回调 107 | */ 108 | public void getToken(GetTokenHandler handler) { 109 | HMSAgentLog.i("getToken:handler=" + StrUtils.objDesc(handler)); 110 | this.handler = handler; 111 | retryTimes = MAX_RETRY_TIMES; 112 | connect(); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/QueryAgreementApi.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | import com.huawei.android.hms.agent.HMSAgent; 7 | import com.huawei.android.hms.agent.common.ApiClientMgr; 8 | import com.huawei.android.hms.agent.common.BaseApiAgent; 9 | import com.huawei.android.hms.agent.common.CallbackCodeRunnable; 10 | import com.huawei.android.hms.agent.common.HMSAgentLog; 11 | import com.huawei.android.hms.agent.common.StrUtils; 12 | import com.huawei.android.hms.agent.common.ThreadUtil; 13 | import com.huawei.android.hms.agent.push.handler.QueryAgreementHandler; 14 | import com.huawei.hms.api.HuaweiApiClient; 15 | import com.huawei.hms.support.api.push.HuaweiPush; 16 | 17 | /** 18 | * 获取push协议展示的接口。 19 | */ 20 | public class QueryAgreementApi extends BaseApiAgent { 21 | 22 | /** 23 | * 调用接口回调 24 | */ 25 | private QueryAgreementHandler handler; 26 | 27 | /** 28 | * HuaweiApiClient 连接结果回调 29 | * 30 | * @param rst 结果码 31 | * @param client HuaweiApiClient 实例 32 | */ 33 | @Override 34 | public void onConnect(final int rst, final HuaweiApiClient client) { 35 | //需要在子线程中执行获取push协议展示的操作 36 | ThreadUtil.INST.execute(new Runnable() { 37 | @Override 38 | public void run() { 39 | if (client == null || !ApiClientMgr.INST.isConnect(client)) { 40 | HMSAgentLog.e("client not connted"); 41 | onQueryAgreementResult(rst); 42 | } else { 43 | HuaweiPush.HuaweiPushApi.queryAgreement(client); 44 | onQueryAgreementResult(HMSAgent.AgentResultCode.HMSAGENT_SUCCESS); 45 | } 46 | } 47 | }); 48 | } 49 | 50 | void onQueryAgreementResult(int rstCode) { 51 | HMSAgentLog.i("queryAgreement:callback=" + StrUtils.objDesc(handler) + " retCode=" + rstCode); 52 | if (handler != null) { 53 | new Handler(Looper.getMainLooper()).post(new CallbackCodeRunnable(handler, rstCode)); 54 | handler = null; 55 | } 56 | } 57 | 58 | /** 59 | * 请求push协议展示 60 | */ 61 | public void queryAgreement(QueryAgreementHandler handler) { 62 | HMSAgentLog.i("queryAgreement:handler=" + StrUtils.objDesc(handler)); 63 | this.handler = handler; 64 | connect(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/handler/DeleteTokenHandler.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push.handler; 2 | 3 | import com.huawei.android.hms.agent.common.handler.ICallbackCode; 4 | 5 | /** 6 | * deleteToken 回调 7 | */ 8 | public interface DeleteTokenHandler extends ICallbackCode { 9 | } 10 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/handler/EnableReceiveNormalMsgHandler.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push.handler; 2 | 3 | import com.huawei.android.hms.agent.common.handler.ICallbackCode; 4 | 5 | /** 6 | * enableReceiveNormalMsg 回调 7 | */ 8 | public interface EnableReceiveNormalMsgHandler extends ICallbackCode { 9 | } 10 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/handler/EnableReceiveNotifyMsgHandler.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push.handler; 2 | 3 | import com.huawei.android.hms.agent.common.handler.ICallbackCode; 4 | 5 | /** 6 | * enableReceiveNotifyMsg 回调 7 | */ 8 | public interface EnableReceiveNotifyMsgHandler extends ICallbackCode { 9 | } 10 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/handler/GetPushStateHandler.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push.handler; 2 | 3 | import com.huawei.android.hms.agent.common.handler.ICallbackCode; 4 | 5 | /** 6 | * getPushState 回调 7 | */ 8 | public interface GetPushStateHandler extends ICallbackCode { 9 | } 10 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/handler/GetTokenHandler.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push.handler; 2 | 3 | import com.huawei.android.hms.agent.common.handler.ICallbackCode; 4 | 5 | /** 6 | * 获取 pushtoken 回调 7 | */ 8 | public interface GetTokenHandler extends ICallbackCode { 9 | } 10 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/huawei/android/hms/agent/push/handler/QueryAgreementHandler.java: -------------------------------------------------------------------------------- 1 | package com.huawei.android.hms.agent.push.handler; 2 | 3 | import com.huawei.android.hms.agent.common.handler.ICallbackCode; 4 | 5 | /** 6 | * queryAgreement 回调 7 | */ 8 | public interface QueryAgreementHandler extends ICallbackCode { 9 | } 10 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/yunchao/tencentim/demo/DemoModule.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.demo; 2 | 3 | import com.facebook.react.bridge.Promise; 4 | import com.facebook.react.bridge.ReactApplicationContext; 5 | import com.facebook.react.bridge.ReactContextBaseJavaModule; 6 | import com.facebook.react.bridge.ReactMethod; 7 | 8 | 9 | public class DemoModule extends ReactContextBaseJavaModule { 10 | 11 | public DemoModule(ReactApplicationContext reactContext) { 12 | super(reactContext); 13 | } 14 | 15 | 16 | @Override 17 | public String getName() { 18 | return "DemoModule"; 19 | } 20 | 21 | @ReactMethod 22 | public void getSig(int sdkAppId, String appsec, String userId, Promise promise) { 23 | String res = GenerateTestUserSig.genTestUserSig(Long.valueOf(sdkAppId), appsec, userId); 24 | promise.resolve(res); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/yunchao/tencentim/demo/DemoPackage.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.demo; 2 | 3 | import com.facebook.react.ReactPackage; 4 | import com.facebook.react.bridge.NativeModule; 5 | import com.facebook.react.bridge.ReactApplicationContext; 6 | import com.facebook.react.uimanager.ViewManager; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class DemoPackage implements ReactPackage { 12 | 13 | @Override 14 | public List createNativeModules(ReactApplicationContext reactContext) { 15 | List list = new ArrayList<>(); 16 | list.add(new DemoModule(reactContext)); 17 | return list; 18 | } 19 | 20 | @Override 21 | public List createViewManagers(ReactApplicationContext reactContext) { 22 | return new ArrayList<>(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/yunchao/tencentim/demo/GenerateTestUserSig.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.demo; 2 | 3 | import android.text.TextUtils; 4 | import android.util.Base64; 5 | 6 | import org.json.JSONException; 7 | import org.json.JSONObject; 8 | 9 | import java.io.UnsupportedEncodingException; 10 | import java.nio.charset.Charset; 11 | import java.security.InvalidKeyException; 12 | import java.security.NoSuchAlgorithmException; 13 | import java.util.Arrays; 14 | import java.util.zip.Deflater; 15 | 16 | import javax.crypto.Mac; 17 | import javax.crypto.spec.SecretKeySpec; 18 | 19 | /* 20 | * Module: GenerateTestUserSig 21 | * 22 | * Function: 用于生成测试用的 UserSig,UserSig 是腾讯云为其云服务设计的一种安全保护签名。 23 | * 其计算方法是对 SDKAppID、UserID 和 EXPIRETIME 进行加密,加密算法为 HMAC-SHA256。 24 | * 25 | * Attention: 请不要将如下代码发布到您的线上正式版本的 App 中,原因如下: 26 | * 27 | * 本文件中的代码虽然能够正确计算出 UserSig,但仅适合快速调通 SDK 的基本功能,不适合线上产品, 28 | * 这是因为客户端代码中的 SECRETKEY 很容易被反编译逆向破解,尤其是 Web 端的代码被破解的难度几乎为零。 29 | * 一旦您的密钥泄露,攻击者就可以计算出正确的 UserSig 来盗用您的腾讯云流量。 30 | * 31 | * 正确的做法是将 UserSig 的计算代码和加密密钥放在您的业务服务器上,然后由 App 按需向您的服务器获取实时算出的 UserSig。 32 | * 由于破解服务器的成本要高于破解客户端 App,所以服务器计算的方案能够更好地保护您的加密密钥。 33 | * 34 | * Reference:https://cloud.tencent.com/document/product/269/32688#Server 35 | */ 36 | public class GenerateTestUserSig { 37 | 38 | 39 | /** 40 | * 签名过期时间,建议不要设置的过短 41 | *

42 | * 时间单位:秒 43 | * 默认时间:7 x 24 x 60 x 60 = 604800 = 7 天 44 | */ 45 | private static final int EXPIRETIME = 604800; 46 | 47 | /** 48 | * 计算 UserSig 签名 49 | * 50 | * 函数内部使用 HMAC-SHA256 非对称加密算法,对 SDKAPPID、userId 和 EXPIRETIME 进行加密。 51 | * 52 | * @note: 请不要将如下代码发布到您的线上正式版本的 App 中,原因如下: 53 | * 54 | * 本文件中的代码虽然能够正确计算出 UserSig,但仅适合快速调通 SDK 的基本功能,不适合线上产品, 55 | * 这是因为客户端代码中的 SECRETKEY 很容易被反编译逆向破解,尤其是 Web 端的代码被破解的难度几乎为零。 56 | * 一旦您的密钥泄露,攻击者就可以计算出正确的 UserSig 来盗用您的腾讯云流量。 57 | * 58 | * 正确的做法是将 UserSig 的计算代码和加密密钥放在您的业务服务器上,然后由 App 按需向您的服务器获取实时算出的 UserSig。 59 | * 由于破解服务器的成本要高于破解客户端 App,所以服务器计算的方案能够更好地保护您的加密密钥。 60 | * 61 | * 文档:https://cloud.tencent.com/document/product/269/32688#Server 62 | */ 63 | public static String genTestUserSig(long sdkAppId, String secretKey, String userId) { 64 | return GenTLSSignature(sdkAppId, userId, EXPIRETIME, null, secretKey); 65 | } 66 | 67 | /** 68 | * 生成 tls 票据 69 | * 70 | * @param sdkappid 应用的 appid 71 | * @param userId 用户 id 72 | * @param expire 有效期,单位是秒 73 | * @param userbuf 默认填写null 74 | * @param priKeyContent 生成 tls 票据使用的私钥内容 75 | * @return 如果出错,会返回为空,或者有异常打印,成功返回有效的票据 76 | */ 77 | private static String GenTLSSignature(long sdkappid, String userId, long expire, byte[] userbuf, String priKeyContent) { 78 | if (TextUtils.isEmpty(priKeyContent)) { 79 | return ""; 80 | } 81 | long currTime = System.currentTimeMillis() / 1000; 82 | JSONObject sigDoc = new JSONObject(); 83 | try { 84 | sigDoc.put("TLS.ver", "2.0"); 85 | sigDoc.put("TLS.identifier", userId); 86 | sigDoc.put("TLS.sdkappid", sdkappid); 87 | sigDoc.put("TLS.expire", expire); 88 | sigDoc.put("TLS.time", currTime); 89 | } catch (JSONException e) { 90 | e.printStackTrace(); 91 | } 92 | 93 | String base64UserBuf = null; 94 | if (null != userbuf) { 95 | base64UserBuf = Base64.encodeToString(userbuf, Base64.NO_WRAP); 96 | try { 97 | sigDoc.put("TLS.userbuf", base64UserBuf); 98 | } catch (JSONException e) { 99 | e.printStackTrace(); 100 | } 101 | } 102 | String sig = hmacsha256(sdkappid, userId, currTime, expire, priKeyContent, base64UserBuf); 103 | if (sig.length() == 0) { 104 | return ""; 105 | } 106 | try { 107 | sigDoc.put("TLS.sig", sig); 108 | } catch (JSONException e) { 109 | e.printStackTrace(); 110 | } 111 | Deflater compressor = new Deflater(); 112 | compressor.setInput(sigDoc.toString().getBytes(Charset.forName("UTF-8"))); 113 | compressor.finish(); 114 | byte[] compressedBytes = new byte[2048]; 115 | int compressedBytesLength = compressor.deflate(compressedBytes); 116 | compressor.end(); 117 | return new String(base64EncodeUrl(Arrays.copyOfRange(compressedBytes, 0, compressedBytesLength))); 118 | } 119 | 120 | 121 | private static String hmacsha256(long sdkappid, String userId, long currTime, long expire, String priKeyContent, String base64Userbuf) { 122 | String contentToBeSigned = "TLS.identifier:" + userId + "\n" 123 | + "TLS.sdkappid:" + sdkappid + "\n" 124 | + "TLS.time:" + currTime + "\n" 125 | + "TLS.expire:" + expire + "\n"; 126 | if (null != base64Userbuf) { 127 | contentToBeSigned += "TLS.userbuf:" + base64Userbuf + "\n"; 128 | } 129 | try { 130 | byte[] byteKey = priKeyContent.getBytes("UTF-8"); 131 | Mac hmac = Mac.getInstance("HmacSHA256"); 132 | SecretKeySpec keySpec = new SecretKeySpec(byteKey, "HmacSHA256"); 133 | hmac.init(keySpec); 134 | byte[] byteSig = hmac.doFinal(contentToBeSigned.getBytes("UTF-8")); 135 | return new String(Base64.encode(byteSig, Base64.NO_WRAP)); 136 | } catch (UnsupportedEncodingException e) { 137 | return ""; 138 | } catch (NoSuchAlgorithmException e) { 139 | return ""; 140 | } catch (InvalidKeyException e) { 141 | return ""; 142 | } 143 | } 144 | 145 | private static byte[] base64EncodeUrl(byte[] input) { 146 | byte[] base64 = new String(Base64.encode(input, Base64.NO_WRAP)).getBytes(); 147 | for (int i = 0; i < base64.length; ++i) 148 | switch (base64[i]) { 149 | case '+': 150 | base64[i] = '*'; 151 | break; 152 | case '/': 153 | base64[i] = '-'; 154 | break; 155 | case '=': 156 | base64[i] = '_'; 157 | break; 158 | default: 159 | break; 160 | } 161 | return base64; 162 | } 163 | 164 | } 165 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/yunchao/tencentim/demo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.demo; 2 | 3 | import android.content.Context; 4 | import android.os.Bundle; 5 | import android.text.TextUtils; 6 | import android.util.Log; 7 | import com.facebook.react.ReactActivity; 8 | import com.huawei.android.hms.agent.HMSAgent; 9 | import com.huawei.android.hms.agent.common.handler.ConnectHandler; 10 | import com.huawei.android.hms.agent.push.handler.GetTokenHandler; 11 | import com.tencent.imsdk.log.QLog; 12 | import com.tencent.imsdk.utils.IMFunc; 13 | import com.tencent.qcloud.tim.uikit.TUIKit; 14 | import com.tencent.qcloud.tim.uikit.base.IMEventListener; 15 | import com.tencent.qcloud.tim.uikit.utils.ToastUtil; 16 | import com.yunchao.tencentim.demo.utils.ThirdPushTokenMgr; 17 | 18 | public class MainActivity extends ReactActivity { 19 | private static final String TAG = "HUAWEIPushReceiver"; 20 | 21 | @Override 22 | protected void onCreate(Bundle savedInstanceState) { 23 | super.onCreate(savedInstanceState); 24 | 25 | if (IMFunc.isBrandHuawei()) { 26 | // 华为离线推送 27 | HMSAgent.connect(this, new ConnectHandler() { 28 | @Override 29 | public void onConnect(int rst) { 30 | QLog.i(TAG, "huawei push HMS connect end:" + rst); 31 | } 32 | }); 33 | getHuaWeiPushToken(); 34 | } 35 | 36 | } 37 | 38 | private void getHuaWeiPushToken() { 39 | HMSAgent.Push.getToken(new GetTokenHandler() { 40 | @Override 41 | public void onResult(int rtnCode) { 42 | QLog.i(TAG, "huawei push get token result code: " + rtnCode); 43 | } 44 | }); 45 | } 46 | 47 | /** 48 | * Returns the name of the main component registered from JavaScript. This is used to schedule 49 | * rendering of the component. 50 | */ 51 | @Override 52 | protected String getMainComponentName() { 53 | return "demo"; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/yunchao/tencentim/demo/MainApplication.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.demo; 2 | 3 | import android.app.Activity; 4 | import android.app.Application; 5 | import android.os.Bundle; 6 | import com.facebook.react.PackageList; 7 | import com.facebook.react.ReactApplication; 8 | import com.facebook.react.ReactNativeHost; 9 | import com.facebook.react.ReactPackage; 10 | import com.facebook.soloader.SoLoader; 11 | import com.huawei.android.hms.agent.HMSAgent; 12 | import com.tencent.imsdk.TIMBackgroundParam; 13 | import com.tencent.imsdk.TIMCallBack; 14 | import com.tencent.imsdk.TIMConversation; 15 | import com.tencent.imsdk.TIMManager; 16 | import com.tencent.imsdk.TIMMessage; 17 | import com.tencent.imsdk.TIMOfflinePushNotification; 18 | import com.tencent.imsdk.session.SessionWrapper; 19 | import com.tencent.imsdk.utils.IMFunc; 20 | import com.tencent.imsdk.v2.V2TIMMessage; 21 | import com.tencent.qcloud.tim.uikit.TUIKit; 22 | import com.tencent.qcloud.tim.uikit.base.IMEventListener; 23 | import com.yunchao.tencentim.IMApplication; 24 | import com.yunchao.tencentim.demo.thridpush.MessageNotification; 25 | import com.yunchao.tencentim.demo.utils.IMLog; 26 | 27 | import java.util.List; 28 | 29 | public class MainApplication extends Application implements ReactApplication { 30 | private static final String TAG = MainApplication.class.getSimpleName(); 31 | 32 | private static MainApplication instance; 33 | 34 | public static MainApplication instance() { 35 | return instance; 36 | } 37 | 38 | private final ReactNativeHost mReactNativeHost = 39 | new ReactNativeHost(this) { 40 | @Override 41 | public boolean getUseDeveloperSupport() { 42 | return BuildConfig.DEBUG; 43 | } 44 | 45 | @Override 46 | protected List getPackages() { 47 | @SuppressWarnings("UnnecessaryLocalVariable") 48 | List packages = new PackageList(this).getPackages(); 49 | // Packages that cannot be autolinked yet can be added manually here, for example: 50 | // packages.add(new MyReactNativePackage()); 51 | packages.add(new DemoPackage()); // <-- Add this line with your package name. 52 | return packages; 53 | } 54 | 55 | @Override 56 | protected String getJSMainModuleName() { 57 | return "index"; 58 | } 59 | }; 60 | 61 | @Override 62 | public ReactNativeHost getReactNativeHost() { 63 | return mReactNativeHost; 64 | } 65 | 66 | @Override 67 | public void onCreate() { 68 | super.onCreate(); 69 | instance = this; 70 | 71 | SoLoader.init(this, /* native exopackage */ false); 72 | 73 | // 初始化 Context 74 | IMApplication.setContext(this, MainActivity.class); 75 | //初始化IM 76 | tencentIMInitMethod(); 77 | 78 | } 79 | 80 | private void tencentIMInitMethod() { 81 | instance = this; 82 | if (SessionWrapper.isMainProcess(getApplicationContext())) { 83 | 84 | // 配置 Config,请按需配置 85 | if (IMFunc.isBrandHuawei()) { 86 | // 华为离线推送 87 | HMSAgent.init(this); 88 | } 89 | registerActivityLifecycleCallbacks(new StatisticActivityLifecycleCallback()); 90 | } 91 | } 92 | 93 | class StatisticActivityLifecycleCallback implements ActivityLifecycleCallbacks { 94 | private int foregroundActivities = 0; 95 | private boolean isChangingConfiguration; 96 | private IMEventListener mIMEventListener = new IMEventListener() { 97 | @Override 98 | public void onNewMessage(V2TIMMessage v2TIMMessage) { 99 | MessageNotification notification = MessageNotification.getInstance(); 100 | notification.notify(v2TIMMessage); 101 | } 102 | 103 | }; 104 | 105 | @Override 106 | public void onActivityCreated(Activity activity, Bundle bundle) { 107 | IMLog.i(IMLog.TAG, "onActivityCreated bundle: " + bundle); 108 | } 109 | 110 | @Override 111 | public void onActivityStarted(Activity activity) { 112 | foregroundActivities++; 113 | if (foregroundActivities == 1 && !isChangingConfiguration) { 114 | // 应用切到前台 115 | IMLog.i(IMLog.TAG, "application enter foreground"); 116 | TIMManager.getInstance().doForeground(new TIMCallBack() { 117 | @Override 118 | public void onError(int code, String desc) { 119 | IMLog.e(IMLog.TAG, "doForeground err = " + code + ", desc = " + desc); 120 | } 121 | 122 | @Override 123 | public void onSuccess() { 124 | IMLog.i(IMLog.TAG, "doForeground success"); 125 | } 126 | }); 127 | TUIKit.removeIMEventListener(mIMEventListener); 128 | } 129 | isChangingConfiguration = false; 130 | } 131 | 132 | @Override 133 | public void onActivityResumed(Activity activity) { 134 | } 135 | 136 | @Override 137 | public void onActivityPaused(Activity activity) { 138 | } 139 | 140 | @Override 141 | public void onActivityStopped(Activity activity) { 142 | foregroundActivities--; 143 | if (foregroundActivities == 0) { 144 | // 应用切到后台 145 | IMLog.i(IMLog.TAG, "application enter background"); 146 | int unReadCount = 0; 147 | List conversationList = TIMManager.getInstance().getConversationList(); 148 | for (TIMConversation timConversation : conversationList) { 149 | unReadCount += timConversation.getUnreadMessageNum(); 150 | } 151 | TIMBackgroundParam param = new TIMBackgroundParam(); 152 | param.setC2cUnread(unReadCount); 153 | TIMManager.getInstance().doBackground(param, new TIMCallBack() { 154 | @Override 155 | public void onError(int code, String desc) { 156 | IMLog.e(IMLog.TAG, "doBackground err = " + code + ", desc = " + desc); 157 | } 158 | 159 | @Override 160 | public void onSuccess() { 161 | IMLog.i(IMLog.TAG, "doBackground success"); 162 | } 163 | }); 164 | // 应用退到后台,消息转化为系统通知 165 | TUIKit.addIMEventListener(mIMEventListener); 166 | } 167 | isChangingConfiguration = activity.isChangingConfigurations(); 168 | } 169 | 170 | @Override 171 | public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { 172 | } 173 | 174 | @Override 175 | public void onActivityDestroyed(Activity activity) { 176 | } 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/yunchao/tencentim/demo/thirdpush/HUAWEIPushReceiver.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.demo.thirdpush; 2 | 3 | import android.content.Context; 4 | import android.os.Bundle; 5 | import android.util.Log; 6 | 7 | import com.huawei.hms.support.api.push.PushReceiver; 8 | import com.yunchao.tencentim.demo.utils.ThirdPushTokenMgr; 9 | 10 | import java.nio.charset.StandardCharsets; 11 | 12 | public class HUAWEIPushReceiver extends PushReceiver { 13 | private static final String TAG = "HUAWEIPushReceiver"; 14 | 15 | @Override 16 | public boolean onPushMsg(Context context, byte[] msgBytes, Bundle extras) { 17 | try { 18 | //CP可以自己解析消息内容,然后做相应的处理 19 | String content = null; 20 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { 21 | content = new String(msgBytes, StandardCharsets.UTF_8); 22 | } 23 | Log.i(TAG, "收到PUSH透传消息,消息内容为 : " + content); 24 | } catch (Exception e) { 25 | e.printStackTrace(); 26 | } 27 | return false; 28 | } 29 | 30 | @Override 31 | public void onToken(Context context, String token, Bundle extras) { 32 | Log.i(TAG, "onToken:" + token); 33 | ThirdPushTokenMgr.getInstance().setThirdPushToken(token); // token 在此处传入,后续推送信息上报时需要使用 34 | ThirdPushTokenMgr.getInstance().setPushTokenToTIM(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/yunchao/tencentim/demo/utils/IMLog.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.demo.utils; 2 | 3 | import com.tencent.imsdk.log.QLog; 4 | 5 | public class IMLog extends QLog { 6 | 7 | public static final String TAG = "TencentIM"; 8 | 9 | private static final String PRE = "TencentIM-TUIKit-"; 10 | 11 | private static String mixTag(String tag) { 12 | return PRE + tag; 13 | } 14 | 15 | /** 16 | * 打印INFO级别日志 17 | * 18 | * @param strTag TAG 19 | * @param strInfo 消息 20 | */ 21 | public static void v(String strTag, String strInfo) { 22 | QLog.v(mixTag(strTag), strInfo); 23 | } 24 | 25 | /** 26 | * 打印DEBUG级别日志 27 | * 28 | * @param strTag TAG 29 | * @param strInfo 消息 30 | */ 31 | public static void d(String strTag, String strInfo) { 32 | QLog.d(mixTag(strTag), strInfo); 33 | } 34 | 35 | /** 36 | * 打印INFO级别日志 37 | * 38 | * @param strTag TAG 39 | * @param strInfo 消息 40 | */ 41 | public static void i(String strTag, String strInfo) { 42 | QLog.i(mixTag(strTag), strInfo); 43 | } 44 | 45 | /** 46 | * 打印WARN级别日志 47 | * 48 | * @param strTag TAG 49 | * @param strInfo 消息 50 | */ 51 | public static void w(String strTag, String strInfo) { 52 | QLog.w(mixTag(strTag), strInfo); 53 | } 54 | 55 | /** 56 | * 打印ERROR级别日志 57 | * 58 | * @param strTag TAG 59 | * @param strInfo 消息 60 | */ 61 | public static void e(String strTag, String strInfo) { 62 | QLog.e(mixTag(strTag), strInfo); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/yunchao/tencentim/demo/utils/PrivateConstants.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.demo.utils; 2 | 3 | public class PrivateConstants { 4 | 5 | /****** 华为离线推送参数start ******/ 6 | // 在腾讯云控制台上传第三方推送证书后分配的证书ID 7 | public static final long HW_PUSH_BUZID = 13120; 8 | // 华为开发者联盟给应用分配的应用APPID 9 | public static final String HW_PUSH_APPID = "102999473"; // 见清单文件 10 | /****** 华为离线推送参数end ******/ 11 | 12 | } 13 | -------------------------------------------------------------------------------- /demo/android/app/src/main/java/com/yunchao/tencentim/demo/utils/ThirdPushTokenMgr.java: -------------------------------------------------------------------------------- 1 | package com.yunchao.tencentim.demo.utils; 2 | 3 | import android.text.TextUtils; 4 | import android.util.Log; 5 | 6 | import com.tencent.imsdk.TIMCallBack; 7 | import com.tencent.imsdk.TIMManager; 8 | import com.tencent.imsdk.TIMOfflinePushToken; 9 | import com.tencent.imsdk.log.QLog; 10 | import com.tencent.imsdk.utils.IMFunc; 11 | 12 | /** 13 | * 用来保存厂商注册离线推送token的管理类示例,当登陆im后,通过 setOfflinePushToken 上报证书 ID 及设备 token 给im后台。开发者可以根据自己的需求灵活实现 14 | */ 15 | 16 | public class ThirdPushTokenMgr { 17 | 18 | private static final String TAG = "HUAWEIPushReceiver"; 19 | private String mThirdPushToken; 20 | private boolean mIsTokenSet; 21 | 22 | public static ThirdPushTokenMgr getInstance() { 23 | return ThirdPushTokenHolder.instance; 24 | } 25 | 26 | public String getThirdPushToken() { 27 | return mThirdPushToken; 28 | } 29 | 30 | public void setThirdPushToken(String mThirdPushToken) { 31 | this.mThirdPushToken = mThirdPushToken; 32 | } 33 | 34 | public void setPushTokenToTIM() { 35 | String token = ThirdPushTokenMgr.getInstance().getThirdPushToken(); 36 | if (TextUtils.isEmpty(token)) { 37 | QLog.i(TAG, "setPushTokenToTIM third token is empty"); 38 | mIsTokenSet = false; 39 | return; 40 | } 41 | 42 | TIMOfflinePushToken param = null; 43 | if (IMFunc.isBrandHuawei()) { 44 | param = new TIMOfflinePushToken(PrivateConstants.HW_PUSH_BUZID, token); 45 | } else { 46 | return; 47 | } 48 | TIMManager.getInstance().setOfflinePushToken(param, new TIMCallBack() { 49 | @Override 50 | public void onError(int code, String desc) { 51 | Log.d(TAG, "setOfflinePushToken err code = " + code); 52 | } 53 | 54 | @Override 55 | public void onSuccess() { 56 | Log.d(TAG, "setOfflinePushToken success"); 57 | mIsTokenSet = true; 58 | } 59 | }); 60 | } 61 | 62 | private static class ThirdPushTokenHolder { 63 | private static final ThirdPushTokenMgr instance = new ThirdPushTokenMgr(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | demo 3 | 4 | -------------------------------------------------------------------------------- /demo/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /demo/android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext { 5 | buildToolsVersion = "28.0.3" 6 | minSdkVersion = 19 7 | compileSdkVersion = 28 8 | targetSdkVersion = 28 9 | } 10 | repositories { 11 | google() 12 | jcenter() 13 | } 14 | dependencies { 15 | classpath("com.android.tools.build:gradle:3.5.3") 16 | // NOTE: Do not place your application dependencies here; they belong 17 | // in the individual module build.gradle files 18 | } 19 | } 20 | 21 | allprojects { 22 | repositories { 23 | mavenLocal() 24 | maven { 25 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 26 | url("$rootDir/../node_modules/react-native/android") 27 | } 28 | maven { 29 | // Android JSC is installed from npm 30 | url("$rootDir/../node_modules/jsc-android/dist") 31 | } 32 | maven {url 'http://developer.huawei.com/repo/'} 33 | google() 34 | jcenter() 35 | maven { url 'https://www.jitpack.io' } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /demo/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | # AndroidX package structure to make it clearer which packages are bundled with the 21 | # Android operating system, and which are packaged with your app's APK 22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 23 | android.useAndroidX=true 24 | # Automatically convert third-party libraries to use AndroidX 25 | android.enableJetifier=true 26 | 27 | # Version of flipper SDK to use with React Native 28 | FLIPPER_VERSION=0.54.0 29 | -------------------------------------------------------------------------------- /demo/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mengyou658/react-native-tencent-im-ui/b78e9d9b69a432fcfa84b287cbf57485dae28749/demo/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /demo/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.2-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /demo/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /demo/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /demo/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'demo' 2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) 3 | include ':app' 4 | -------------------------------------------------------------------------------- /demo/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo", 3 | "displayName": "demo" 4 | } -------------------------------------------------------------------------------- /demo/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /demo/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import {AppRegistry} from 'react-native'; 6 | import App from './App'; 7 | import {name as appName} from './app.json'; 8 | 9 | AppRegistry.registerComponent(appName, () => App); 10 | -------------------------------------------------------------------------------- /demo/ios/Podfile: -------------------------------------------------------------------------------- 1 | # 这里使用的是清华镜像 2 | source 'https://mirrors.tuna.tsinghua.edu.cn/git/CocoaPods/Specs.git' 3 | require_relative '../node_modules/react-native/scripts/react_native_pods' 4 | require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' 5 | 6 | platform :ios, '10.0' 7 | 8 | target 'demo' do 9 | config = use_native_modules! 10 | 11 | use_react_native!(:path => config["reactNativePath"]) 12 | 13 | target 'demoTests' do 14 | inherit! :complete 15 | # Pods for testing 16 | end 17 | 18 | # Enables Flipper. 19 | # 20 | # Note that if you have use_frameworks! enabled, Flipper will not work and 21 | # you should disable these next few lines. 22 | use_flipper! 23 | post_install do |installer| 24 | flipper_post_install(installer) 25 | end 26 | end 27 | 28 | target 'demo-tvOS' do 29 | # Pods for demo-tvOS 30 | 31 | target 'demo-tvOSTests' do 32 | inherit! :search_paths 33 | # Pods for testing 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /demo/ios/demo-tvOS/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | NSAppTransportSecurity 26 | 27 | NSExceptionDomains 28 | 29 | localhost 30 | 31 | NSExceptionAllowsInsecureHTTPLoads 32 | 33 | 34 | 35 | 36 | NSLocationWhenInUseUsageDescription 37 | 38 | UILaunchStoryboardName 39 | LaunchScreen 40 | UIRequiredDeviceCapabilities 41 | 42 | armv7 43 | 44 | UISupportedInterfaceOrientations 45 | 46 | UIInterfaceOrientationPortrait 47 | UIInterfaceOrientationLandscapeLeft 48 | UIInterfaceOrientationLandscapeRight 49 | 50 | UIViewControllerBasedStatusBarAppearance 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /demo/ios/demo-tvOSTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /demo/ios/demo.xcodeproj/xcshareddata/xcschemes/demo-tvOS.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /demo/ios/demo.xcodeproj/xcshareddata/xcschemes/demo.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /demo/ios/demo.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /demo/ios/demo.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /demo/ios/demo/AppDelegate.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | @interface AppDelegate : UIResponder 5 | 6 | @property (nonatomic, strong) UIWindow *window; 7 | 8 | @end 9 | -------------------------------------------------------------------------------- /demo/ios/demo/AppDelegate.m: -------------------------------------------------------------------------------- 1 | #import "AppDelegate.h" 2 | 3 | #import 4 | #import 5 | #import 6 | 7 | #ifdef FB_SONARKIT_ENABLED 8 | #import 9 | #import 10 | #import 11 | #import 12 | #import 13 | #import 14 | #import "ConversationController.h" 15 | static void InitializeFlipper(UIApplication *application) { 16 | FlipperClient *client = [FlipperClient sharedClient]; 17 | SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults]; 18 | [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]]; 19 | [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]]; 20 | [client addPlugin:[FlipperKitReactPlugin new]]; 21 | [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]]; 22 | [client start]; 23 | } 24 | #endif 25 | 26 | @implementation AppDelegate 27 | 28 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 29 | { 30 | #ifdef FB_SONARKIT_ENABLED 31 | InitializeFlipper(application); 32 | #endif 33 | 34 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; 35 | RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge 36 | moduleName:@"demo" 37 | initialProperties:nil]; 38 | 39 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; 40 | 41 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 42 | UIViewController *rootViewController = [UIViewController new]; 43 | rootViewController.view = rootView; 44 | UINavigationController *nv = [[UINavigationController alloc] initWithRootViewController:rootViewController]; 45 | nv.navigationBar.hidden = YES; 46 | nv.delegate = self; 47 | 48 | self.window.rootViewController = nv; 49 | 50 | ConversationController *c = [ConversationController getInstance]; 51 | [c initNc: nv]; 52 | 53 | [self.window makeKeyAndVisible]; 54 | return YES; 55 | } 56 | 57 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge 58 | { 59 | #if DEBUG 60 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; 61 | #else 62 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; 63 | #endif 64 | } 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /demo/ios/demo/DemoModule.h: -------------------------------------------------------------------------------- 1 | // 2 | // RNTIMChatModel.h 3 | // fangbossApp 4 | // 5 | // Created by 云超 on 2020/9/26. 6 | // Copyright © 2020 Facebook. All rights reserved. 7 | // 8 | #import "TUIKit.h" 9 | #import 10 | #import 11 | #import 12 | #import 13 | 14 | @interface DemoModule : NSObject 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /demo/ios/demo/DemoModule.m: -------------------------------------------------------------------------------- 1 | // 2 | // DemoModule.m 3 | // fangbossApp 4 | // 5 | // Created by 云超 on 2020/9/26. 6 | // Copyright © 2020 Facebook. All rights reserved. 7 | // 8 | 9 | #import "TUIKit.h" 10 | #import 11 | #import 12 | #import "TUIConversationListController.h" 13 | #import "DemoModule.h" 14 | #import "GenerateTestUserSig.h" 15 | @implementation DemoModule 16 | 17 | RCT_EXPORT_MODULE(DemoModule); 18 | RCT_EXPORT_METHOD(getSig:(int)sdkAppId 19 | secretKey:(NSString *)secretKey 20 | identifier:(NSString *)identifier 21 | resolver:(RCTPromiseResolveBlock)resolve 22 | rejecter:(RCTPromiseRejectBlock)reject 23 | ) 24 | { 25 | GenerateTestUserSig *generateTestUserSig = [[GenerateTestUserSig alloc] init]; 26 | NSString *str = [generateTestUserSig genTestUserSig: sdkAppId 27 | secretKey:secretKey 28 | identifier:identifier]; 29 | resolve(str); 30 | } 31 | 32 | @end 33 | 34 | -------------------------------------------------------------------------------- /demo/ios/demo/GenerateTestUserSig.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Module: GenerateTestUserSig 3 | * 4 | * Function: 用于生成测试用的 UserSig,UserSig 是腾讯云为其云服务设计的一种安全保护签名。 5 | * 其计算方法是对 SDKAppID、UserID 和 EXPIRETIME 进行加密,加密算法为 HMAC-SHA256。 6 | * 7 | * Attention: 请不要将如下代码发布到您的线上正式版本的 App 中,原因如下: 8 | * 9 | * 本文件中的代码虽然能够正确计算出 UserSig,但仅适合快速调通 SDK 的基本功能,不适合线上产品, 10 | * 这是因为客户端代码中的 SECRETKEY 很容易被反编译逆向破解,尤其是 Web 端的代码被破解的难度几乎为零。 11 | * 一旦您的密钥泄露,攻击者就可以计算出正确的 UserSig 来盗用您的腾讯云流量。 12 | * 13 | * 正确的做法是将 UserSig 的计算代码和加密密钥放在您的业务服务器上,然后由 App 按需向您的服务器获取实时算出的 UserSig。 14 | * 由于破解服务器的成本要高于破解客户端 App,所以服务器计算的方案能够更好地保护您的加密密钥。 15 | * 16 | * Reference:https://cloud.tencent.com/document/product/269/32688#Server 17 | */ 18 | 19 | #import 20 | 21 | NS_ASSUME_NONNULL_BEGIN 22 | 23 | /** 24 | * 签名过期时间,建议不要设置的过短 25 | * 26 | * 时间单位:秒 27 | * 默认时间:7 x 24 x 60 x 60 = 604800 = 7 天 28 | */ 29 | static const int EXPIRETIME = 604800; 30 | 31 | 32 | @interface GenerateTestUserSig : NSObject 33 | /** 34 | * 计算 UserSig 签名 35 | * 36 | * 函数内部使用 HMAC-SHA256 非对称加密算法,对 SDKAPPID、userId 和 EXPIRETIME 进行加密。 37 | * 38 | * @note: 请不要将如下代码发布到您的线上正式版本的 App 中,原因如下: 39 | * 40 | * 本文件中的代码虽然能够正确计算出 UserSig,但仅适合快速调通 SDK 的基本功能,不适合线上产品, 41 | * 这是因为客户端代码中的 SECRETKEY 很容易被反编译逆向破解,尤其是 Web 端的代码被破解的难度几乎为零。 42 | * 一旦您的密钥泄露,攻击者就可以计算出正确的 UserSig 来盗用您的腾讯云流量。 43 | * 44 | * 正确的做法是将 UserSig 的计算代码和加密密钥放在您的业务服务器上,然后由 App 按需向您的服务器获取实时算出的 UserSig。 45 | * 由于破解服务器的成本要高于破解客户端 App,所以服务器计算的方案能够更好地保护您的加密密钥。 46 | * 47 | * 文档:https://cloud.tencent.com/document/product/269/32688#Server 48 | */ 49 | - (NSString *)genTestUserSig:(int)sdkAppId 50 | secretKey:(NSString *)secretKey 51 | identifier:(NSString *)identifier; 52 | @end 53 | 54 | NS_ASSUME_NONNULL_END 55 | -------------------------------------------------------------------------------- /demo/ios/demo/GenerateTestUserSig.m: -------------------------------------------------------------------------------- 1 | #import "GenerateTestUserSig.h" 2 | #import 3 | #import 4 | 5 | @implementation GenerateTestUserSig 6 | 7 | - (NSString *)genTestUserSig:(int)sdkAppId 8 | secretKey:(NSString *)secretKey 9 | identifier:(NSString *)identifier 10 | { 11 | CFTimeInterval current = CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970; 12 | long TLSTime = floor(current); 13 | NSMutableDictionary *obj = [@{@"TLS.ver": @"2.0", 14 | @"TLS.identifier": identifier, 15 | @"TLS.sdkappid": @(sdkAppId), 16 | @"TLS.expire": @(EXPIRETIME), 17 | @"TLS.time": @(TLSTime)} mutableCopy]; 18 | NSMutableString *stringToSign = [[NSMutableString alloc] init]; 19 | NSArray *keyOrder = @[@"TLS.identifier", 20 | @"TLS.sdkappid", 21 | @"TLS.time", 22 | @"TLS.expire"]; 23 | for (NSString *key in keyOrder) { 24 | [stringToSign appendFormat:@"%@:%@\n", key, obj[key]]; 25 | } 26 | NSLog(@"%@", stringToSign); 27 | //NSString *sig = [self sigString:stringToSign]; 28 | NSString *sig = [self hmac:stringToSign 29 | secretKey:secretKey]; 30 | 31 | obj[@"TLS.sig"] = sig; 32 | NSLog(@"sig: %@", sig); 33 | NSError *error = nil; 34 | NSData *jsonToZipData = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&error]; 35 | if (error) { 36 | NSLog(@"[Error] json serialization failed: %@", error); 37 | return @""; 38 | } 39 | 40 | const Bytef* zipsrc = (const Bytef*)[jsonToZipData bytes]; 41 | uLongf srcLen = jsonToZipData.length; 42 | uLong upperBound = compressBound(srcLen); 43 | Bytef *dest = (Bytef*)malloc(upperBound); 44 | uLongf destLen = upperBound; 45 | int ret = compress2(dest, &destLen, (const Bytef*)zipsrc, srcLen, Z_BEST_SPEED); 46 | if (ret != Z_OK) { 47 | NSLog(@"[Error] Compress Error %d, upper bound: %lu", ret, upperBound); 48 | free(dest); 49 | return @""; 50 | } 51 | NSString *result = [self base64URL: [NSData dataWithBytesNoCopy:dest length:destLen]]; 52 | return result; 53 | } 54 | 55 | - (NSString *)hmac:(NSString *)plainText 56 | secretKey:(NSString *)secretKey 57 | { 58 | const char *cKey = [secretKey cStringUsingEncoding:NSASCIIStringEncoding]; 59 | const char *cData = [plainText cStringUsingEncoding:NSASCIIStringEncoding]; 60 | 61 | unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; 62 | 63 | CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); 64 | 65 | NSData *HMACData = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)]; 66 | return [HMACData base64EncodedStringWithOptions:0]; 67 | } 68 | 69 | - (NSString *)base64URL:(NSData *)data 70 | { 71 | NSString *result = [data base64EncodedStringWithOptions:0]; 72 | NSMutableString *final = [[NSMutableString alloc] init]; 73 | const char *cString = [result cStringUsingEncoding:NSUTF8StringEncoding]; 74 | for (int i = 0; i < result.length; ++ i) { 75 | char x = cString[i]; 76 | switch(x){ 77 | case '+': 78 | [final appendString:@"*"]; 79 | break; 80 | case '/': 81 | [final appendString:@"-"]; 82 | break; 83 | case '=': 84 | [final appendString:@"_"]; 85 | break; 86 | default: 87 | [final appendFormat:@"%c", x]; 88 | break; 89 | } 90 | } 91 | return final; 92 | } 93 | 94 | @end 95 | -------------------------------------------------------------------------------- /demo/ios/demo/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /demo/ios/demo/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /demo/ios/demo/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | demo 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSRequiresIPhoneOS 26 | 27 | NSAppTransportSecurity 28 | 29 | NSAllowsArbitraryLoads 30 | 31 | NSExceptionDomains 32 | 33 | localhost 34 | 35 | NSExceptionAllowsInsecureHTTPLoads 36 | 37 | 38 | 39 | 40 | NSLocationWhenInUseUsageDescription 41 | 42 | UILaunchStoryboardName 43 | LaunchScreen 44 | UIRequiredDeviceCapabilities 45 | 46 | armv7 47 | 48 | UISupportedInterfaceOrientations 49 | 50 | UIInterfaceOrientationPortrait 51 | 52 | UIViewControllerBasedStatusBarAppearance 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /demo/ios/demo/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 25 | 31 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /demo/ios/demo/main.m: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #import "AppDelegate.h" 4 | 5 | int main(int argc, char * argv[]) { 6 | @autoreleasepool { 7 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /demo/ios/demoTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /demo/ios/demoTests/demoTests.m: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | #import 5 | #import 6 | 7 | #define TIMEOUT_SECONDS 600 8 | #define TEXT_TO_LOOK_FOR @"Welcome to React" 9 | 10 | @interface demoTests : XCTestCase 11 | 12 | @end 13 | 14 | @implementation demoTests 15 | 16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test 17 | { 18 | if (test(view)) { 19 | return YES; 20 | } 21 | for (UIView *subview in [view subviews]) { 22 | if ([self findSubviewInView:subview matching:test]) { 23 | return YES; 24 | } 25 | } 26 | return NO; 27 | } 28 | 29 | - (void)testRendersWelcomeScreen 30 | { 31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController]; 32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 33 | BOOL foundElement = NO; 34 | 35 | __block NSString *redboxError = nil; 36 | #ifdef DEBUG 37 | RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 38 | if (level >= RCTLogLevelError) { 39 | redboxError = message; 40 | } 41 | }); 42 | #endif 43 | 44 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 45 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 46 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 47 | 48 | foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { 49 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 50 | return YES; 51 | } 52 | return NO; 53 | }]; 54 | } 55 | 56 | #ifdef DEBUG 57 | RCTSetLogFunction(RCTDefaultLogFunction); 58 | #endif 59 | 60 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 61 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 62 | } 63 | 64 | 65 | @end 66 | -------------------------------------------------------------------------------- /demo/metro.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Metro configuration for React Native 3 | * https://github.com/facebook/react-native 4 | * 5 | * @format 6 | */ 7 | 8 | module.exports = { 9 | transformer: { 10 | getTransformOptions: async () => ({ 11 | transform: { 12 | experimentalImportSupport: false, 13 | inlineRequires: false, 14 | }, 15 | }), 16 | }, 17 | }; 18 | -------------------------------------------------------------------------------- /demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "android": "react-native run-android", 7 | "android:release": "react-native run-android --variant=release", 8 | "ios": "react-native run-ios", 9 | "start": "react-native start", 10 | "start-clean": "react-native start --reset-cache", 11 | "test": "jest", 12 | "lint": "eslint ." 13 | }, 14 | "dependencies": { 15 | "react": "16.13.1", 16 | "react-native": "0.63.3", 17 | "react-native-tencent-im-ui": "^1.1.3", 18 | "teaset": "^0.7.4" 19 | }, 20 | "devDependencies": { 21 | "@babel/core": "^7.8.4", 22 | "@babel/runtime": "^7.8.4", 23 | "@react-native-community/eslint-config": "^1.1.0", 24 | "babel-jest": "^25.1.0", 25 | "eslint": "^6.5.1", 26 | "jest": "^25.1.0", 27 | "metro-react-native-babel-preset": "^0.59.0", 28 | "react-test-renderer": "16.13.1" 29 | }, 30 | "jest": { 31 | "preset": "react-native" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /demo/readme.md: -------------------------------------------------------------------------------- 1 | # react-native-tecent-ui-demo 2 | 注意,LiteAVSDK_TRTC不支持模拟器运行,请使用真机运行 3 | -------------------------------------------------------------------------------- /demo/src/conView.js: -------------------------------------------------------------------------------- 1 | 2 | // 展示聊天列表界面 3 | import {TIMConversationModel, TIMInitSdk, TIMLogin, TIMLogout, TIMStartChat} from 'react-native-tencent-im-ui'; 4 | import React from "react"; 5 | import { 6 | SafeAreaView, 7 | StatusBar, 8 | } from 'react-native'; 9 | 10 | export default class Conversation extends React.Component { 11 | 12 | render() { 13 | return 14 | 15 | 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /demo/src/genSig.js: -------------------------------------------------------------------------------- 1 | import { NativeModules } from "react-native"; 2 | 3 | const DemoModule = NativeModules.DemoModule; 4 | 5 | /** 6 | * 腾讯云 SDKAppId,需要替换为您自己账号下的 SDKAppId。 7 | * 8 | * 进入腾讯云实时音视频[控制台](https://console.cloud.tencent.com/rav ) 创建应用,即可看到 SDKAppId, 9 | * 它是腾讯云用于区分客户的唯一标识。 10 | */ 11 | export const SDKAPPID = 1400431123; 12 | 13 | /** 14 | * 计算签名用的加密密钥,获取步骤如下: 15 | * 16 | * step1. 进入腾讯云实时音视频[控制台](https://console.cloud.tencent.com/rav ),如果还没有应用就创建一个, 17 | * step2. 单击“应用配置”进入基础配置页面,并进一步找到“帐号体系集成”部分。 18 | * step3. 点击“查看密钥”按钮,就可以看到计算 UserSig 使用的加密的密钥了,请将其拷贝并复制到如下的变量中 19 | * 20 | * 注意:该方案仅适用于调试Demo,正式上线前请将 UserSig 计算代码和密钥迁移到您的后台服务器上,以避免加密密钥泄露导致的流量盗用。 21 | * 文档:https://cloud.tencent.com/document/product/647/17275#Server 22 | */ 23 | export const SECRETKEY = 'de936233134cc03b9837bf1178a5306100728bfd31dfe25c71f5c945f18c7812'; 24 | 25 | /** 26 | * 这里测试使用,请勿模仿,正常需要从服务器端生成 27 | * @param userID 28 | * @returns {{userSig: *, SDKAppID: number}} 29 | */ 30 | export async function genTestUserSig(userID) { 31 | return await DemoModule.getSig(SDKAPPID, SECRETKEY, userID); 32 | } 33 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import ConversationModel from './lib/ConversationView'; 2 | import {initSdk, login, logout, startChat} from './lib/TencentIMModel'; 3 | 4 | export const TIMConversationModel = ConversationModel; 5 | export const TIMInitSdk = initSdk; 6 | export const TIMLogin = login; 7 | export const TIMLogout = logout; 8 | export const TIMStartChat = startChat; 9 | 10 | export default { 11 | TIMConversationModel, 12 | TIMInitSdk: TIMInitSdk, 13 | TIMLogin: TIMLogin, 14 | TIMLogout: TIMLogout, 15 | TIMStartChat: TIMStartChat 16 | }; 17 | -------------------------------------------------------------------------------- /ios/TxImUi/Controller/ChatViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ChatViewController.h 3 | // TUIKitDemo 4 | // 5 | // Created by kennethmiao on 2018/10/10. 6 | // Copyright © 2018年 Tencent. All rights reserved. 7 | // 8 | /** 腾讯云IM Demo 聊天视图 9 | * 本文件实现了聊天视图 10 | * 在用户需要收发群组、以及其他用户消息时提供UI 11 | * 12 | * 本类依赖于腾讯云 TUIKit和IMSDK 实现 13 | * 14 | */ 15 | #import 16 | #import "TUIChatController.h" 17 | #import "TUnReadView.h" 18 | @class TUIMessageCellData; 19 | @interface ChatViewController : UIViewController 20 | @property (nonatomic, strong) TUIConversationCellData *conversationData; 21 | @property (nonatomic, strong) TUnReadView *unRead; 22 | @property (nonatomic, strong) UINavigationController * nc; 23 | /** 24 | * 获取实例 25 | */ 26 | + (instancetype)getInstance; 27 | - (void) initNc:(UINavigationController *)nc; 28 | - (void)viewDidLoadAsync; 29 | - (void)sendMessage:(TUIMessageCellData*)msg; 30 | @end 31 | -------------------------------------------------------------------------------- /ios/TxImUi/Controller/ConversationController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ConversationController.h 3 | // TUIKitDemo 4 | // 5 | // Created by kennethmiao on 2018/10/10. 6 | // Copyright © 2018年 Tencent. All rights reserved. 7 | // 8 | /** 腾讯云IM Demo 对话列表视图 9 | * 本文件实现了对话列表视图控制器,即下方按钮“消息”对应的视图控制器 10 | * 您可以从此处查看最近消息,整理您的消息列表 11 | * 12 | * 本类依赖于腾讯云 TUIKit和IMSDK 实现 13 | */ 14 | #import 15 | 16 | @interface ConversationController : UIViewController 17 | @property (nonatomic, strong) UINavigationController * nc; 18 | /** 19 | * 获取实例 20 | */ 21 | + (instancetype)getInstance; 22 | - (void) initNc:(UINavigationController *)nc; 23 | /** 24 | *跳转到对应的聊天界面 25 | */ 26 | - (void)pushToChatViewController:(NSString *)groupID userID:(NSString *)userID title:(NSString *)title; 27 | @end 28 | -------------------------------------------------------------------------------- /ios/TxImUi/Custom/MyCustomCell.h: -------------------------------------------------------------------------------- 1 | // 2 | // MyCustomCell.h 3 | // TUIKitDemo 4 | // 5 | // Created by annidyfeng on 2019/6/10. 6 | // Copyright © 2019年 Tencent. All rights reserved. 7 | // 8 | /** 腾讯云IM Demo自定义气泡视图 9 | * 用于显示聊天气泡中的文本信息数据 10 | * 11 | */ 12 | #import "TUIMessageCell.h" 13 | #import "MyCustomCellData.h" 14 | 15 | NS_ASSUME_NONNULL_BEGIN 16 | 17 | @interface MyCustomCell : TUIMessageCell 18 | @property UILabel *myTextLabel; 19 | @property UILabel *myLinkLabel; 20 | 21 | @property MyCustomCellData *customData; 22 | - (void)fillWithData:(MyCustomCellData *)data; 23 | 24 | @end 25 | 26 | NS_ASSUME_NONNULL_END 27 | -------------------------------------------------------------------------------- /ios/TxImUi/Custom/MyCustomCell.m: -------------------------------------------------------------------------------- 1 | // 2 | // MyCustomCell.m 3 | // TUIKitDemo 4 | // 5 | // Created by annidyfeng on 2019/6/10. 6 | // Copyright © 2019年 Tencent. All rights reserved. 7 | // 8 | /** 腾讯云IM Demo自定义气泡视图 9 | * 用于显示聊天气泡中的文本信息数据 10 | * 11 | */ 12 | #import "MyCustomCell.h" 13 | #import "ReactiveObjC/ReactiveObjC.h" 14 | #import "MMLayout/UIView+MMLayout.h" 15 | #import "UIColor+TUIDarkMode.h" 16 | #import "THeader.h" 17 | 18 | @implementation MyCustomCell 19 | 20 | - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 21 | { 22 | self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 23 | if (self) { 24 | self.container.backgroundColor = [UIColor d_colorWithColorLight:TCell_Nomal dark:TCell_Nomal_Dark]; 25 | 26 | _myTextLabel = [[UILabel alloc] init]; 27 | _myTextLabel.numberOfLines = 0; 28 | _myTextLabel.font = [UIFont systemFontOfSize:15]; 29 | _myTextLabel.textColor = [UIColor d_colorWithColorLight:TText_Color dark:TText_Color_Dark]; 30 | [self.container addSubview:_myTextLabel]; 31 | 32 | _myLinkLabel = [[UILabel alloc] initWithFrame:CGRectZero]; 33 | _myLinkLabel.text = @"查看详情>>"; 34 | _myLinkLabel.font = [UIFont systemFontOfSize:15]; 35 | _myLinkLabel.textColor = [UIColor d_systemBlueColor]; 36 | [self.container addSubview:_myLinkLabel]; 37 | 38 | [self.container.layer setMasksToBounds:YES]; 39 | [self.container.layer setBorderColor:[UIColor d_systemGrayColor].CGColor]; 40 | [self.container.layer setBorderWidth:1]; 41 | [self.container.layer setCornerRadius:5]; 42 | } 43 | return self; 44 | } 45 | 46 | - (void)fillWithData:(MyCustomCellData *)data; 47 | { 48 | [super fillWithData:data]; 49 | self.customData = data; 50 | self.myTextLabel.text = data.text; 51 | } 52 | 53 | - (void)layoutSubviews 54 | { 55 | [super layoutSubviews]; 56 | self.myTextLabel.mm_top(10).mm_left(10).mm_flexToRight(10).mm_flexToBottom(50); 57 | self.myLinkLabel.mm_sizeToFit().mm_left(10).mm_bottom(10); 58 | } 59 | @end 60 | -------------------------------------------------------------------------------- /ios/TxImUi/Custom/MyCustomCellData.h: -------------------------------------------------------------------------------- 1 | // 2 | // MyCustomCellData.h 3 | // TUIKitDemo 4 | // 5 | // Created by annidyfeng on 2019/6/10. 6 | // Copyright © 2019年 Tencent. All rights reserved. 7 | // 8 | /** 腾讯云IM Demo自定义气泡数据 9 | * 用于存储聊天气泡中的文本信息数据 10 | * 11 | */ 12 | #import "TUIMessageCellData.h" 13 | 14 | NS_ASSUME_NONNULL_BEGIN 15 | 16 | @interface MyCustomCellData : TUIMessageCellData 17 | 18 | @property NSString *text; 19 | @property NSString *link; 20 | 21 | @end 22 | 23 | NS_ASSUME_NONNULL_END 24 | -------------------------------------------------------------------------------- /ios/TxImUi/Custom/MyCustomCellData.m: -------------------------------------------------------------------------------- 1 | // 2 | // MyCustomCellData.m 3 | // TUIKitDemo 4 | // 5 | // Created by annidyfeng on 2019/6/10. 6 | // Copyright © 2019年 Tencent. All rights reserved. 7 | // 8 | /** 腾讯云IM Demo自定义气泡数据 9 | * 用于存储聊天气泡中的文本信息数据 10 | * 11 | */ 12 | #import "MyCustomCellData.h" 13 | 14 | @implementation MyCustomCellData 15 | 16 | 17 | - (CGSize)contentSize 18 | { 19 | CGRect rect = [self.text boundingRectWithSize:CGSizeMake(300, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:15] } context:nil]; 20 | CGSize size = CGSizeMake(ceilf(rect.size.width)+1, ceilf(rect.size.height)); 21 | 22 | // 加上气泡边距 23 | size.height += 60; 24 | size.width += 20; 25 | 26 | return size; 27 | } 28 | 29 | @end 30 | -------------------------------------------------------------------------------- /ios/TxImUi/TencentIMConversationModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIViewController+RNTIMModel.h 3 | // fangbossApp 4 | // 5 | // Created by 云超 on 2020/9/24. 6 | // Copyright © 2020 Facebook. All rights reserved. 7 | // 8 | 9 | #import "TUIKit.h" 10 | #import 11 | #import 12 | #import 13 | #import 14 | 15 | @interface TencentIMConversationModel : RCTViewManager 16 | 17 | @end 18 | 19 | -------------------------------------------------------------------------------- /ios/TxImUi/TencentIMConversationModel.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIViewController+RNTIMConversationModel.m 3 | // fangbossApp 4 | // 5 | // Created by 云超 on 2020/9/24. 6 | // Copyright © 2020 Facebook. All rights reserved. 7 | // 8 | 9 | #import "TencentIMConversationModel.h" 10 | #import "TUIKit.h" 11 | #import 12 | #import 13 | #import "TencentIMManager.h" 14 | #import "TUIConversationListController.h" 15 | #import "ConversationView.h" 16 | @implementation TencentIMConversationModel 17 | 18 | RCT_EXPORT_MODULE(); 19 | - (UIView *)view 20 | { 21 | return [[ConversationView alloc] init]; 22 | } 23 | @end 24 | -------------------------------------------------------------------------------- /ios/TxImUi/TencentIMModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIViewController+RNTIMModel.h 3 | // fangbossApp 4 | // 5 | // Created by 云超 on 2020/9/24. 6 | // Copyright © 2020 Facebook. All rights reserved. 7 | // 8 | 9 | #import "TUIKit.h" 10 | #import 11 | #import 12 | #import 13 | #import 14 | 15 | @interface TencentIMModel : NSObject 16 | 17 | @end 18 | 19 | -------------------------------------------------------------------------------- /ios/TxImUi/TencentIMModel.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIViewController+TencentIMModel.m 3 | // fangbossApp 4 | // 5 | // Created by 云超 on 2020/9/24. 6 | // Copyright © 2020 Facebook. All rights reserved. 7 | // 8 | 9 | #import "TencentIMModel.h" 10 | #import "TUIKit.h" 11 | #import 12 | #import 13 | #import "TencentIMManager.h" 14 | 15 | @implementation TencentIMModel 16 | 17 | RCT_EXPORT_MODULE(TencentIMModel); 18 | /** 19 | * 初始化SDK 20 | * @param configFilePath 配置文件路径,默认为mainBundle下的txim.plist 21 | */ 22 | RCT_EXPORT_METHOD(initSdk:(int)sdkAppId) 23 | { 24 | TencentIMManager *tm = [TencentIMManager getInstance]; 25 | TIMSdkConfig *sdkConfig = [TIMSdkConfig new]; 26 | sdkConfig.sdkAppId = sdkAppId; 27 | [tm initSdk:sdkConfig]; 28 | } 29 | 30 | /** 31 | * 用户登录 32 | * @param identify identify 33 | * @param userSig userSig 34 | * @param succ 成功回调 35 | * @param fail 失败回调 36 | */ 37 | RCT_EXPORT_METHOD(login:(NSString *)identify 38 | userSig:(NSString *)userSig 39 | resolver:(RCTPromiseResolveBlock)resolve 40 | rejecter:(RCTPromiseRejectBlock)reject) 41 | { 42 | TencentIMManager *tm = [TencentIMManager getInstance]; 43 | [tm loginWithIdentify:identify 44 | userSig:userSig 45 | succ:^{ 46 | resolve(@{ 47 | @"code": @(0), 48 | @"msg": @"登录成功!", 49 | }); 50 | } 51 | fail:^(int code, NSString *msg) { 52 | reject([NSString stringWithFormat:@"%d", code], msg, nil); 53 | }]; 54 | } 55 | 56 | /** 57 | * 用户登出 58 | * @param succ 成功回调 59 | * @param fail 失败回调 60 | */ 61 | RCT_EXPORT_METHOD(logout:(RCTPromiseResolveBlock)resolve 62 | rejecter:(RCTPromiseRejectBlock)reject){ 63 | TencentIMManager *tm = [TencentIMManager getInstance]; 64 | [tm logoutWithSucc:^{ 65 | resolve(@(YES)); 66 | } fail:^(int code, NSString *msg) { 67 | reject([NSString stringWithFormat:@"%@", @(code)], msg, nil); 68 | }]; 69 | } 70 | 71 | /** 72 | * 开启会话 73 | */ 74 | RCT_EXPORT_METHOD(startChatView: (NSString *)identify 75 | title:(NSString *)title 76 | type:(int)type){ 77 | // NSLog(@"startChat:%@",identify); 78 | TencentIMManager *tm = [TencentIMManager getInstance]; 79 | [tm startChat:identify 80 | title:title 81 | type:type]; 82 | } 83 | 84 | @end 85 | -------------------------------------------------------------------------------- /ios/TxImUi/Util/PAirSandbox.h: -------------------------------------------------------------------------------- 1 | // 2 | // PAirSandbox.h 3 | // AirSandboxDemo 4 | // 5 | // Created by gao feng on 2017/7/18. 6 | // Copyright © 2017年 music4kid. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface PAirSandbox : NSObject 12 | 13 | + (instancetype)sharedInstance; 14 | 15 | - (void)enableSwipe; 16 | - (void)showSandboxBrowser; 17 | 18 | - (void)addAppGroup:(NSString *)groupId; 19 | 20 | @end 21 | 22 | -------------------------------------------------------------------------------- /ios/TxImUi/Util/TCConstants.h: -------------------------------------------------------------------------------- 1 | // 2 | // TCConstants.h 3 | // TCLVBIMDemo 4 | // 5 | // Created by realingzhou on 16/8/22. 6 | // Copyright © 2016年 tencent. All rights reserved. 7 | // 8 | 9 | #ifndef TCConstants_h 10 | #define TCConstants_h 11 | 12 | //Http配置 13 | #define kHttpServerAddr @"https://im-demo.qcloud.com" 14 | 15 | 16 | //********************************************************************** 17 | 18 | #define kHttpTimeout 30 19 | 20 | //错误码 21 | #define kError_InvalidParam -10001 22 | #define kError_ConvertJsonFailed -10002 23 | #define kError_HttpError -10003 24 | 25 | //IMSDK群组相关错误码 26 | #define kError_GroupNotExist 10010 //该群已解散 27 | #define kError_HasBeenGroupMember 10013 //已经是群成员 28 | 29 | //错误信息 30 | #define kErrorMsgNetDisconnected @"网络异常,请检查网络" 31 | 32 | #endif /* TCConstants_h */ 33 | -------------------------------------------------------------------------------- /ios/TxImUi/Util/TCUtil.h: -------------------------------------------------------------------------------- 1 | // 2 | // TCUtil.h 3 | // TCLVBIMDemo 4 | // 5 | // Created by felixlin on 16/8/2. 6 | // Copyright © 2016年 tencent. All rights reserved. 7 | // 8 | /** 腾讯云IM Demo数据处理单元 9 | * 10 | * 本类为Demo客户端提供数据处理服务,以便客户端更好的工作 11 | * 12 | */ 13 | #import 14 | 15 | 16 | 17 | 18 | @interface TCUtil : NSObject 19 | 20 | + (NSData *)dictionary2JsonData:(NSDictionary *)dict; 21 | 22 | + (NSString *)dictionary2JsonStr:(NSDictionary *)dict; 23 | 24 | + (NSDictionary *)jsonSring2Dictionary:(NSString *)jsonString; 25 | 26 | + (NSDictionary *)jsonData2Dictionary:(NSData *)jsonData; 27 | 28 | + (NSString *)getFileCachePath:(NSString *)fileName; 29 | 30 | + (NSUInteger)getContentLength:(NSString*)string; 31 | 32 | + (void)asyncSendHttpRequest:(NSDictionary*)param handler:(void (^)(int resultCode, NSDictionary* resultDict))handler; 33 | + (void)asyncSendHttpRequest:(NSString*)command params:(NSDictionary*)params handler:(void (^)(int resultCode, NSString* message, NSDictionary* resultDict))handler; 34 | + (void)asyncSendHttpRequest:(NSString*)command token:(NSString*)token params:(NSDictionary*)params handler:(void (^)(int resultCode, NSString* message, NSDictionary* resultDict))handler; 35 | 36 | 37 | 38 | @end 39 | 40 | -------------------------------------------------------------------------------- /ios/TxImUi/Util/TencentIMManager.h: -------------------------------------------------------------------------------- 1 | // 2 | // IMManager.h 3 | // RCTTxim 4 | // 5 | // Created by 张建军 on 2019/5/5. 6 | // Copyright © 2019 feewee. All rights reserved. 7 | // 8 | 9 | #import "TUIKit.h" 10 | #import 11 | #import 12 | #import 13 | #import 14 | 15 | NS_ASSUME_NONNULL_BEGIN 16 | 17 | @interface TencentIMManager : NSObject 18 | 19 | /** 20 | * 获取实例 21 | */ 22 | + (instancetype)getInstance; 23 | 24 | /** 25 | * 初始化SDK 26 | * @param configFilePath 配置文件路径,默认为mainBundle下的txim.plist 27 | */ 28 | - (BOOL)initSdk:(TIMSdkConfig *_Nullable)sdkConfig; 29 | 30 | /** 31 | * 用户登录 32 | * @param identify identify 33 | * @param userSig userSig 34 | * @param succ 成功回调 35 | * @param fail 失败回调 36 | */ 37 | - (void)loginWithIdentify:(NSString *)identify 38 | userSig:(NSString *)userSig 39 | succ:(TIMSucc)succ 40 | fail:(TIMFail)fail; 41 | 42 | /** 43 | * 用户登出 44 | * @param succ 成功回调 45 | * @param fail 失败回调 46 | */ 47 | - (void)logoutWithSucc:(TIMSucc)succ fail:(TIMFail)fail; 48 | 49 | /** 50 | * 开启会话 51 | */ 52 | - (void)startChat: (NSString *)identify 53 | title:(NSString *)title 54 | type:(int)type; 55 | 56 | @end 57 | 58 | NS_ASSUME_NONNULL_END 59 | -------------------------------------------------------------------------------- /ios/TxImUi/Util/TencentIMManager.m: -------------------------------------------------------------------------------- 1 | // 2 | // IMManager.m 3 | // RCTTxim 4 | // 5 | // Created by 张建军 on 2019/5/5. 6 | // Copyright © 2019 feewee. All rights reserved. 7 | // 8 | 9 | #import "TencentIMManager.h" 10 | #import "TUIKit.h" 11 | #import 12 | #import 13 | #import "ConversationController.h" 14 | 15 | @implementation TencentIMManager { 16 | /// 是否初始化 17 | BOOL isInit; 18 | /// 应用ID 19 | int sdkAppId; 20 | /// 会话 21 | TIMConversation *conversation; 22 | /// 会话 23 | NSString *currentReceiver; 24 | /// 设备token 25 | NSData *deviceToken; 26 | /// IM配置 27 | NSDictionary *configDict; 28 | } 29 | 30 | 31 | + (instancetype)getInstance { 32 | __strong static TencentIMManager *instance; 33 | static dispatch_once_t onceToken; 34 | dispatch_once(&onceToken, ^{ 35 | instance = [self new]; 36 | }); 37 | return instance; 38 | } 39 | 40 | #pragma clang diagnostic push 41 | #pragma ide diagnostic ignored "ResourceNotFoundInspection" 42 | 43 | - (BOOL)initSdk:(TIMSdkConfig *)sdkConfig { 44 | if (isInit) { 45 | return YES; 46 | } 47 | TIMManager *tm = [TIMManager sharedInstance]; 48 | int sdkAppId = [sdkConfig sdkAppId]; 49 | //新版本不用了 50 | // NSString *accountType = [configDict valueForKey:@"accountType"]; 51 | // if (!accountType) { 52 | // IM_LOG_TAG_ERROR(@"Init", @"未配置accountType"); 53 | // return NO; 54 | // } 55 | // sdkConfig.accountType = accountType; 56 | // 是否crash上报 57 | // id disableCrashReportValue = [configDict valueForKey:@"disableCrashReport"]; 58 | // if (disableCrashReportValue) { 59 | // sdkConfig.disableCrashReportValue = [disableCrashReportValue boolValue]; 60 | // } 61 | // 是否允许log打印 62 | id disableLogPrintValue = [configDict valueForKey:@"disableLogPrint"]; 63 | if (disableLogPrintValue) { 64 | sdkConfig.disableLogPrint = [disableLogPrintValue boolValue]; 65 | } 66 | // Log输出级别, 默认DEBUG等级 67 | id logLevelValue = [configDict valueForKey:@"logLevel"]; 68 | if (logLevelValue) { 69 | sdkConfig.logLevel = (TIMLogLevel) [logLevelValue integerValue]; 70 | } 71 | [[TUIKit sharedInstance] setupWithAppId:sdkAppId]; // SDKAppID 可以在 即时通信 IM 控制台中获取 72 | isInit = YES; 73 | return isInit; 74 | } 75 | 76 | #pragma clang diagnostic pop 77 | 78 | - (void)loginWithIdentify:(NSString *)identify 79 | userSig:(NSString *)userSig 80 | succ:(TIMLoginSucc)succ 81 | fail:(TIMFail)fail { 82 | // 登录参数 83 | TIMLoginParam *loginParam = [TIMLoginParam new]; 84 | loginParam.identifier = identify; 85 | loginParam.userSig = userSig; 86 | loginParam.appidAt3rd = [NSString stringWithFormat:@"%d", sdkAppId]; 87 | TIMManager *tm = [TIMManager sharedInstance]; 88 | void (^login)(void) = ^(void) { 89 | int result = [tm login:loginParam 90 | succ:^{ 91 | [self configAppAPNSDeviceToken]; 92 | succ(); 93 | } fail:fail]; 94 | if (result != 0) { 95 | fail(result, @"调用登录失败"); 96 | } 97 | }; 98 | // 判断是否已经登录 99 | if ([tm getLoginStatus] == TIM_STATUS_LOGINED) { 100 | // 判断是否已经登录了当前账号 101 | if ([[tm getLoginUser] isEqualToString:identify]) { 102 | login(); 103 | } else { 104 | // 登出之前的账号 105 | int result = [tm logout:^{ 106 | login(); 107 | } fail:fail]; 108 | if (result != 0) { 109 | fail(result, @"切换登录失败"); 110 | } 111 | } 112 | } else { 113 | login(); 114 | } 115 | } 116 | 117 | - (void)logoutWithSucc:(TIMLoginSucc)succ fail:(TIMFail)fail { 118 | TIMManager *tm = [TIMManager sharedInstance]; 119 | if ([tm getLoginStatus] == TIM_STATUS_LOGOUT) { 120 | succ(); 121 | } else { 122 | int result = [tm logout:succ fail:fail]; 123 | if (result != 0) { 124 | fail(result, @"调用登出失败"); 125 | } 126 | } 127 | } 128 | 129 | - (void)startChat: (NSString *)identify 130 | title:(NSString *)title 131 | type:(int)type { 132 | TUIConversationCellData *data = [[TUIConversationCellData alloc] init]; 133 | if (type == 2){ 134 | data.groupID = identify; // 如果是群会话,传入对应的群 ID 135 | } else { 136 | data.userID = identify; // 如果是单聊会话,传入对方用户 ID 137 | } 138 | NSLog(@"startChat:%@",identify); 139 | 140 | ConversationController * vc = [ConversationController getInstance]; 141 | [vc pushToChatViewController:data.groupID userID:data.userID title:title]; 142 | 143 | 144 | // dispatch_async(dispatch_get_main_queue(), ^{ 145 | // AppDelegate *delegate = (AppDelegate *)([UIApplication sharedApplication].delegate); 146 | // UIViewController *rootVC = delegate.window.rootViewController; 147 | // ChatViewController *chat = [[ChatViewController alloc] init]; 148 | // chat.conversationData = data; 149 | // [rootVC presentViewController:chat animated:YES completion:nil]; 150 | // }); 151 | 152 | } 153 | 154 | - (void)configDeviceToken:(NSData *)token { 155 | deviceToken = token; 156 | } 157 | 158 | /** 159 | * 配置设备token 160 | */ 161 | - (void)configAppAPNSDeviceToken { 162 | TIMManager *tm = [TIMManager sharedInstance]; 163 | // APNS配置 164 | TIMAPNSConfig *apnsConfig = [TIMAPNSConfig new]; 165 | [apnsConfig setOpenPush:1]; 166 | [tm setAPNS:apnsConfig succ:^{ 167 | // IM_LOG_TAG_INFO(@"APNS", @"APNS配置成功"); 168 | } fail:^(int code, NSString *msg) { 169 | // IM_LOG_TAG_WARN(@"APNS", @"APNS配置失败,错误码:%d,原因:%@", code, msg); 170 | }]; 171 | // NSString *token = [NSString stringWithFormat:@"%@", deviceToken]; 172 | // IM_LOG_TAG_INFO(@"SetToken", @"Token is : %@", token); 173 | TIMTokenParam *param = [TIMTokenParam new]; 174 | #if kAppStoreVersion// AppStore 版本 175 | #if DEBUG 176 | param.busiId = (uint32_t) [[configDict valueForKey:@"debugBusiId"] unsignedIntegerValue]; 177 | #else 178 | param.busiId = (uint32_t) [[configDict valueForKey:@"busiId"] unsignedIntegerValue]; 179 | #endif 180 | #else// 企业证书 ID 181 | param.busiId = (uint32_t) [[configDict valueForKey:@"busiId"] unsignedIntegerValue]; 182 | #endif 183 | [param setToken:deviceToken]; 184 | [tm setToken:param 185 | succ:^{ 186 | // IM_LOG_TAG_INFO(@"SetToken", @"上传token成功"); 187 | } 188 | fail:^(int code, NSString *msg) { 189 | // IM_LOG_TAG_WARN(@"SetToken", @"上传token失败,错误码:%d,原因:%@", code, msg); 190 | }]; 191 | } 192 | 193 | 194 | 195 | 196 | 197 | @end 198 | -------------------------------------------------------------------------------- /ios/TxImUi/model/ConversationView.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIViewController+ConversationView.h 3 | // fangbossApp 4 | // 5 | // Created by 云超 on 2020/9/26. 6 | // Copyright © 2020 Facebook. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | #import "ConversationController.h" 12 | 13 | NS_ASSUME_NONNULL_BEGIN 14 | 15 | @interface ConversationView : UIView 16 | 17 | @property (nonatomic, strong) ConversationController * messageVC; 18 | @end 19 | 20 | NS_ASSUME_NONNULL_END 21 | -------------------------------------------------------------------------------- /ios/TxImUi/model/ConversationView.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIViewController+ConversationView.m 3 | // fangbossApp 4 | // 5 | // Created by 云超 on 2020/9/26. 6 | // Copyright © 2020 Facebook. All rights reserved. 7 | // 8 | 9 | #import "ConversationView.h" 10 | #import 11 | #import "ConversationController.h" 12 | 13 | @implementation ConversationView : UIView 14 | - (instancetype)init { 15 | if (self = [super init]) { 16 | ConversationController * messageVC = [ConversationController getInstance]; 17 | self.messageVC = messageVC; 18 | [self addSubview:messageVC.view]; 19 | } 20 | return self; 21 | } 22 | @end 23 | -------------------------------------------------------------------------------- /ios/TximUi.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /ios/TximUi.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /lib/ConversationView.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { requireNativeComponent } from "react-native"; 3 | 4 | const ConversationModel = requireNativeComponent("TencentIMConversationModel"); 5 | 6 | export default ConversationModel 7 | -------------------------------------------------------------------------------- /lib/TencentIMModel.js: -------------------------------------------------------------------------------- 1 | import { NativeModules } from "react-native"; 2 | 3 | export const TencentIMModel = NativeModules.TencentIMModel; 4 | 5 | let initFlag = false; 6 | let loginFlag = false; 7 | 8 | /** 9 | * 初始化 10 | * @param sdkAppId 11 | */ 12 | export function initSdk(sdkAppId) { 13 | TencentIMModel.initSdk(sdkAppId); 14 | initFlag = true; 15 | } 16 | 17 | /** 18 | * 登录 19 | * @param userId 20 | * @param userSig 21 | * @returns {*|PromiseLike<*>|Promise<*>} 22 | */ 23 | export function login(userId, userSig) { 24 | return TencentIMModel.login(userId, userSig).then(res=> { 25 | loginFlag = true; 26 | return res; 27 | }); 28 | } 29 | 30 | /** 31 | * 登出 32 | * @returns {Promise<*>} 33 | */ 34 | export async function logout() { 35 | return TencentIMModel.logout().then(res=>{ 36 | loginFlag = false; 37 | return res; 38 | }); 39 | } 40 | 41 | /** 42 | * 从其他界面跳转到聊天界面 43 | * @param userId im用户id 44 | * @param conTitle 聊天标题 45 | * @param type: 46 | * 1 = 用户会话 47 | * 2 = 分组会话 48 | */ 49 | export function startChat(userId, conTitle, type = 1) { 50 | if (!loginFlag) { 51 | throw new Error("请先调用登录接口:login(userId, userSig)"); 52 | } 53 | TencentIMModel.startChatView(userId, conTitle, type); 54 | } 55 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-tencent-im-ui", 3 | "title": "React Native Tencent IM With UI ", 4 | "version": "1.1.3", 5 | "description": "腾讯云即时通信 IM 服务的react-native,使用原生ui版本的sdk", 6 | "main": "index.js", 7 | "files": [ 8 | "README.md", 9 | "android", 10 | "index.js", 11 | "ios", 12 | "lib", 13 | "react-native-tencent-im-ui.podspec" 14 | ], 15 | "scripts": { 16 | "test": "echo \"Error: no test specified\" && exit 1", 17 | "npm:publish": "npm --registry https://registry.npmjs.org/ publish", 18 | "npm:unpublish": "npm --registry https://registry.npmjs.org/ unpublish react-native-tencent-im-ui --force", 19 | "npm:sync": "cnpm sync react-native-tencent-im-ui", 20 | "pod:lint": "export LANG=en_US.UTF-8 && pod lib lint react-native-tencent-im-ui.podspec", 21 | "pod:install": "cd ios && export LANG=en_US.UTF-8 && pod install" 22 | }, 23 | "repository": { 24 | "type": "git", 25 | "url": "git+https://github.com/mengyou658/react-native-tencent-im-ui.git", 26 | "baseUrl": "https://github.com/mengyou658/react-native-tencent-im-ui" 27 | }, 28 | "keywords": [ 29 | "react-native", 30 | "txim", 31 | "tencent", 32 | "im", 33 | "chat" 34 | ], 35 | "author": { 36 | "name": "yunchaoq", 37 | "email": "mengyou658@163.com" 38 | }, 39 | "license": "ISC", 40 | "licenseFilename": "LICENSE", 41 | "readmeFilename": "README.md", 42 | "peerDependencies": { 43 | "react": "^16.8.1", 44 | "react-native": ">=0.60.0-rc.0 <1.0.x" 45 | }, 46 | "devDependencies": { 47 | "react": "^16.9.0", 48 | "react-native": "^0.61.5" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /react-native-tencent-im-ui.podspec: -------------------------------------------------------------------------------- 1 | require "json" 2 | 3 | package = JSON.parse(File.read(File.join(__dir__, "package.json"))) 4 | 5 | Pod::Spec.new do |s| 6 | s.name = "react-native-tencent-im-ui" 7 | s.version = package['version'] 8 | s.summary = package['description'] 9 | s.description = package['description'] 10 | s.homepage = package['repository']['baseUrl'] 11 | s.license = package['license'] 12 | s.author = package['author'] 13 | s.source = { :git => package['repository']['url'], :tag => s.version.to_s } 14 | 15 | s.ios.deployment_target = '9.0' 16 | s.source_files = "ios/**/*.{h,c,m,swift}" 17 | s.requires_arc = true 18 | 19 | s.dependency "React" 20 | s.dependency "TXIMSDK_TUIKit_iOS" 21 | end 22 | 23 | --------------------------------------------------------------------------------