├── .gitignore
├── CHANGELOG.md
├── Demo.jpg
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── libs
│ ├── qq_mta-sdk-1.6.2.jar
│ └── qq_sdk_v3.3.0_lite.jar
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── tsy
│ │ └── socialsample
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── tsy
│ │ │ └── socialsample
│ │ │ ├── MainActivity.java
│ │ │ └── WBShareActivity.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── tsy
│ └── socialsample
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── social_sdk
├── .gitignore
├── build.gradle
├── libs
├── qq_mta-sdk-1.6.2.jar
└── qq_sdk_v3.3.0_lite.jar
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── com
│ └── tsy
│ └── sdk
│ └── social
│ └── ApplicationTest.java
├── main
├── AndroidManifest.xml
├── java
│ └── com
│ │ └── tsy
│ │ └── sdk
│ │ └── social
│ │ ├── PlatformConfig.java
│ │ ├── PlatformType.java
│ │ ├── SSOHandler.java
│ │ ├── SocialApi.java
│ │ ├── api
│ │ └── WXApi.java
│ │ ├── listener
│ │ ├── AuthListener.java
│ │ └── ShareListener.java
│ │ ├── qq
│ │ └── QQHandler.java
│ │ ├── share_media
│ │ ├── IShareMedia.java
│ │ ├── ShareImageMedia.java
│ │ ├── ShareMusicMedia.java
│ │ ├── ShareTextImageMedia.java
│ │ ├── ShareTextMedia.java
│ │ ├── ShareVideoMedia.java
│ │ └── ShareWebMedia.java
│ │ ├── sina
│ │ ├── SinaWBHandler.java
│ │ └── WBShareCallbackActivity.java
│ │ ├── util
│ │ ├── BitmapUtils.java
│ │ ├── LogUtils.java
│ │ ├── NetUtils.java
│ │ └── Utils.java
│ │ └── weixin
│ │ ├── WXCallbackActivity.java
│ │ └── WXHandler.java
└── res
│ └── values
│ └── strings.xml
└── test
└── java
└── com
└── tsy
└── sdk
└── social
└── ExampleUnitTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | .idea
5 | .DS_Store
6 | /build
7 | /captures
8 | app2
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Change Log
2 | ==========
3 |
4 | ## Version 2.0.0
5 |
6 | _2018-01-15_
7 |
8 | * 将Library上传至JCenter,并分别上传 full 和 core 版本
9 |
10 | ## Version 1.8.0
11 |
12 | _2018-01-08_
13 |
14 | * 微信更新SDK为1.4.0,采用JCenter引用
15 | * QQ更新SDK为3.3.0
16 |
17 | ## Version 1.7.0
18 |
19 | _2017-04-13_
20 |
21 | * 微博SDK更新至3.2,jcenter引用sdk,修改分享渠道只能为图文分享
22 |
23 | ## Version 1.6.0
24 |
25 | _2017-02-14_
26 |
27 | * 增加混淆规则
28 | * 微博抽出分享回调,简化AndroidManifest的填写和回调设置代码
29 |
30 | ## Version 1.5.5
31 |
32 | _2017-01-04_
33 |
34 | * 微信增加自定义Scope和State
35 | * 微博增加自定义REDIRECT_URL
36 |
37 | ## Version 1.5.4
38 |
39 | _2016-12-15_
40 |
41 | * 修复未安装微信时的空指针异常
42 |
43 | ## Version 1.5.3
44 |
45 | _2016-12-12_
46 |
47 | * 修复微信朋友圈分享回调失败的bug
48 |
49 |
50 | ## Version 1.5.2
51 |
52 | _2016-12-09_
53 |
54 | * 简化微信接入时要创建WXEntryActivity的步骤
55 |
56 |
57 | ## Version 1.4
58 |
59 | _2016-11-13_
60 |
61 | * 增加可选的微信Api调用
62 |
63 |
64 | ## Version 1.3
65 |
66 | _2016-09-18_
67 |
68 | * 集成新浪微博登录授权、分享
69 |
70 |
71 | ## Version 1.2
72 |
73 | _2016-09-06_
74 |
75 | * 将微信appsecret移除,客户端不放appsecret
76 |
77 |
78 | ## Version 1.1
79 |
80 | _2016-08-19_
81 |
82 | * 集成QQ授权登录,QQ分享,QQ空间分享
83 |
84 |
85 | ## Version 1.0
86 |
87 | _2016-08-12_
88 |
89 | * 集成微信授权登录,5种分享媒介,微信会话分享,微信朋友圈分享
--------------------------------------------------------------------------------
/Demo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/Demo.jpg
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SocialSDKAndroid
2 |
3 | [](https://www.apache.org/licenses/LICENSE-2.0)
4 |
5 | > 对第三方社会化sdk的集成和二次封装,比如第三方授权登录、第三方分享等. 欢迎发issue建议新的功能点和渠道集成
6 |
7 | 原文阅读:
8 |
9 | [http://www.jianshu.com/p/4ec1d9c15763](http://www.jianshu.com/p/4ec1d9c15763)
10 |
11 |
12 | ## 0 版本更新记录
13 |
14 | [版本更新记录](https://github.com/tsy12321/SocialSDKAndroid/blob/master/CHANGELOG.md)
15 |
16 | ## 1 引用
17 |
18 | ### 第一种方式:三个平台包全部包含的Library
19 |
20 | 在项目级别的 `build-gradle` 中添加
21 |
22 | ```groovy
23 | allprojects {
24 | repositories {
25 | maven { url "https://dl.bintray.com/thelasterstar/maven" } //微博sdk maven库
26 | }
27 | }
28 | ```
29 |
30 | 在app级别的 `build-gradle` 中添加
31 |
32 | ```groovy
33 | dependencies {
34 | compile 'com.tsy.social:social-sdk-full:2.0.0'
35 | }
36 | ```
37 |
38 | ### 第二种方式:引入核心包,然后自由选择需要的平台SDK
39 |
40 | 在app级别的 `build-gradle` 中添加
41 |
42 | ```groovy
43 | dependencies {
44 | compile 'com.tsy.social:social-sdk-core:2.0.0'
45 | //social sdk 自由选择
46 | //微信sdk
47 | // compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:1.4.0'
48 | //QQ SDK
49 | // compile files('libs/qq_mta-sdk-1.6.2.jar')
50 | // compile files('libs/qq_sdk_v3.3.0_lite.jar')
51 | //微博SDK
52 | // compile 'com.sina.weibo.sdk:core:1.0.0:openDefaultRelease@aar'
53 | }
54 | ```
55 |
56 | 如果使用了微博SDK,需要在项目级别的 `build-gradle` 中添加
57 |
58 | ```groovy
59 | allprojects {
60 | repositories {
61 | maven { url "https://dl.bintray.com/thelasterstar/maven" } //微博sdk maven库
62 | }
63 | }
64 | ```
65 | 这种方式可以减少sdk的体积,需要什么平台就引入哪个平台.更为合理.
66 |
67 | **注意:该方式在sync时可能会报引用错误(如果没有使用微博的SDK),可以忽略**
68 |
69 | ### 1.1 目录介绍
70 |
71 | - app/ Demo代码
72 | - social_sdk/ sdk的开发源码module 开发完成后用gradle中makejar打成jar包
73 | - qq_sdk/ qq sdk
74 |
75 | ### 1.2 Demo介绍
76 |
77 | 替换Demo中的MainActivity中的qq appid、wx appid、weibo appkey为自己的
78 |
79 | ```java
80 | public class MainActivity extends AppCompatActivity implements IWeiboHandler.Response{
81 |
82 | ...
83 |
84 | private static final String WX_APPID = "your wx appid"; //申请的wx appid
85 | private static final String QQ_APPID = "your qq appid"; //申请的qq appid
86 | private static final String SINA_WB_APPKEY = "your sina wb appkey"; //申请的新浪微博 appkey
87 |
88 | ...
89 | }
90 | ```
91 |
92 | 替换AndroidManifest中的qq appid为自己的
93 |
94 | ```java
95 |
96 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 | ```
108 |
109 | 替换builde.gradle文件中的签名为自己的app签名。
110 |
111 | 修改 `build.gradle` 中的 `applicationID` 和 项目的 `PackageName` (右键IDE的项目树,修改包名)
112 |
113 | 修改完上面4个地方后即可跑通Demo。如下
114 |
115 | 
116 |
117 | ## 2 功能介绍
118 |
119 | ### 2.1 授权登录
120 |
121 | 1. 微信授权登录
122 | 2. QQ授权登录
123 | 3. 新浪微博授权登录
124 |
125 | ### 2.2 分享
126 |
127 | #### 2.2.1 分享媒介
128 |
129 | 1. 文字
130 | 1. 图片
131 | 1. 音乐
132 | 1. 视频
133 | 1. 网页
134 |
135 | #### 2.2.2 分享平台
136 |
137 | 1. 微信会话分享
138 | 1. 微信朋友圈分享
139 | 1. QQ分享
140 | 1. QQ空间分享
141 | 1. 新浪微博分享
142 |
143 | ### 2.3 API调用
144 |
145 | SDK中封装了部分API,比如当第三方授权成功后获取到access_token,会提供一些API查询用户信息,刷新access_token等。
146 |
147 | **!注意:由于调用这些API会用到appsecret,所以一般不建议放到客户端做**
148 |
149 | 具体API见底附录。
150 |
151 |
152 | ## 3 开发说明
153 |
154 | ### 3.1 准备
155 |
156 | AndroidManifest加上以下基本的权限(之后各个平台会注册一些不同的信息后面会说明)
157 |
158 | ```xml
159 |
160 |
161 |
162 |
163 |
164 | ```
165 |
166 | ### 3.2 配置平台信息
167 |
168 | 在项目入口(或者在调用前)需要配置平台的信息,配置一次即可.
169 |
170 | ```java
171 | PlatformConfig.setWeixin(WX_APPID);
172 | PlatformConfig.setQQ(QQ_APPID);
173 | PlatformConfig.setSinaWB(SINA_WB_APPKEY);
174 | ```
175 |
176 | ### 3.3 接口使用说明
177 |
178 | 调用方式使用api调用登录或者分享接口,在参数中区别平台,实现回调接收成功、取消或者失败的结果.
179 |
180 | 示例如下:(某些平台会有一些特殊处理后面会在平台中说明)
181 |
182 | 初始化api:
183 |
184 | ```java
185 | SocialApi mSocialApi = SocialApi.get(getApplicationContext());
186 | ```
187 |
188 | 登录授权:
189 | ```java
190 | mSocialApi.doOauthVerify(this, PlatformType.WEIXIN, new AuthListener() {
191 | @Override
192 | public void onComplete(PlatformType platform_type, Map map) {
193 | Log.i("tsy", "oncomplete:" + map);
194 | }
195 |
196 | @Override
197 | public void onError(PlatformType platform_type, String err_msg) {
198 | Log.i("tsy", "onError:" + err_msg);
199 | }
200 |
201 | @Override
202 | public void onCancel(PlatformType platform_type) {
203 | Log.i("tsy", "onCancel");
204 | }
205 | });
206 | ```
207 |
208 | 分享:
209 | ```java
210 |
211 | //分享媒介 后面有详细介绍
212 | ShareWebMedia shareMedia = new ShareWebMedia();
213 | shareMedia.setTitle("分享网页测试");
214 | shareMedia.setDescription("分享网页测试");
215 | shareMedia.setWebPageUrl("http://www.baidu.com");
216 | shareMedia.setThumb(BitmapUtils.readBitMap(getApplicationContext(), R.mipmap.ic_launcher));
217 |
218 | mSocialApi.doShare(this, PlatformType.WEIXIN, shareMedia, new ShareListener() {
219 | @Override
220 | public void onComplete(PlatformType platform_type) {
221 | Log.i("tsy", "share onComplete");
222 | }
223 |
224 | @Override
225 | public void onError(PlatformType platform_type, String err_msg) {
226 | Log.i("tsy", "share onError:" + err_msg);
227 | }
228 |
229 | @Override
230 | public void onCancel(PlatformType platform_type) {
231 | Log.i("tsy", "share onCancel");
232 | }
233 | });
234 |
235 | ```
236 |
237 | ### 3.4 分享媒介
238 |
239 | 现在集成了文字分享,图片分享,音乐分享,视频分享,网页分享5种分享媒介.不同的平台可能只有其中某几种.
240 |
241 | #### 3.4.1 文字分享
242 |
243 | ```java
244 | ShareTextMedia shareMedia = new ShareTextMedia();
245 | shareMedia.setText("分享文字测试");
246 | ```
247 | #### 3.4.2 图片分享
248 |
249 | ```java
250 | ShareImageMedia shareMedia = new ShareImageMedia();
251 | shareMedia.setImage(BitmapUtils.readBitMap(getApplicationContext(), R.mipmap.ic_launcher));
252 | ```
253 |
254 | #### 3.4.3 音乐分享
255 |
256 | ```java
257 | ShareMusicMedia shareMedia = new ShareMusicMedia();
258 | shareMedia.setTitle("分享音乐测试");
259 | shareMedia.setDescription("分享音乐测试");
260 | shareMedia.setMusicUrl("http://idg-tangsiyuan.tunnel.nibaguai.com/splash/music.mp3");
261 | shareMedia.setThumb(BitmapUtils.readBitMap(getApplicationContext(), R.mipmap.ic_launcher));
262 | ```
263 |
264 | #### 3.4.4 视频分享
265 |
266 | ```java
267 | ShareVideoMedia shareMedia = new ShareVideoMedia();
268 | shareMedia.setTitle("分享视频测试");
269 | shareMedia.setDescription("分享视频测试");
270 | shareMedia.setVideoUrl("http://idg-tangsiyuan.tunnel.nibaguai.com/splash/music.mp3");
271 | shareMedia.setThumb(BitmapUtils.readBitMap(getApplicationContext(), R.mipmap.ic_launcher));
272 | ```
273 |
274 | #### 3.4.5 网页分享
275 |
276 | ```java
277 | ShareWebMedia shareMedia = new ShareWebMedia();
278 | shareMedia.setTitle("分享网页测试");
279 | shareMedia.setDescription("分享网页测试");
280 | shareMedia.setWebPageUrl("http://www.baidu.com");
281 | shareMedia.setThumb(BitmapUtils.readBitMap(getApplicationContext(), R.mipmap.ic_launcher));
282 | ```
283 |
284 | ## 4 第三方平台接入
285 |
286 | ### 4.1 微信
287 |
288 | #### 4.1.1 集成sdk
289 |
290 | ```
291 | compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:1.4.0'
292 | ```
293 |
294 | #### 4.1.2 配置
295 |
296 | AndroidManifest中添加:
297 |
298 | ```java
299 |
305 |
309 | ```
310 |
311 | #### 4.1.3 常量定义
312 |
313 | 设置配置信息:
314 |
315 | ```java
316 | PlatformConfig.setWeixin(WX_APPID);
317 | ```
318 |
319 | PlatformType:
320 |
321 | 微信:PlatformType.WEIXIN(可用于登录和微信回话分享)
322 |
323 | 朋友圈:PlatformType.WEIXIN_CIRCLE(用于微信朋友圈分享)
324 |
325 |
326 | #### 4.1.4 自定义scope state
327 |
328 | 可以通过接口setScopeState修改 scope 和 state。
329 |
330 | 默认scope是 "snsapi_userinfo,snsapi_friend,snsapi_message"
331 | 默认state是 "none"
332 |
333 | ```java
334 | WXHandler.setScopeState("your scope", "your state");
335 | ```
336 |
337 | #### 4.1.5 注意
338 |
339 | 使用微信登录分享需要签名打包,并且签名和包名要和微信平台填入的信息一致。
340 |
341 |
342 | ### 4.2 QQ
343 |
344 | #### 4.2.1 集成sdk
345 |
346 | 将目录中的qq_mta-sdk-1.6.2.jar和qq_sdk_v3.3.0_lite.jar放入项目.
347 |
348 | #### 4.2.2 配置
349 |
350 | AndroidManifest中添加:
351 |
352 | ```java
353 |
354 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
369 | ```
370 |
371 | #### 4.2.3 常量定义
372 |
373 | 设置配置信息:
374 |
375 | ```java
376 | PlatformConfig.setQQ(QQ_APPID);
377 | ```
378 |
379 | PlatformType:
380 |
381 | 微信:PlatformType.QQ(可用于登录和QQ分享)
382 |
383 | 朋友圈:PlatformType.QZONE(用于qq控件分享)
384 |
385 | #### 4.2.4 注意
386 |
387 | 使用QQ登录需要签名打包,并且签名和包名要和QQ开放平台填入的信息一致。
388 |
389 | #### 4.2.5 回调设置
390 |
391 | 要在onActivityResult添加以下
392 |
393 | ```java
394 | @Override
395 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
396 | super.onActivityResult(requestCode, resultCode, data);
397 |
398 | mSocialApi.onActivityResult(requestCode, resultCode, data);
399 | }
400 | ```
401 |
402 | ### 4.3 新浪微博
403 |
404 | #### 4.3.1 集成sdk
405 |
406 | 在项目根目录的build.gradle中增加中央仓库
407 |
408 | ```
409 | maven { url "https://dl.bintray.com/thelasterstar/maven/" }
410 | ```
411 |
412 | 在需要引入SDK的module目录的build.gradle中引入sdk-core依赖
413 |
414 | ```
415 | compile 'com.sina.weibo.sdk:core:1.0.0:openDefaultRelease@aar'
416 | ```
417 |
418 | #### 4.3.2 配置
419 |
420 | 创建文件 `WBShareActivity` 继承 `WBShareCallbackActivity`
421 |
422 | ```java
423 | public class WBShareActivity extends WBShareCallbackActivity {
424 | }
425 | ```
426 |
427 | AndroidManifest中添加:
428 |
429 | ```java
430 |
431 |
436 |
440 |
441 |
442 |
443 |
444 |
445 | ```
446 |
447 | #### 4.3.3 回调设置
448 |
449 | 要在onActivityResult添加以下(如果qq已经添加则不需要重复添加)
450 |
451 | ```java
452 | @Override
453 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
454 | super.onActivityResult(requestCode, resultCode, data);
455 |
456 | mSocialApi.onActivityResult(requestCode, resultCode, data);
457 | }
458 | ```
459 |
460 | #### 4.3.4 常量定义
461 |
462 | 设置配置信息:
463 |
464 | ```java
465 | PlatformConfig.setSinaWB(SINA_WB_APPKEY);
466 | ```
467 |
468 | #### 4.3.5 自定义REDIRECT_URL
469 |
470 | 可以通过接口setRedirctUrl修改 REDIRECT_URL
471 |
472 | 默认REDIRECT_URL是 "https://api.weibo.com/oauth2/default.html"
473 |
474 | ```java
475 | SinaWBHandler.setRedirctUrl("your RedirctUrl");
476 | ```
477 |
478 | #### 4.3.6 注意
479 |
480 | 使用新浪登录分享需要签名打包,并且签名和包名要和新浪平台填入的信息一致。
481 |
482 | 并且微博开放平台的回调地址(REDIRECT_URL)要和代码中的REDIRECT_URL一致
483 |
484 | ## 附录
485 |
486 | ### API列表
487 |
488 | #### 1 微信API (WXApi)
489 |
490 | 1. 获取access_token
491 |
492 | ```java
493 | /**
494 | * 获取access_token
495 | * @param wxAppId wx appid
496 | * @param wxAppSecret wx appsecret
497 | * @param code 调用微信登录获取的code
498 | * @param callback
499 | */
500 | ```
501 | getAccessToken(String wxAppId, String wxAppSecret,
502 | String code,
503 | final Callback callback)
504 |
505 | 1. 获取用户信息
506 |
507 | ```java
508 | /**
509 | * 获取用户信息
510 | * @param openid openid
511 | * @param access_token access_token
512 | * @param callback
513 | */
514 | ```
515 | getUserInfo(String openid, String access_token,
516 | final Callback callback)
517 |
518 | ## 混淆
519 |
520 | ```
521 | #social
522 | -dontwarn com.tsy.sdk.social.**
523 | -keep class com.tsy.sdk.social.**{*;}
524 |
525 | #qq & weixin
526 | -dontwarn com.tencent.**
527 | -keep class com.tencent.** {*;}
528 |
529 | #sina
530 | -dontwarn com.sina.**
531 | -keep class com.sina.** {*;}
532 | ```
533 |
534 | ## About Me
535 | 简书地址:http://www.jianshu.com/users/21716b19302d/latest_articles
536 |
537 | 微信公众号
538 |
539 | 
540 |
541 | License
542 | -------
543 |
544 | Copyright 2017 SY.Tang
545 |
546 | Licensed under the Apache License, Version 2.0 (the "License");
547 | you may not use this file except in compliance with the License.
548 | You may obtain a copy of the License at
549 |
550 | http://www.apache.org/licenses/LICENSE-2.0
551 |
552 | Unless required by applicable law or agreed to in writing, software
553 | distributed under the License is distributed on an "AS IS" BASIS,
554 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
555 | See the License for the specific language governing permissions and
556 | limitations under the License.
557 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 24
5 | buildToolsVersion "24.0.3"
6 |
7 | defaultConfig {
8 | applicationId "com.tsy.socialsample"
9 | minSdkVersion 14
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 |
15 | // signingConfigs {
16 | // release {
17 | // storeFile file("your sign file")
18 | // storePassword "your password"
19 | // keyAlias "your keyAlias"
20 | // keyPassword "your keyPassword"
21 | // }
22 | // }
23 | //
24 | // buildTypes {
25 | // debug {
26 | // signingConfig signingConfigs.release
27 | // }
28 | // release {
29 | // minifyEnabled false
30 | // proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
31 | // }
32 | // }
33 | }
34 |
35 | buildscript {
36 | repositories {
37 | mavenCentral()
38 | }
39 | dependencies {
40 | classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
41 | }
42 | }
43 |
44 | apply plugin: 'com.neenbedankt.android-apt'
45 |
46 | dependencies {
47 | testCompile 'junit:junit:4.12'
48 | compile 'com.android.support:appcompat-v7:24.2.1'
49 | //ButterKnife
50 | compile 'com.jakewharton:butterknife:8.2.1'
51 | apt 'com.jakewharton:butterknife-compiler:8.2.1'
52 | compile 'pub.devrel:easypermissions:1.0.1'
53 |
54 | compile 'com.tsy.social:social-sdk-full:2.0.0'
55 | // compile 'com.tsy.social:social-sdk-core:2.0.0'
56 | // compile project(':social_sdk')
57 | //social sdk
58 | // compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:1.4.0'
59 | // compile files('libs/qq_mta-sdk-1.6.2.jar')
60 | // compile files('libs/qq_sdk_v3.3.0_lite.jar')
61 | // compile 'com.sina.weibo.sdk:core:1.0.0:openDefaultRelease@aar'
62 | }
63 |
64 |
--------------------------------------------------------------------------------
/app/libs/qq_mta-sdk-1.6.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/app/libs/qq_mta-sdk-1.6.2.jar
--------------------------------------------------------------------------------
/app/libs/qq_sdk_v3.3.0_lite.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/app/libs/qq_sdk_v3.3.0_lite.jar
--------------------------------------------------------------------------------
/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 /Users/tsy/Library/Android/sdk/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 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/tsy/socialsample/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.tsy.socialsample;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
31 |
35 |
36 |
37 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
52 |
53 |
54 |
59 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tsy/socialsample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.tsy.socialsample;
2 |
3 | import android.Manifest;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.graphics.Bitmap;
7 | import android.graphics.BitmapFactory;
8 | import android.os.Bundle;
9 | import android.support.v7.app.AppCompatActivity;
10 | import android.util.Log;
11 | import android.widget.RadioGroup;
12 | import android.widget.Toast;
13 |
14 | import com.tsy.sdk.social.PlatformConfig;
15 | import com.tsy.sdk.social.PlatformType;
16 | import com.tsy.sdk.social.SocialApi;
17 | import com.tsy.sdk.social.listener.AuthListener;
18 | import com.tsy.sdk.social.listener.ShareListener;
19 | import com.tsy.sdk.social.share_media.IShareMedia;
20 | import com.tsy.sdk.social.share_media.ShareImageMedia;
21 | import com.tsy.sdk.social.share_media.ShareMusicMedia;
22 | import com.tsy.sdk.social.share_media.ShareTextImageMedia;
23 | import com.tsy.sdk.social.share_media.ShareTextMedia;
24 | import com.tsy.sdk.social.share_media.ShareVideoMedia;
25 | import com.tsy.sdk.social.share_media.ShareWebMedia;
26 |
27 | import java.io.InputStream;
28 | import java.util.List;
29 | import java.util.Map;
30 |
31 | import butterknife.BindView;
32 | import butterknife.ButterKnife;
33 | import butterknife.OnClick;
34 | import pub.devrel.easypermissions.EasyPermissions;
35 |
36 | public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
37 |
38 | private static final int REQUEST_LOCATION = 1;
39 | @BindView(R.id.radioGShareMedia)
40 | RadioGroup radioGShareMedia;
41 |
42 | @BindView(R.id.radioGSharePlatform)
43 | RadioGroup radioGSharePlatform;
44 |
45 | private static final String WX_APPID = "your wx appid"; //申请的wx appid
46 | private static final String QQ_APPID = "your qq appid"; //申请的qq appid
47 | private static final String SINA_WB_APPKEY = "your sina wb appkey"; //申请的新浪微博 appkey
48 |
49 | private SocialApi mSocialApi;
50 |
51 | @Override
52 | protected void onCreate(Bundle savedInstanceState) {
53 | super.onCreate(savedInstanceState);
54 | setContentView(R.layout.activity_main);
55 | ButterKnife.bind(this);
56 |
57 | PlatformConfig.setWeixin(WX_APPID);
58 | PlatformConfig.setQQ(QQ_APPID);
59 | PlatformConfig.setSinaWB(SINA_WB_APPKEY);
60 |
61 | mSocialApi = SocialApi.get(getApplicationContext());
62 | }
63 |
64 | /**
65 | * 微信登录
66 | */
67 | @OnClick(R.id.btnWXLogin)
68 | public void onWXLogin() {
69 | mSocialApi.doOauthVerify(this, PlatformType.WEIXIN , new MyAuthListener());
70 | }
71 |
72 | /**
73 | * qq登录
74 | */
75 | @OnClick(R.id.btnQQLogin)
76 | public void onQQLogin() {
77 | mSocialApi.doOauthVerify(this, PlatformType.QQ, new MyAuthListener());
78 | }
79 |
80 | /**
81 | * 新浪微博登录
82 | */
83 | @OnClick(R.id.btnSinaWBLogin)
84 | public void onSinaWBLogin() {
85 | mSocialApi.doOauthVerify(this, PlatformType.SINA_WB, new MyAuthListener());
86 | }
87 |
88 | @Override
89 | protected void onResume() {
90 | super.onResume();
91 |
92 | //申请权限
93 | String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
94 | if (!EasyPermissions.hasPermissions(this, perms)) {
95 | EasyPermissions.requestPermissions(this, "need access external storage", REQUEST_LOCATION, perms);
96 | }
97 | }
98 |
99 | @Override
100 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
101 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
102 | EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
103 | }
104 |
105 | @Override
106 | public void onPermissionsGranted(int requestCode, List perms) {
107 |
108 | }
109 |
110 | @Override
111 | public void onPermissionsDenied(int requestCode, List perms) {
112 | if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
113 | Toast.makeText(getApplicationContext(), "前往设置开启访问存储空间权限", Toast.LENGTH_SHORT).show();
114 | finish();
115 | }
116 | }
117 |
118 | public class MyAuthListener implements AuthListener {
119 | @Override
120 | public void onComplete(PlatformType platform_type, Map map) {
121 | Toast.makeText(MainActivity.this, platform_type + " login onComplete", Toast.LENGTH_SHORT).show();
122 | Log.i("tsy", "login onComplete:" + map);
123 | }
124 |
125 | @Override
126 | public void onError(PlatformType platform_type, String err_msg) {
127 | Toast.makeText(MainActivity.this, platform_type + " login onError:" + err_msg, Toast.LENGTH_SHORT).show();
128 | Log.i("tsy", "login onError:" + err_msg);
129 | }
130 |
131 | @Override
132 | public void onCancel(PlatformType platform_type) {
133 | Toast.makeText(MainActivity.this, platform_type + " login onCancel", Toast.LENGTH_SHORT).show();
134 | Log.i("tsy", "login onCancel");
135 | }
136 | }
137 |
138 | @OnClick(R.id.btnShare)
139 | public void onShare() {
140 | //获取分享类型
141 | IShareMedia shareMedia;
142 | switch (radioGShareMedia.getCheckedRadioButtonId()) {
143 | case R.id.radioShareText:
144 | shareMedia = new ShareTextMedia();
145 | ((ShareTextMedia)shareMedia).setText("分享文字测试");
146 | break;
147 |
148 | case R.id.radioShareImage:
149 | shareMedia = new ShareImageMedia();
150 | ((ShareImageMedia)shareMedia).setImage(readBitMap(getApplicationContext(), R.mipmap.ic_launcher));
151 | break;
152 |
153 | case R.id.radioShareTextImage:
154 | shareMedia = new ShareTextImageMedia();
155 | ((ShareTextImageMedia)shareMedia).setText("分享文字测试");
156 | ((ShareTextImageMedia)shareMedia).setImage(readBitMap(getApplicationContext(), R.mipmap.ic_launcher));
157 | break;
158 |
159 | case R.id.radioShareMusic:
160 | shareMedia = new ShareMusicMedia();
161 | ((ShareMusicMedia)shareMedia).setTitle("分享音乐测试");
162 | ((ShareMusicMedia)shareMedia).setDescription("分享音乐测试");
163 | ((ShareMusicMedia)shareMedia).setMusicUrl("http://tsy.tunnel.nibaguai.com/splash/music.mp3");
164 | ((ShareMusicMedia)shareMedia).setThumb(readBitMap(getApplicationContext(), R.mipmap.ic_launcher));
165 | break;
166 |
167 | case R.id.radioShareVideo:
168 | shareMedia = new ShareVideoMedia();
169 | ((ShareVideoMedia)shareMedia).setTitle("分享视频测试");
170 | ((ShareVideoMedia)shareMedia).setDescription("分享视频测试");
171 | ((ShareVideoMedia)shareMedia).setVideoUrl("http://tsy.tunnel.nibaguai.com/splash/music.mp3");
172 | ((ShareVideoMedia)shareMedia).setThumb(readBitMap(getApplicationContext(), R.mipmap.ic_launcher));
173 | break;
174 |
175 | case R.id.radioShareWeb:
176 | shareMedia = new ShareWebMedia();
177 | ((ShareWebMedia)shareMedia).setTitle("分享网页测试");
178 | ((ShareWebMedia)shareMedia).setDescription("分享网页测试");
179 | ((ShareWebMedia)shareMedia).setWebPageUrl("http://www.baidu.com");
180 | ((ShareWebMedia)shareMedia).setThumb(readBitMap(getApplicationContext(), R.mipmap.ic_launcher));
181 | break;
182 |
183 | default:
184 | return;
185 | }
186 |
187 | //分享渠道
188 | switch (radioGSharePlatform.getCheckedRadioButtonId()) {
189 | case R.id.radioShareWX:
190 | mSocialApi.doShare(this, PlatformType.WEIXIN, shareMedia, new MyShareListener());
191 | break;
192 |
193 | case R.id.radioShareWXCircle:
194 | mSocialApi.doShare(this, PlatformType.WEIXIN_CIRCLE, shareMedia, new MyShareListener());
195 | break;
196 |
197 | case R.id.radioShareQQ:
198 | mSocialApi.doShare(this, PlatformType.QQ, shareMedia, new MyShareListener());
199 | break;
200 |
201 | case R.id.radioShareQZone:
202 | mSocialApi.doShare(this, PlatformType.QZONE, shareMedia, new MyShareListener());
203 | break;
204 |
205 | case R.id.radioShareSinaWB:
206 | mSocialApi.doShare(this, PlatformType.SINA_WB, shareMedia, new MyShareListener());
207 | break;
208 |
209 | default:
210 | return;
211 | }
212 | }
213 |
214 | public class MyShareListener implements ShareListener {
215 |
216 | @Override
217 | public void onComplete(PlatformType platform_type) {
218 | Toast.makeText(MainActivity.this, platform_type + " share onComplete", Toast.LENGTH_SHORT).show();
219 | }
220 |
221 | @Override
222 | public void onError(PlatformType platform_type, String err_msg) {
223 | Toast.makeText(MainActivity.this, platform_type + " share onError:" + err_msg, Toast.LENGTH_SHORT).show();
224 | }
225 |
226 | @Override
227 | public void onCancel(PlatformType platform_type) {
228 | Toast.makeText(MainActivity.this, platform_type + " share onCancel", Toast.LENGTH_SHORT).show();
229 | }
230 | }
231 |
232 | @Override
233 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
234 | mSocialApi.onActivityResult(requestCode, resultCode, data);
235 | }
236 |
237 | private Bitmap readBitMap(Context context, int resId) {
238 | BitmapFactory.Options opt = new BitmapFactory.Options();
239 | opt.inPreferredConfig = Bitmap.Config.RGB_565;
240 | opt.inPurgeable = true;
241 | opt.inInputShareable = true;
242 | InputStream is = context.getResources().openRawResource(resId);
243 | return BitmapFactory.decodeStream(is, null, opt);
244 | }
245 | }
246 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tsy/socialsample/WBShareActivity.java:
--------------------------------------------------------------------------------
1 | package com.tsy.socialsample;
2 |
3 | import com.tsy.sdk.social.sina.WBShareCallbackActivity;
4 |
5 | /**
6 | * Created by tsy on 2017/2/14.
7 | */
8 |
9 | public class WBShareActivity extends WBShareCallbackActivity {
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
14 |
15 |
19 |
20 |
26 |
27 |
35 |
36 |
44 |
45 |
46 |
54 |
55 |
62 |
63 |
67 |
68 |
73 |
74 |
82 |
83 |
90 |
95 |
99 |
103 |
107 |
111 |
115 |
116 |
117 |
118 |
123 |
131 |
132 |
139 |
144 |
148 |
152 |
156 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
174 |
175 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SocialSDKSample
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/tsy/socialsample/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.tsy.socialsample;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.2.3'
9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
10 | classpath 'com.novoda:bintray-release:0.4.0'
11 | }
12 | }
13 |
14 | allprojects {
15 | repositories {
16 | jcenter()
17 | maven { url "https://dl.bintray.com/thelasterstar/maven" }
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Oct 20 14:30:25 CST 2016
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':social_sdk'
2 |
--------------------------------------------------------------------------------
/social_sdk/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | .idea
3 | *.iml
4 |
--------------------------------------------------------------------------------
/social_sdk/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'maven-publish'
3 | apply plugin: 'com.novoda.bintray-release'
4 |
5 | Properties properties = new Properties()
6 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
7 |
8 | android {
9 | compileSdkVersion 24
10 | buildToolsVersion "24.0.3"
11 |
12 | defaultConfig {
13 | minSdkVersion 14
14 | targetSdkVersion 23
15 | versionCode 1
16 | versionName "1.0"
17 | }
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 | }
25 |
26 | dependencies {
27 | testCompile 'junit:junit:4.12'
28 | compile 'com.android.support:appcompat-v7:24.2.1'
29 | compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:1.4.0'
30 | compile files('libs/qq_sdk_v3.3.0_lite.jar')
31 | compile files('libs/qq_mta-sdk-1.6.2.jar')
32 | compile 'com.sina.weibo.sdk:core:1.0.0:openDefaultRelease@aar'
33 | }
34 |
35 | tasks.withType(Javadoc) {
36 | options.addStringOption('Xdoclint:none', '-quiet')
37 | options.addStringOption('encoding', 'UTF-8')
38 | options.addStringOption('charSet', 'UTF-8')
39 | }
40 |
41 | publish {
42 | userOrg = 'tangsiyuan'
43 | groupId = 'com.tsy.social'
44 | artifactId = 'social-sdk-full'
45 | publishVersion = '2.0.0'
46 | desc = '对微信、QQ、微博第三方分享登录的封装'
47 | website = 'https://github.com/tsy12321/SocialSDKAndroid'
48 | dryRun = false
49 | bintrayUser = properties.getProperty('bintrayUser');
50 | bintrayKey = properties.getProperty('bintrayKey');
51 | }
--------------------------------------------------------------------------------
/social_sdk/libs/qq_mta-sdk-1.6.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/social_sdk/libs/qq_mta-sdk-1.6.2.jar
--------------------------------------------------------------------------------
/social_sdk/libs/qq_sdk_v3.3.0_lite.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsy12321/SocialSDKAndroid/cb22aefdc04241df93c2c20896f4a583fe43b57a/social_sdk/libs/qq_sdk_v3.3.0_lite.jar
--------------------------------------------------------------------------------
/social_sdk/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 /Users/tsy/Library/Android/sdk/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 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/social_sdk/src/androidTest/java/com/tsy/sdk/social/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/social_sdk/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/PlatformConfig.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * 第三方平台配置信息存储
8 | * Created by tsy on 16/8/4.
9 | */
10 | public class PlatformConfig {
11 |
12 | public static Map configs = new HashMap();
13 |
14 | static {
15 | configs.put(PlatformType.WEIXIN, new PlatformConfig.Weixin(PlatformType.WEIXIN));
16 | configs.put(PlatformType.WEIXIN_CIRCLE, new PlatformConfig.Weixin(PlatformType.WEIXIN_CIRCLE));
17 | configs.put(PlatformType.QQ, new PlatformConfig.QQ(PlatformType.QQ));
18 | configs.put(PlatformType.QZONE, new PlatformConfig.QQ(PlatformType.QZONE));
19 | configs.put(PlatformType.SINA_WB, new PlatformConfig.SinaWB(PlatformType.SINA_WB));
20 | }
21 |
22 | public interface Platform {
23 | PlatformType getName();
24 | }
25 |
26 | //微信
27 | public static class Weixin implements PlatformConfig.Platform {
28 | private final PlatformType media;
29 | public String appId = null;
30 |
31 | public PlatformType getName() {
32 | return this.media;
33 | }
34 |
35 | public Weixin(PlatformType type) {
36 | this.media = type;
37 | }
38 | }
39 |
40 | /**
41 | * 设置微信配置信息
42 | * @param appId
43 | */
44 | public static void setWeixin(String appId) {
45 | PlatformConfig.Weixin weixin = (PlatformConfig.Weixin)configs.get(PlatformType.WEIXIN);
46 | weixin.appId = appId;
47 |
48 | PlatformConfig.Weixin weixin_circle = (PlatformConfig.Weixin)configs.get(PlatformType.WEIXIN_CIRCLE);
49 | weixin_circle.appId = appId;
50 | }
51 |
52 | //qq
53 | public static class QQ implements PlatformConfig.Platform {
54 | private final PlatformType media;
55 | public String appId = null;
56 |
57 | public PlatformType getName() {
58 | return this.media;
59 | }
60 |
61 | public QQ(PlatformType type) {
62 | this.media = type;
63 | }
64 | }
65 |
66 | /**
67 | * 设置qq配置信息
68 | * @param appId
69 | */
70 | public static void setQQ(String appId) {
71 | PlatformConfig.QQ qq = (PlatformConfig.QQ)configs.get(PlatformType.QQ);
72 | qq.appId = appId;
73 |
74 | PlatformConfig.QQ qzone = (PlatformConfig.QQ)configs.get(PlatformType.QZONE);
75 | qzone.appId = appId;
76 | }
77 |
78 | //qq
79 | public static class SinaWB implements PlatformConfig.Platform {
80 | private final PlatformType media;
81 | public String appKey = null;
82 |
83 | public PlatformType getName() {
84 | return this.media;
85 | }
86 |
87 | public SinaWB(PlatformType type) {
88 | this.media = type;
89 | }
90 | }
91 |
92 | /**
93 | * 设置新浪微博配置信息
94 | * @param appKey
95 | */
96 | public static void setSinaWB(String appKey) {
97 | PlatformConfig.SinaWB sinaWB = (PlatformConfig.SinaWB)configs.get(PlatformType.SINA_WB);
98 | sinaWB.appKey = appKey;
99 | }
100 |
101 | public static Platform getPlatformConfig(PlatformType platformType) {
102 | return configs.get(platformType);
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/PlatformType.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social;
2 |
3 | /**
4 | * Created by tsy on 16/8/4.
5 | */
6 | public enum PlatformType {
7 | WEIXIN,
8 | WEIXIN_CIRCLE,
9 | QQ,
10 | QZONE,
11 | SINA_WB;
12 | }
13 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/SSOHandler.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 |
7 | import com.tsy.sdk.social.listener.AuthListener;
8 | import com.tsy.sdk.social.listener.ShareListener;
9 | import com.tsy.sdk.social.share_media.IShareMedia;
10 |
11 | /**
12 | * Created by tsy on 16/8/4.
13 | */
14 | public abstract class SSOHandler {
15 |
16 | /**
17 | * 初始化
18 | * @param config 配置信息
19 | */
20 | public void onCreate(Context context, PlatformConfig.Platform config) {
21 |
22 | }
23 |
24 | /**
25 | * 登录授权
26 | * @param activity
27 | * @param authListener 授权回调
28 | */
29 | public void authorize(Activity activity, AuthListener authListener) {
30 |
31 | }
32 |
33 | /**
34 | * 分享
35 | * @param shareMedia 分享内容
36 | * @param shareListener 分享回调
37 | */
38 | public void share(Activity activity, IShareMedia shareMedia, ShareListener shareListener) {
39 |
40 | }
41 |
42 | /**
43 | * 重写onActivityResult
44 | * @param requestCode
45 | * @param resultCode
46 | * @param data
47 | */
48 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
49 |
50 | }
51 |
52 | /**
53 | * 是否安装
54 | * @return
55 | */
56 | public boolean isInstall() {
57 | return true;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/SocialApi.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 |
7 | import com.tsy.sdk.social.listener.AuthListener;
8 | import com.tsy.sdk.social.listener.ShareListener;
9 | import com.tsy.sdk.social.qq.QQHandler;
10 | import com.tsy.sdk.social.share_media.IShareMedia;
11 | import com.tsy.sdk.social.sina.SinaWBHandler;
12 | import com.tsy.sdk.social.weixin.WXHandler;
13 |
14 | import java.util.HashMap;
15 | import java.util.Map;
16 |
17 | /**
18 | * api调用统一入口
19 | * Created by tsy on 16/8/4.
20 | */
21 | public class SocialApi {
22 |
23 | private static SocialApi mApi = null;
24 | private static Context mContext = null;
25 |
26 | private final Map mMapSSOHandler = new HashMap();
27 |
28 | private SocialApi(Context context) {
29 | mContext = context;
30 | }
31 |
32 | /**
33 | * 获取单例
34 | * @param context 建议传入全局context
35 | * @return
36 | */
37 | public static SocialApi get(Context context) {
38 | if(mApi == null) {
39 | mApi = new SocialApi(context);
40 | }
41 |
42 | return mApi;
43 | }
44 |
45 | public SSOHandler getSSOHandler(PlatformType platformType) {
46 | if(mMapSSOHandler.get(platformType) == null) {
47 | switch (platformType) {
48 | case WEIXIN:
49 | mMapSSOHandler.put(platformType, new WXHandler());
50 | break;
51 |
52 | case WEIXIN_CIRCLE:
53 | mMapSSOHandler.put(platformType, new WXHandler());
54 | break;
55 |
56 | case QQ:
57 | mMapSSOHandler.put(platformType, new QQHandler());
58 | break;
59 |
60 | case QZONE:
61 | mMapSSOHandler.put(platformType, new QQHandler());
62 | break;
63 |
64 | case SINA_WB:
65 | mMapSSOHandler.put(platformType, new SinaWBHandler());
66 | break;
67 | default:
68 | break;
69 | }
70 | }
71 |
72 | return mMapSSOHandler.get(platformType);
73 | }
74 |
75 | /**
76 | * 第三方登录授权
77 | * @param activity
78 | * @param platformType 第三方平台
79 | * @param authListener 授权回调
80 | */
81 | public void doOauthVerify(Activity activity, PlatformType platformType, AuthListener authListener) {
82 | SSOHandler ssoHandler = getSSOHandler(platformType);
83 | ssoHandler.onCreate(mContext, PlatformConfig.getPlatformConfig(platformType));
84 | ssoHandler.authorize(activity, authListener);
85 | }
86 |
87 | /**
88 | * 分享
89 | * @param platformType
90 | * @param shareMedia
91 | * @param shareListener
92 | */
93 | public void doShare(Activity activity, PlatformType platformType, IShareMedia shareMedia, ShareListener shareListener) {
94 | SSOHandler ssoHandler = getSSOHandler(platformType);
95 | ssoHandler.onCreate(mContext, PlatformConfig.getPlatformConfig(platformType));
96 | ssoHandler.share(activity, shareMedia, shareListener);
97 | }
98 |
99 | /**
100 | * actvitiy result
101 | * @param requestCode
102 | * @param resultCode
103 | * @param data
104 | */
105 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
106 | for (Map.Entry entry : mMapSSOHandler.entrySet()) {
107 | entry.getValue().onActivityResult(requestCode, resultCode, data);
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/api/WXApi.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.api;
2 |
3 | import com.tsy.sdk.social.util.NetUtils;
4 |
5 | import org.json.JSONObject;
6 |
7 | import java.util.HashMap;
8 | import java.util.Map;
9 |
10 | /**
11 | * 微信Api调用
12 | * Created by tangsiyuan on 2016/11/13.
13 | */
14 |
15 | public class WXApi {
16 | private static final String WX_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token"; //获取access token
17 | private static final String WX_GET_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo"; //获取用户信息
18 |
19 | public interface Callback {
20 | void onComplete(Map data);
21 | void onError(String msg);
22 | }
23 |
24 | /**
25 | * 获取access_token
26 | * @param wxAppId wx appid
27 | * @param wxAppSecret wx appsecret
28 | * @param code 调用微信登录获取的code
29 | * @param callback
30 | */
31 | public static void getAccessToken(String wxAppId, String wxAppSecret,
32 | String code,
33 | final Callback callback) {
34 | String access_token_url = WX_ACCESS_TOKEN_URL + "?appid=" + wxAppId + "&secret="
35 | + wxAppSecret + "&code=" + code + "&grant_type=authorization_code";
36 |
37 | //获取access token
38 | NetUtils.doGet(access_token_url, new NetUtils.HttpResponseCallBack() {
39 | @Override
40 | public void onSuccess(JSONObject response) {
41 | if (response == null || response.length() == 0) {
42 | callback.onError("null respone");
43 | return;
44 | }
45 |
46 | if(response.optString("access_token") == null || response.optString("access_token").length() == 0) {
47 | callback.onError("errcode=" + response.optString("errcode") + " errmsg=" + response.optString("errmsg"));
48 | return;
49 | }
50 |
51 | Map data = new HashMap();
52 | String[] keys = {"access_token", "expires_in", "refresh_token", "openid", "scope"};
53 | for(int i=0; i data = new HashMap();
95 | String[] keys = {"openid", "nickname", "sex", "province", "city", "country", "headimgurl", "unionid"};
96 | for(int i=0; i map);
12 |
13 | void onError(PlatformType platform_type, String err_msg);
14 |
15 | void onCancel(PlatformType platform_type);
16 | }
17 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/listener/ShareListener.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.listener;
2 |
3 | import com.tsy.sdk.social.PlatformType;
4 |
5 | /**
6 | * 分享回调监听
7 | * Created by tsy on 16/8/5.
8 | */
9 | public interface ShareListener {
10 | void onComplete(PlatformType platform_type);
11 |
12 | void onError(PlatformType platform_type, String err_msg);
13 |
14 | void onCancel(PlatformType platform_type);
15 | }
16 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/qq/QQHandler.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.qq;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 | import android.os.Environment;
8 | import android.util.Log;
9 |
10 | import com.tencent.connect.share.QQShare;
11 | import com.tencent.connect.share.QzoneShare;
12 | import com.tencent.tauth.IUiListener;
13 | import com.tencent.tauth.Tencent;
14 | import com.tencent.tauth.UiError;
15 | import com.tsy.sdk.social.PlatformConfig;
16 | import com.tsy.sdk.social.PlatformType;
17 | import com.tsy.sdk.social.SSOHandler;
18 | import com.tsy.sdk.social.listener.AuthListener;
19 | import com.tsy.sdk.social.listener.ShareListener;
20 | import com.tsy.sdk.social.share_media.IShareMedia;
21 | import com.tsy.sdk.social.share_media.ShareImageMedia;
22 | import com.tsy.sdk.social.share_media.ShareMusicMedia;
23 | import com.tsy.sdk.social.share_media.ShareWebMedia;
24 | import com.tsy.sdk.social.util.BitmapUtils;
25 | import com.tsy.sdk.social.util.LogUtils;
26 | import com.tsy.sdk.social.util.Utils;
27 |
28 | import org.json.JSONObject;
29 |
30 | import java.io.File;
31 | import java.text.SimpleDateFormat;
32 | import java.util.ArrayList;
33 | import java.util.Date;
34 |
35 | /**
36 | * QQ 第三方 Handler
37 | * Created by tsy on 16/8/18.
38 | */
39 | public class QQHandler extends SSOHandler {
40 |
41 | private Context mContext;
42 | private Activity mActivity;
43 |
44 | private Tencent mTencent;
45 |
46 | private PlatformConfig.QQ mConfig;
47 | private AuthListener mAuthListener;
48 | private ShareListener mShareListener;
49 |
50 | public QQHandler() {
51 |
52 | }
53 |
54 | @Override
55 | public void onCreate(Context context, PlatformConfig.Platform config) {
56 | this.mContext = context;
57 | this.mConfig = (PlatformConfig.QQ) config;
58 |
59 | this.mTencent = Tencent.createInstance(mConfig.appId, mContext);
60 | }
61 |
62 | @Override
63 | public void authorize(Activity activity, AuthListener authListener) {
64 | this.mActivity = activity;
65 | this.mAuthListener = authListener;
66 |
67 | this.mTencent.login(this.mActivity, "all", new IUiListener() {
68 | @Override
69 | public void onComplete(Object o) {
70 | if (null == o || ((JSONObject)o) == null) {
71 | LogUtils.e("onComplete response=null");
72 | mAuthListener.onError(mConfig.getName(), "onComplete response=null");
73 | return;
74 | }
75 |
76 | JSONObject response = (JSONObject) o;
77 |
78 | initOpenidAndToken(response);
79 |
80 | mAuthListener.onComplete(mConfig.getName(), Utils.jsonToMap(response));
81 |
82 | mTencent.logout(mActivity);
83 | }
84 |
85 | @Override
86 | public void onError(UiError uiError) {
87 | String errmsg = "errcode=" + uiError.errorCode + " errmsg=" + uiError.errorMessage + " errdetail=" + uiError.errorDetail;
88 | LogUtils.e(errmsg);
89 | mAuthListener.onError(mConfig.getName(), errmsg);
90 | }
91 |
92 | @Override
93 | public void onCancel() {
94 | mAuthListener.onCancel(mConfig.getName());
95 | }
96 | });
97 | }
98 |
99 | @Override
100 | public void share(Activity activity, IShareMedia shareMedia, ShareListener shareListener) {
101 | this.mActivity = activity;
102 | this.mShareListener = shareListener;
103 |
104 | //获取当前时间
105 | SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMddHHmmss");
106 | Date curDate = new Date(System.currentTimeMillis());
107 | String strDate = formatter.format(curDate);
108 |
109 | final String path = Environment.getExternalStorageDirectory().toString() + "/socail_qq_img_tmp" + strDate + ".png";
110 | final File file = new File(path);
111 | if(file.exists()) {
112 | file.delete();
113 | }
114 |
115 | Bundle params = new Bundle();
116 |
117 | if(this.mConfig.getName() == PlatformType.QZONE) { //qq空间
118 | if(shareMedia instanceof ShareWebMedia) { //网页分享
119 | ShareWebMedia shareWebMedia = (ShareWebMedia) shareMedia;
120 |
121 | //图片保存本地
122 | BitmapUtils.saveBitmapFile(shareWebMedia.getThumb(), path);
123 |
124 | params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
125 | params.putString(QzoneShare.SHARE_TO_QQ_TITLE, shareWebMedia.getTitle());
126 | params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareWebMedia.getDescription());
127 | params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareWebMedia.getWebPageUrl());
128 |
129 | ArrayList path_arr = new ArrayList<>();
130 | path_arr.add(path);
131 | params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, path_arr); //!这里是大坑 不能用SHARE_TO_QQ_IMAGE_LOCAL_URL
132 | } else {
133 | if(this.mShareListener != null) {
134 | this.mShareListener.onError(this.mConfig.getName(), "QZone is not support this shareMedia");
135 | }
136 | return ;
137 | }
138 |
139 | //qq zone分享
140 | this.mTencent.shareToQzone(this.mActivity, params, new IUiListener() {
141 | @Override
142 | public void onComplete(Object o) {
143 | mShareListener.onComplete(mConfig.getName());
144 |
145 | if(file.exists()) {
146 | file.delete();
147 | }
148 | }
149 |
150 | @Override
151 | public void onError(UiError uiError) {
152 | String errmsg = "errcode=" + uiError.errorCode + " errmsg=" + uiError.errorMessage + " errdetail=" + uiError.errorDetail;
153 | LogUtils.e(errmsg);
154 | mShareListener.onError(mConfig.getName(), errmsg);
155 |
156 | if(file.exists()) {
157 | file.delete();
158 | }
159 | }
160 |
161 | @Override
162 | public void onCancel() {
163 | mShareListener.onCancel(mConfig.getName());
164 |
165 | if(file.exists()) {
166 | file.delete();
167 | }
168 | }
169 | });
170 | } else { //分享到qq
171 | if(shareMedia instanceof ShareWebMedia) { //网页分享
172 | ShareWebMedia shareWebMedia = (ShareWebMedia) shareMedia;
173 |
174 | //图片保存本地
175 | BitmapUtils.saveBitmapFile(shareWebMedia.getThumb(), path);
176 |
177 | params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
178 | params.putString(QQShare.SHARE_TO_QQ_TITLE, shareWebMedia.getTitle());
179 | params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareWebMedia.getDescription());
180 | params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareWebMedia.getWebPageUrl());
181 | params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, path);
182 | } else if(shareMedia instanceof ShareImageMedia) { //图片分享
183 | ShareImageMedia shareImageMedia = (ShareImageMedia) shareMedia;
184 |
185 | //图片保存本地
186 | BitmapUtils.saveBitmapFile(shareImageMedia.getImage(), path);
187 |
188 | params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
189 | params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,path);
190 | } else if (shareMedia instanceof ShareMusicMedia) { //音乐分享
191 | ShareMusicMedia shareMusicMedia = (ShareMusicMedia) shareMedia;
192 |
193 | //图片保存本地
194 | BitmapUtils.saveBitmapFile(shareMusicMedia.getThumb(), path);
195 |
196 | params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_AUDIO);
197 | params.putString(QQShare.SHARE_TO_QQ_TITLE, shareMusicMedia.getTitle());
198 | params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareMusicMedia.getDescription());
199 | params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareMusicMedia.getMusicUrl());
200 | params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, path);
201 | params.putString(QQShare.SHARE_TO_QQ_AUDIO_URL, shareMusicMedia.getMusicUrl());
202 | } else {
203 | if(this.mShareListener != null) {
204 | this.mShareListener.onError(this.mConfig.getName(), "QQ is not support this shareMedia");
205 | }
206 | return ;
207 | }
208 |
209 | //qq分享
210 | mTencent.shareToQQ(mActivity, params, new IUiListener() {
211 | @Override
212 | public void onComplete(Object o) {
213 | mShareListener.onComplete(mConfig.getName());
214 |
215 | if(file.exists()) {
216 | file.delete();
217 | }
218 | }
219 |
220 | @Override
221 | public void onError(UiError uiError) {
222 | String errmsg = "errcode=" + uiError.errorCode + " errmsg=" + uiError.errorMessage + " errdetail=" + uiError.errorDetail;
223 | LogUtils.e(errmsg);
224 | mShareListener.onError(mConfig.getName(), errmsg);
225 |
226 | if(file.exists()) {
227 | file.delete();
228 | }
229 | }
230 |
231 | @Override
232 | public void onCancel() {
233 | mShareListener.onCancel(mConfig.getName());
234 |
235 | if(file.exists()) {
236 | file.delete();
237 | }
238 | }
239 | });
240 | }
241 | }
242 |
243 | @Override
244 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
245 | Tencent.onActivityResultData(requestCode, resultCode, data, null);
246 | }
247 |
248 | //要初始化open_id和token
249 | private void initOpenidAndToken(JSONObject jsonObject) {
250 | try {
251 | String token = jsonObject.getString(com.tencent.connect.common.Constants.PARAM_ACCESS_TOKEN);
252 | String expires = jsonObject.getString(com.tencent.connect.common.Constants.PARAM_EXPIRES_IN);
253 | String openId = jsonObject.getString(com.tencent.connect.common.Constants.PARAM_OPEN_ID);
254 |
255 | mTencent.setAccessToken(token, expires);
256 | mTencent.setOpenId(openId);
257 | } catch(Exception e) {
258 | }
259 | }
260 | }
261 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/share_media/IShareMedia.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.share_media;
2 |
3 | /**
4 | * Created by tsy on 16/8/5.
5 | */
6 | public interface IShareMedia {
7 | }
8 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/share_media/ShareImageMedia.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.share_media;
2 |
3 | import android.graphics.Bitmap;
4 |
5 | /**
6 | * 图片分享 实体类
7 | * Created by tsy on 16/8/11.
8 | */
9 | public class ShareImageMedia implements IShareMedia {
10 | private Bitmap mImage;
11 |
12 | public Bitmap getImage() {
13 | return mImage;
14 | }
15 |
16 | public void setImage(Bitmap image) {
17 | mImage = image;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/share_media/ShareMusicMedia.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.share_media;
2 |
3 | import android.graphics.Bitmap;
4 |
5 | /**
6 | * 音乐分享 实体类
7 | * Created by tsy on 16/8/11.
8 | */
9 | public class ShareMusicMedia implements IShareMedia {
10 | private String mMusicUrl; //音乐url
11 | private String mTitle; //标题
12 | private String mDescription; //描述
13 | private Bitmap mThumb; //缩略图
14 |
15 | public String getMusicUrl() {
16 | return mMusicUrl;
17 | }
18 |
19 | public void setMusicUrl(String musicUrl) {
20 | mMusicUrl = musicUrl;
21 | }
22 |
23 | public String getTitle() {
24 | return mTitle;
25 | }
26 |
27 | public void setTitle(String title) {
28 | mTitle = title;
29 | }
30 |
31 | public String getDescription() {
32 | return mDescription;
33 | }
34 |
35 | public void setDescription(String description) {
36 | mDescription = description;
37 | }
38 |
39 | public Bitmap getThumb() {
40 | return mThumb;
41 | }
42 |
43 | public void setThumb(Bitmap thumb) {
44 | mThumb = thumb;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/share_media/ShareTextImageMedia.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.share_media;
2 |
3 | import android.graphics.Bitmap;
4 |
5 | /**
6 | * 文字图片分享 实体类
7 | * Created by tsy on 16/8/11.
8 | */
9 | public class ShareTextImageMedia implements IShareMedia {
10 | private Bitmap mImage;
11 |
12 | public Bitmap getImage() {
13 | return mImage;
14 | }
15 |
16 | public void setImage(Bitmap image) {
17 | mImage = image;
18 | }
19 |
20 | private String mText;
21 |
22 | public String getText() {
23 | return mText;
24 | }
25 |
26 | public void setText(String text) {
27 | mText = text;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/share_media/ShareTextMedia.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.share_media;
2 |
3 | /**
4 | * 文字分享 实体类
5 | * Created by tsy on 16/8/11.
6 | */
7 | public class ShareTextMedia implements IShareMedia {
8 | private String mText;
9 |
10 | public String getText() {
11 | return mText;
12 | }
13 |
14 | public void setText(String text) {
15 | mText = text;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/share_media/ShareVideoMedia.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.share_media;
2 |
3 | import android.graphics.Bitmap;
4 |
5 | /**
6 | * 视频分享 实体类
7 | * Created by tsy on 16/8/11.
8 | */
9 | public class ShareVideoMedia implements IShareMedia {
10 | private String mVideoUrl; //视频url
11 | private String mTitle; //标题
12 | private String mDescription; //描述
13 | private Bitmap mThumb; //缩略图
14 |
15 | public String getVideoUrl() {
16 | return mVideoUrl;
17 | }
18 |
19 | public void setVideoUrl(String videoUrl) {
20 | mVideoUrl = videoUrl;
21 | }
22 |
23 | public String getTitle() {
24 | return mTitle;
25 | }
26 |
27 | public void setTitle(String title) {
28 | mTitle = title;
29 | }
30 |
31 | public String getDescription() {
32 | return mDescription;
33 | }
34 |
35 | public void setDescription(String description) {
36 | mDescription = description;
37 | }
38 |
39 | public Bitmap getThumb() {
40 | return mThumb;
41 | }
42 |
43 | public void setThumb(Bitmap thumb) {
44 | mThumb = thumb;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/share_media/ShareWebMedia.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.share_media;
2 |
3 | import android.graphics.Bitmap;
4 |
5 | /**
6 | * 网页分享 实体类
7 | * Created by tsy on 16/8/5.
8 | */
9 | public class ShareWebMedia implements IShareMedia {
10 |
11 | private String mWebPageUrl; //待分享的网页url
12 | private String mTitle; //网页标题
13 | private String mDescription; //网页描述
14 | private Bitmap mThumb; //网页缩略图
15 |
16 | public String getWebPageUrl() {
17 | return mWebPageUrl;
18 | }
19 |
20 | public void setWebPageUrl(String webPageUrl) {
21 | mWebPageUrl = webPageUrl;
22 | }
23 |
24 | public String getTitle() {
25 | return mTitle;
26 | }
27 |
28 | public void setTitle(String title) {
29 | mTitle = title;
30 | }
31 |
32 | public String getDescription() {
33 | return mDescription;
34 | }
35 |
36 | public void setDescription(String description) {
37 | mDescription = description;
38 | }
39 |
40 | public Bitmap getThumb() {
41 | return mThumb;
42 | }
43 |
44 | public void setThumb(Bitmap thumb) {
45 | mThumb = thumb;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/sina/SinaWBHandler.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.sina;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 |
8 | import com.sina.weibo.sdk.api.ImageObject;
9 | import com.sina.weibo.sdk.api.TextObject;
10 | import com.sina.weibo.sdk.api.WeiboMultiMessage;
11 | import com.sina.weibo.sdk.api.share.BaseResponse;
12 | import com.sina.weibo.sdk.api.share.IWeiboHandler;
13 | import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
14 | import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
15 | import com.sina.weibo.sdk.api.share.WeiboShareSDK;
16 | import com.sina.weibo.sdk.auth.AuthInfo;
17 | import com.sina.weibo.sdk.auth.Oauth2AccessToken;
18 | import com.sina.weibo.sdk.auth.WeiboAuthListener;
19 | import com.sina.weibo.sdk.auth.sso.AccessTokenKeeper;
20 | import com.sina.weibo.sdk.auth.sso.SsoHandler;
21 | import com.sina.weibo.sdk.constant.WBConstants;
22 | import com.sina.weibo.sdk.exception.WeiboException;
23 | import com.tsy.sdk.social.PlatformConfig;
24 | import com.tsy.sdk.social.SSOHandler;
25 | import com.tsy.sdk.social.listener.AuthListener;
26 | import com.tsy.sdk.social.listener.ShareListener;
27 | import com.tsy.sdk.social.share_media.IShareMedia;
28 | import com.tsy.sdk.social.share_media.ShareTextImageMedia;
29 | import com.tsy.sdk.social.util.LogUtils;
30 |
31 | import java.util.HashMap;
32 | import java.util.Map;
33 |
34 | /**
35 | * 新浪微博 第三方Hnadler
36 | * Created by tsy on 16/9/18.
37 | */
38 | public class SinaWBHandler extends SSOHandler {
39 |
40 | private Context mContext;
41 | private Activity mActivity;
42 |
43 | private AuthInfo mAuthInfo;
44 | private SsoHandler mSsoHandler;
45 | private IWeiboShareAPI mWeiboShareAPI;
46 |
47 | private PlatformConfig.SinaWB mConfig;
48 | private AuthListener mAuthListener;
49 | private ShareListener mShareListener;
50 |
51 | private static String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";// 应用的回调页 要和微博开放平台的回调地址一致
52 | private final String SCOPE = "";
53 |
54 | /**
55 | * 设置微博 REDIRECT_URL
56 | * @param redirctUrl
57 | */
58 | public static void setRedirctUrl(String redirctUrl) {
59 | REDIRECT_URL = redirctUrl;
60 | }
61 |
62 | @Override
63 | public void onCreate(Context context, PlatformConfig.Platform config) {
64 | this.mContext = context;
65 | this.mConfig = (PlatformConfig.SinaWB) config;
66 |
67 | this.mAuthInfo = new AuthInfo(mContext, mConfig.appKey, REDIRECT_URL, SCOPE);
68 |
69 | this.mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(context, mConfig.appKey);
70 | this.mWeiboShareAPI.registerApp();
71 | }
72 |
73 | @Override
74 | public void authorize(Activity activity, AuthListener authListener) {
75 | this.mActivity = activity;
76 | this.mAuthListener = authListener;
77 |
78 | this.mSsoHandler = new SsoHandler(mActivity, mAuthInfo);
79 |
80 | mSsoHandler.authorize(new WeiboAuthListener() {
81 | @Override
82 | public void onComplete(Bundle bundle) {
83 | // 从 Bundle 中解析 Token
84 | Oauth2AccessToken accessToken = Oauth2AccessToken.parseAccessToken(bundle);
85 | if(accessToken.isSessionValid()) {
86 | Map map = new HashMap();
87 | map.put("uid", accessToken.getUid());
88 | map.put("access_token", accessToken.getToken());
89 | map.put("refresh_token", accessToken.getRefreshToken());
90 | map.put("expire_time", "" + accessToken.getExpiresTime());
91 |
92 | mAuthListener.onComplete(mConfig.getName(), map);
93 | } else {
94 | String errmsg = "errmsg=accessToken is not SessionValid";
95 | LogUtils.e(errmsg);
96 | mAuthListener.onError(mConfig.getName(), errmsg);
97 | }
98 | }
99 |
100 | @Override
101 | public void onWeiboException(WeiboException e) {
102 | String errmsg = "errmsg=" + e.getMessage();
103 | LogUtils.e(errmsg);
104 | mAuthListener.onError(mConfig.getName(), errmsg);
105 | }
106 |
107 | @Override
108 | public void onCancel() {
109 | mAuthListener.onCancel(mConfig.getName());
110 | }
111 | });
112 | }
113 |
114 | @Override
115 | public void share(Activity activity, IShareMedia shareMedia, ShareListener shareListener) {
116 | this.mActivity = activity;
117 | this.mShareListener = shareListener;
118 |
119 | this.mSsoHandler = new SsoHandler(mActivity, mAuthInfo);
120 |
121 | WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
122 |
123 | if(shareMedia instanceof ShareTextImageMedia) { //文字图片分享
124 | ShareTextImageMedia shareTextImageMedia = (ShareTextImageMedia) shareMedia;
125 |
126 | if(shareTextImageMedia.getText().length() > 0) {
127 | TextObject textObject = new TextObject();
128 | textObject.text = shareTextImageMedia.getText();
129 | weiboMessage.textObject = textObject;
130 | }
131 |
132 | if(shareTextImageMedia.getImage() != null) {
133 | ImageObject imageObject = new ImageObject();
134 | imageObject.setImageObject(shareTextImageMedia.getImage());
135 | weiboMessage.imageObject = imageObject;
136 | }
137 | } else {
138 | if(this.mShareListener != null) {
139 | this.mShareListener.onError(this.mConfig.getName(), "weibo is not support this shareMedia");
140 | }
141 | return ;
142 | }
143 |
144 | SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
145 | request.transaction = String.valueOf(System.currentTimeMillis());
146 | request.multiMessage = weiboMessage;
147 |
148 | Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(mContext.getApplicationContext());
149 | String token = "";
150 | if (accessToken != null) {
151 | token = accessToken.getToken();
152 | }
153 | mWeiboShareAPI.sendRequest(mActivity, request, mAuthInfo, token, new WeiboAuthListener() {
154 |
155 | @Override
156 | public void onWeiboException( WeiboException arg0 ) {
157 | }
158 |
159 | @Override
160 | public void onComplete( Bundle bundle ) {
161 | // TODO Auto-generated method stub
162 | Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
163 | AccessTokenKeeper.writeAccessToken(mContext.getApplicationContext(), newToken);
164 | }
165 |
166 | @Override
167 | public void onCancel() {
168 | }
169 | });
170 |
171 | // mWeiboShareAPI.sendRequest(mActivity, request);
172 | }
173 |
174 | @Override
175 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
176 | if(mSsoHandler != null) {
177 | mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
178 | }
179 | }
180 |
181 | public void onNewIntent(Intent intent, IWeiboHandler.Response response) {
182 | if(mWeiboShareAPI != null) {
183 | mWeiboShareAPI.handleWeiboResponse(intent, response);
184 | }
185 | }
186 |
187 | public void onResponse(BaseResponse baseResponse) {
188 | if(baseResponse!= null){
189 | switch (baseResponse.errCode) {
190 | case WBConstants.ErrorCode.ERR_OK:
191 | if(this.mShareListener != null) {
192 | this.mShareListener.onComplete(this.mConfig.getName());
193 | }
194 | break;
195 | case WBConstants.ErrorCode.ERR_CANCEL:
196 | if(this.mShareListener != null) {
197 | this.mShareListener.onCancel(this.mConfig.getName());
198 | }
199 | break;
200 | case WBConstants.ErrorCode.ERR_FAIL:
201 | if(this.mShareListener != null) {
202 | this.mShareListener.onError(this.mConfig.getName(), baseResponse.errMsg);
203 | }
204 | break;
205 | }
206 | }
207 | }
208 | }
209 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/sina/WBShareCallbackActivity.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.sina;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 |
7 | import com.sina.weibo.sdk.api.share.BaseResponse;
8 | import com.sina.weibo.sdk.api.share.IWeiboHandler;
9 | import com.tsy.sdk.social.PlatformConfig;
10 | import com.tsy.sdk.social.PlatformType;
11 | import com.tsy.sdk.social.SocialApi;
12 |
13 | /**
14 | * Created by tsy on 16/8/4.
15 | */
16 | public class WBShareCallbackActivity extends Activity implements IWeiboHandler.Response {
17 |
18 | protected SinaWBHandler mSinaWBHandler = null;
19 |
20 | public WBShareCallbackActivity() {
21 |
22 | }
23 |
24 | protected void onCreate(Bundle savedInstanceState) {
25 | super.onCreate(savedInstanceState);
26 | SocialApi api = SocialApi.get(this.getApplicationContext());
27 | this.mSinaWBHandler = (SinaWBHandler) api.getSSOHandler(PlatformType.SINA_WB);
28 | this.mSinaWBHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.SINA_WB));
29 |
30 | if(this.getIntent() != null) {
31 | this.handleIntent(this.getIntent());
32 | }
33 | }
34 |
35 | protected final void onNewIntent(Intent paramIntent) {
36 | super.onNewIntent(paramIntent);
37 | SocialApi api = SocialApi.get(this.getApplicationContext());
38 | this.mSinaWBHandler = (SinaWBHandler) api.getSSOHandler(PlatformType.SINA_WB);
39 | this.mSinaWBHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.SINA_WB));
40 |
41 | this.handleIntent(this.getIntent());
42 | }
43 |
44 | protected void handleIntent(Intent intent) {
45 | this.mSinaWBHandler.onNewIntent(intent, this);
46 | }
47 |
48 | @Override
49 | public void onResponse(BaseResponse baseResponse) {
50 | this.mSinaWBHandler.onResponse(baseResponse);
51 | finish();
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/util/BitmapUtils.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.util;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.BitmapFactory;
5 |
6 | import java.io.ByteArrayOutputStream;
7 | import java.io.File;
8 | import java.io.FileOutputStream;
9 | import java.io.IOException;
10 |
11 | /**
12 | * Bitmap相关工具类
13 | * Created by tsy on 16/8/5.
14 | */
15 | public class BitmapUtils {
16 |
17 | /**
18 | * Bitmap保存为文件
19 | * @param bitmap
20 | * @param path
21 | * @return
22 | */
23 | public static File saveBitmapFile(Bitmap bitmap, String path) {
24 | FileOutputStream out = null;
25 | try {
26 | out = new FileOutputStream(path);
27 | bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
28 | } catch (Exception e) {
29 | e.printStackTrace();
30 | return null;
31 | } finally {
32 | try {
33 | if (out != null) {
34 | out.close();
35 | }
36 | } catch (IOException e) {
37 | e.printStackTrace();
38 | }
39 | }
40 |
41 | return new File(path);
42 | }
43 |
44 | /**
45 | * Bitmap 转 bytes
46 | * @param bitmap
47 | * @return
48 | */
49 | public static byte[] bitmap2Bytes(Bitmap bitmap) {
50 | ByteArrayOutputStream byteArrayOutputStream = null;
51 | if(bitmap != null && !bitmap.isRecycled()) {
52 | try {
53 | byteArrayOutputStream = new ByteArrayOutputStream();
54 | bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
55 | if(byteArrayOutputStream.toByteArray() == null) {
56 | LogUtils.e("BitmapUtils", "bitmap2Bytes byteArrayOutputStream toByteArray=null");
57 | }
58 | return byteArrayOutputStream.toByteArray();
59 | } catch (Exception e) {
60 | LogUtils.e("BitmapUtils", e.toString());
61 | } finally {
62 | if(byteArrayOutputStream != null) {
63 | try {
64 | byteArrayOutputStream.close();
65 | } catch (IOException var14) {
66 | ;
67 | }
68 | }
69 | }
70 |
71 | return null;
72 | } else {
73 | LogUtils.e("BitmapUtils", "bitmap2Bytes bitmap == null or bitmap.isRecycled()");
74 | return null;
75 | }
76 | }
77 |
78 | /**
79 | * 压缩图片
80 | * 在保证质量的情况下尽可能压缩 不保证压缩到指定字节
81 | * @param datas
82 | * @param byteCount 指定压缩字节数
83 | * @return
84 | */
85 | public static byte[] compressBitmap(byte[] datas, int byteCount) {
86 | boolean isFinish = false;
87 | if(datas != null && datas.length > byteCount) {
88 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
89 | Bitmap tmpBitmap = BitmapFactory.decodeByteArray(datas, 0, datas.length);
90 | int times = 1;
91 | double percentage = 1.0D;
92 |
93 | while(!isFinish && times <= 10) {
94 | percentage = Math.pow(0.8D, (double)times);
95 | int compress_datas = (int)(100.0D * percentage);
96 | tmpBitmap.compress(Bitmap.CompressFormat.JPEG, compress_datas, outputStream);
97 | if(outputStream != null && outputStream.size() < byteCount) {
98 | isFinish = true;
99 | } else {
100 | outputStream.reset();
101 | ++times;
102 | }
103 | }
104 |
105 | if(outputStream != null) {
106 | byte[] outputStreamByte = outputStream.toByteArray();
107 | if(!tmpBitmap.isRecycled()) {
108 | tmpBitmap.recycle();
109 | }
110 |
111 | if(outputStreamByte.length > byteCount) {
112 | LogUtils.e("BitmapUtils", "compressBitmap cannot compress to " + byteCount + ", after compress size=" + outputStreamByte.length);
113 | }
114 |
115 | return outputStreamByte;
116 | }
117 | }
118 |
119 | return datas;
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/util/LogUtils.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.util;
2 |
3 | import android.util.Log;
4 |
5 | /**
6 | * Created by tsy on 16/8/4.
7 | */
8 | public class LogUtils {
9 |
10 | public static final String TAG = "socialsdk";
11 |
12 | public static void i(String msg) {
13 | Log.i(TAG, msg);
14 | }
15 |
16 | public static void e(String msg) {
17 | Log.e(TAG, msg);
18 | }
19 |
20 | public static void d(String msg) {
21 | Log.d(TAG, msg);
22 | }
23 |
24 | public static void v(String msg) {
25 | Log.v(TAG, msg);
26 | }
27 |
28 | public static void w(String msg) {
29 | Log.w(TAG, msg);
30 | }
31 |
32 | public static void i(String module, String msg) {
33 | Log.i(TAG, "[" + module + "]" + msg);
34 | }
35 |
36 | public static void e(String module, String msg) {
37 | Log.e(TAG, "[" + module + "]" + msg);
38 | }
39 |
40 | public static void d(String module, String msg) {
41 | Log.d(TAG, "[" + module + "]" + msg);
42 | }
43 |
44 | public static void v(String module, String msg) {
45 | Log.v(TAG, "[" + module + "]" + msg);
46 | }
47 |
48 | public static void w(String module, String msg) {
49 | Log.w(TAG, "[" + module + "]" + msg);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/util/NetUtils.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.util;
2 |
3 | import android.accounts.NetworkErrorException;
4 | import android.annotation.TargetApi;
5 | import android.os.Build;
6 | import android.os.Handler;
7 |
8 | import org.json.JSONException;
9 | import org.json.JSONObject;
10 |
11 | import java.io.BufferedReader;
12 | import java.io.DataOutputStream;
13 | import java.io.File;
14 | import java.io.FileInputStream;
15 | import java.io.InputStream;
16 | import java.io.InputStreamReader;
17 | import java.net.HttpURLConnection;
18 | import java.net.URL;
19 | import java.util.Iterator;
20 | import java.util.Map;
21 |
22 | /**
23 | * Created by tsy on 16/8/4.
24 | */
25 | public class NetUtils {
26 | /**
27 | * 请求结果回调接口
28 | */
29 | public interface HttpResponseCallBack {
30 | void onSuccess(JSONObject response); //返回数据
31 | void onFailure(); //网络连接错误 json解析错误
32 | }
33 |
34 | /**
35 | * 异步传输post请求 仅文本参数
36 | * @param url 请求地址
37 | * @param params 请求参数
38 | * @param callback 请求回调
39 | */
40 | public static void doPost(final String url, final Map params, final HttpResponseCallBack callback) {
41 | final Handler handler = new Handler();
42 | new Thread(new Runnable() {
43 | @Override
44 | public void run() {
45 | final String response = post(url, params, null);
46 | handler.post(new Runnable() {
47 | @Override
48 | public void run() {
49 | if (response == null) {
50 | callback.onFailure();
51 | return;
52 | }
53 | try {
54 | JSONObject json = new JSONObject(response);
55 | callback.onSuccess(json);
56 | } catch (JSONException e) {
57 | callback.onFailure();
58 | }
59 | }
60 | });
61 | }
62 | }).start();
63 | }
64 |
65 | /**
66 | * 异步传输post请求 文本 文件混合参数
67 | * @param url 请求地址
68 | * @param params 文本参数
69 | * @param file 上传文件参数
70 | * @param callback 请求回调
71 | */
72 | public static void doPost(final String url, final Map params, final Map file, final HttpResponseCallBack callback) {
73 | //CILogUtils.i("post url=" + url + " params=" + params + " file:" + file);
74 | final Handler handler = new Handler();
75 | new Thread(new Runnable() {
76 | @Override
77 | public void run() {
78 | final String response = post(url, params, file);
79 | //CILogUtils.i("post response=" + response);
80 | handler.post(new Runnable() {
81 | @Override
82 | public void run() {
83 | if (response == null) {
84 | callback.onFailure();
85 | return;
86 | }
87 | try {
88 | JSONObject json = new JSONObject(response);
89 | callback.onSuccess(json);
90 | } catch (JSONException e) {
91 | callback.onFailure();
92 | }
93 | }
94 | });
95 | }
96 | }).start();
97 | }
98 |
99 | /**
100 | * 异步传输get请求
101 | * @param url 请求url
102 | * @param callback 请求回调
103 | */
104 | public static void doGet(final String url, final HttpResponseCallBack callback) {
105 | final Handler handler = new Handler();
106 | new Thread(new Runnable() {
107 | @Override
108 | public void run() {
109 | final String response = get(url);
110 | handler.post(new Runnable() {
111 | @Override
112 | public void run() {
113 | if(response == null) {
114 | callback.onFailure();
115 | return;
116 | }
117 | try {
118 | JSONObject json = new JSONObject(response);
119 | callback.onSuccess(json);
120 | } catch (JSONException e) {
121 | callback.onFailure();
122 | }
123 | }
124 | });
125 | }
126 | }).start();
127 | }
128 |
129 | /**
130 | * 使用HttpURLConnection进行post请求
131 | * @param url 请求地址
132 | * @param params 请求参数 key-val
133 | * @param files 上传的文件 key-file path
134 | * @return 请求返回值
135 | */
136 | @TargetApi(Build.VERSION_CODES.ECLAIR)
137 | private static String post(String url, Map params, Map files) {
138 | HttpURLConnection conn = null;
139 |
140 | //http content 头尾等信息
141 | String PREFIX = "--"; //前缀
142 | String BOUNDARY = "*****"+Long.toString(System.currentTimeMillis())+"*****"; //自定义分割串
143 | String END = "\r\n"; //结束
144 |
145 | try {
146 | //创建连接
147 | URL mURL = new URL(url); // 创建一个URL对象
148 | conn = (HttpURLConnection) mURL.openConnection(); // 调用URL的openConnection()方法,获取HttpURLConnection对象
149 |
150 | conn.setReadTimeout(5000);// 设置读取超时为5秒
151 | conn.setConnectTimeout(10000);// 设置连接网络超时为10秒
152 |
153 | // 允许Input、Output,不使用Cache
154 | conn.setDoInput(true);
155 | conn.setDoOutput(true);
156 | conn.setUseCaches(false);
157 |
158 | conn.setRequestMethod("POST");// 设置请求方法为post
159 | conn.setRequestProperty("Connection", "Keep-Alive");
160 | conn.setRequestProperty("Charset", "UTF-8");
161 | conn.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
162 | conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
163 |
164 | DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
165 |
166 | //post文件
167 | if(files != null && !files.isEmpty()) {
168 | Iterator> iterator = files.entrySet().iterator();
169 | while (iterator.hasNext()) {
170 | Map.Entry param = iterator.next();
171 | String file_param_name = param.getKey(); //参数名
172 | String file_path = param.getValue(); //路径
173 | String filename = file_path.substring(file_path.lastIndexOf("/") + 1); //文件名
174 |
175 | File file = new File(file_path);
176 | if(file == null || !file.exists()) {
177 | //CILogUtils.e("file not exist:" + file);
178 | continue;
179 | }
180 |
181 | //头部
182 | StringBuilder sb = new StringBuilder();
183 | sb.append(PREFIX + BOUNDARY + END);
184 | sb.append("Content-Disposition: form-data; name=" + "\"" + file_param_name +
185 | "\";filename=\"" + filename + "\"" + END);
186 | sb.append("Content-Type: application/octet-stream; charset=UTF-8" + END);
187 | sb.append(END);
188 | outputStream.writeBytes(sb.toString());
189 |
190 | // 取得文件的FileInputStream
191 | FileInputStream fis = new FileInputStream(file_path);
192 | byte[] buffer = new byte[1024];
193 | int length = -1;
194 | // 从文件读取数据至缓冲区
195 | while ((length = fis.read(buffer)) != -1) {
196 | outputStream.write(buffer, 0, length);
197 | }
198 | fis.close();
199 |
200 | outputStream.writeBytes(END);
201 | }
202 | }
203 |
204 | // post文本参数
205 | if(params != null && !params.isEmpty()) {
206 | Iterator> iterator = params.entrySet().iterator();
207 | while (iterator.hasNext()) {
208 | Map.Entry param = iterator.next();
209 | String key = param.getKey();
210 | String value = param.getValue();
211 |
212 | if(key == null || value == null) {
213 | continue;
214 | }
215 | outputStream.writeBytes(PREFIX + BOUNDARY + END);
216 | outputStream.writeBytes("Content-Disposition: form-data; name=" + "\"" + key + "\"" + END);
217 | outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + END);
218 | outputStream.writeBytes(END);
219 | outputStream.write(value.getBytes("UTF-8"));
220 | outputStream.writeBytes(END);
221 | }
222 | }
223 |
224 | outputStream.writeBytes(PREFIX + BOUNDARY + END);
225 | outputStream.flush();
226 | outputStream.close();
227 |
228 | //请求返回
229 | int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
230 | if (responseCode == HttpURLConnection.HTTP_OK) {
231 | InputStream is = conn.getInputStream(); //获得输入流
232 | BufferedReader reader = new BufferedReader(new InputStreamReader(is)); //包装字节流为字符流
233 | StringBuilder response = new StringBuilder();
234 | String line;
235 | while ((line = reader.readLine()) != null) {
236 | response.append(line);
237 | }
238 | if(is != null) {
239 | is.close();
240 | }
241 |
242 | return response.toString();
243 | } else {
244 | throw new NetworkErrorException("response status is " + responseCode);
245 | }
246 |
247 | } catch (Exception e) {
248 | e.printStackTrace();
249 | return null;
250 | } finally {
251 | if (conn != null) {
252 | conn.disconnect(); // 关闭连接
253 | }
254 | }
255 | }
256 |
257 | /**
258 | * 使用HttpURLConnection进行get请求
259 | * @param url 请求地址
260 | * @return 请求返回值
261 | */
262 | @TargetApi(Build.VERSION_CODES.ECLAIR)
263 | private static String get(String url) {
264 | HttpURLConnection conn = null;
265 | try {
266 | //创建连接
267 | URL mURL = new URL(url);
268 | conn = (HttpURLConnection) mURL.openConnection();
269 | conn.setRequestMethod("GET");
270 | conn.setReadTimeout(5000);
271 | conn.setConnectTimeout(10000);
272 |
273 | //请求返回
274 | int responseCode = conn.getResponseCode();
275 | if (responseCode == HttpURLConnection.HTTP_OK) {
276 | InputStream is = conn.getInputStream(); //获得输入流
277 | BufferedReader reader = new BufferedReader(new InputStreamReader(is)); //包装字节流为字符流
278 | StringBuilder response = new StringBuilder();
279 | String line;
280 | while ((line = reader.readLine()) != null) {
281 | response.append(line);
282 | }
283 | if(is != null) {
284 | is.close();
285 | }
286 |
287 | return response.toString();
288 | } else {
289 | throw new NetworkErrorException("response status is " + responseCode);
290 | }
291 |
292 | } catch (Exception e) {
293 | e.printStackTrace();
294 | return null;
295 | } finally {
296 | if (conn != null) {
297 | conn.disconnect(); // 关闭连接
298 | }
299 | }
300 | }
301 | }
302 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/util/Utils.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.util;
2 |
3 | import org.json.JSONObject;
4 |
5 | import java.util.HashMap;
6 | import java.util.Iterator;
7 | import java.util.Map;
8 |
9 | /**
10 | * Created by tsy on 16/8/4.
11 | */
12 | public class Utils {
13 |
14 | public static Map jsonToMap(JSONObject val) {
15 | HashMap map = new HashMap();
16 |
17 | Iterator iterator = val.keys();
18 |
19 | while(iterator.hasNext()) {
20 | String var4 = (String)iterator.next();
21 | map.put(var4, val.opt(var4) + "");
22 | }
23 |
24 | return map;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/weixin/WXCallbackActivity.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.weixin;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 |
7 | import com.tencent.mm.opensdk.modelbase.BaseReq;
8 | import com.tencent.mm.opensdk.modelbase.BaseResp;
9 | import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
10 | import com.tsy.sdk.social.PlatformConfig;
11 | import com.tsy.sdk.social.PlatformType;
12 | import com.tsy.sdk.social.SocialApi;
13 |
14 | /**
15 | * Created by tsy on 16/8/4.
16 | */
17 | public class WXCallbackActivity extends Activity implements IWXAPIEventHandler {
18 |
19 | protected WXHandler mWXHandler = null;
20 | protected WXHandler mWXCircleHandler = null;
21 |
22 |
23 | public WXCallbackActivity() {
24 |
25 | }
26 |
27 | protected void onCreate(Bundle savedInstanceState) {
28 | super.onCreate(savedInstanceState);
29 | SocialApi api = SocialApi.get(this.getApplicationContext());
30 | this.mWXHandler = (WXHandler)api.getSSOHandler(PlatformType.WEIXIN);
31 | this.mWXHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.WEIXIN));
32 |
33 | this.mWXCircleHandler = (WXHandler)api.getSSOHandler(PlatformType.WEIXIN_CIRCLE);
34 | this.mWXCircleHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.WEIXIN_CIRCLE));
35 |
36 | this.mWXHandler.getWXApi().handleIntent(this.getIntent(), this);
37 | }
38 |
39 | protected final void onNewIntent(Intent paramIntent) {
40 | super.onNewIntent(paramIntent);
41 | SocialApi api = SocialApi.get(this.getApplicationContext());
42 | this.mWXHandler = (WXHandler)api.getSSOHandler(PlatformType.WEIXIN);
43 | this.mWXHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.WEIXIN));
44 |
45 | this.mWXCircleHandler = (WXHandler)api.getSSOHandler(PlatformType.WEIXIN_CIRCLE);
46 | this.mWXCircleHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.WEIXIN_CIRCLE));
47 |
48 | this.mWXHandler.getWXApi().handleIntent(this.getIntent(), this);
49 | }
50 |
51 | public void onResp(BaseResp resp) {
52 | if(this.mWXHandler != null && resp != null) {
53 | try {
54 | this.mWXHandler.getWXEventHandler().onResp(resp);
55 | } catch (Exception var3) {
56 | ;
57 | }
58 | }
59 |
60 | if(this.mWXCircleHandler != null && resp != null) {
61 | try {
62 | this.mWXCircleHandler.getWXEventHandler().onResp(resp);
63 | } catch (Exception var3) {
64 | ;
65 | }
66 | }
67 |
68 | this.finish();
69 | }
70 |
71 | public void onReq(BaseReq req) {
72 | if(this.mWXHandler != null) {
73 | this.mWXHandler.getWXEventHandler().onReq(req);
74 | }
75 |
76 | this.finish();
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/social_sdk/src/main/java/com/tsy/sdk/social/weixin/WXHandler.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social.weixin;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.graphics.Bitmap;
6 | import android.text.TextUtils;
7 |
8 | import com.tencent.mm.opensdk.constants.ConstantsAPI;
9 | import com.tencent.mm.opensdk.modelbase.BaseReq;
10 | import com.tencent.mm.opensdk.modelbase.BaseResp;
11 | import com.tencent.mm.opensdk.modelmsg.SendAuth;
12 | import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
13 | import com.tencent.mm.opensdk.modelmsg.WXImageObject;
14 | import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
15 | import com.tencent.mm.opensdk.modelmsg.WXMusicObject;
16 | import com.tencent.mm.opensdk.modelmsg.WXTextObject;
17 | import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
18 | import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
19 | import com.tencent.mm.opensdk.openapi.IWXAPI;
20 | import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
21 | import com.tencent.mm.opensdk.openapi.WXAPIFactory;
22 | import com.tsy.sdk.social.PlatformConfig;
23 | import com.tsy.sdk.social.PlatformType;
24 | import com.tsy.sdk.social.SSOHandler;
25 | import com.tsy.sdk.social.listener.AuthListener;
26 | import com.tsy.sdk.social.listener.ShareListener;
27 | import com.tsy.sdk.social.share_media.IShareMedia;
28 | import com.tsy.sdk.social.share_media.ShareImageMedia;
29 | import com.tsy.sdk.social.share_media.ShareMusicMedia;
30 | import com.tsy.sdk.social.share_media.ShareTextMedia;
31 | import com.tsy.sdk.social.share_media.ShareVideoMedia;
32 | import com.tsy.sdk.social.share_media.ShareWebMedia;
33 | import com.tsy.sdk.social.util.BitmapUtils;
34 | import com.tsy.sdk.social.util.LogUtils;
35 |
36 | import java.util.HashMap;
37 | import java.util.Map;
38 |
39 | /**
40 | * 微信处理Handler
41 | * Created by tsy on 16/8/4.
42 | */
43 | public class WXHandler extends SSOHandler {
44 |
45 | private Context mContext;
46 | private Activity mActivtiy;
47 |
48 | private IWXAPI mWXApi;
49 |
50 | //默认scope 和 state
51 | private static String sScope = "snsapi_userinfo,snsapi_friend,snsapi_message";
52 | private static String sState = "none";
53 |
54 | private IWXAPIEventHandler mEventHandler;
55 | private String mLastTransaction = "";
56 |
57 | private PlatformConfig.Weixin mConfig;
58 | private AuthListener mAuthListener;
59 | private ShareListener mShareListener;
60 |
61 | public WXHandler() {
62 | this.mEventHandler = new IWXAPIEventHandler() {
63 | public void onResp(BaseResp resp) {
64 | if(!mLastTransaction.equals(resp.transaction)) {
65 | return;
66 | }
67 |
68 | int type = resp.getType();
69 | switch(type) {
70 | case ConstantsAPI.COMMAND_SENDAUTH: //授权返回
71 | WXHandler.this.onAuthCallback((SendAuth.Resp)resp);
72 | break;
73 |
74 | case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX: //分享返回
75 | WXHandler.this.onShareCallback((SendMessageToWX.Resp)resp);
76 | break;
77 | }
78 |
79 | }
80 |
81 | public void onReq(BaseReq req) {
82 | }
83 | };
84 | }
85 |
86 | /**
87 | * 设置scope和state
88 | * @param scope
89 | * @param state
90 | */
91 | public static void setScopeState(String scope, String state) {
92 | sScope = scope;
93 | sState = state;
94 | }
95 |
96 | @Override
97 | public void onCreate(Context context, PlatformConfig.Platform config) {
98 | this.mContext = context;
99 | this.mConfig = (PlatformConfig.Weixin) config;
100 |
101 | this.mWXApi = WXAPIFactory.createWXAPI(mContext.getApplicationContext(), this.mConfig.appId);
102 | this.mWXApi.registerApp(this.mConfig.appId);
103 | }
104 |
105 | @Override
106 | public boolean isInstall() {
107 | return this.mWXApi.isWXAppInstalled();
108 | }
109 |
110 | @Override
111 | public void authorize(Activity activity, AuthListener authListener) {
112 | if(!isInstall()) {
113 | authListener.onError(this.mConfig.getName(), "wx not install");
114 | LogUtils.e("wx not install");
115 | return ;
116 | }
117 |
118 | this.mActivtiy = activity;
119 | this.mAuthListener = authListener;
120 |
121 | SendAuth.Req req1 = new SendAuth.Req();
122 | req1.scope = sScope;
123 | req1.state = sState;
124 | req1.transaction = buildTransaction("authorize");
125 | mLastTransaction = req1.transaction;
126 |
127 | if(!this.mWXApi.sendReq(req1)) {
128 | this.mAuthListener.onError(this.mConfig.getName(), "sendReq fail");
129 | LogUtils.e("wxapi sendReq fail");
130 | }
131 | }
132 |
133 | //验证回调
134 | protected void onAuthCallback(SendAuth.Resp resp) {
135 | switch (resp.errCode) {
136 | case BaseResp.ErrCode.ERR_OK: //授权成功
137 | Map data = new HashMap();
138 | data.put("code", resp.code);
139 | this.mAuthListener.onComplete(PlatformType.WEIXIN, data);
140 | break;
141 |
142 | case BaseResp.ErrCode.ERR_USER_CANCEL: //授权取消
143 | if(this.mAuthListener != null) {
144 | this.mAuthListener.onCancel(PlatformType.WEIXIN);
145 | }
146 | break;
147 |
148 | default: //授权失败
149 | CharSequence err = TextUtils.concat(new CharSequence[]{"weixin auth error (", String.valueOf(resp.errCode), "):", resp.errStr});
150 | if(mAuthListener != null) {
151 | mAuthListener.onError(PlatformType.WEIXIN, err.toString());
152 | }
153 | break;
154 | }
155 | }
156 |
157 | @Override
158 | public void share(Activity activity, IShareMedia shareMedia, ShareListener shareListener) {
159 | if(!isInstall()) {
160 | shareListener.onError(this.mConfig.getName(), "wx not install");
161 | LogUtils.e("wx not install");
162 | return ;
163 | }
164 |
165 | this.mActivtiy = activity;
166 | this.mShareListener = shareListener;
167 |
168 | WXMediaMessage msg = new WXMediaMessage();
169 | String type = "";
170 |
171 | if(shareMedia instanceof ShareWebMedia) { //网页分享
172 | ShareWebMedia shareWebMedia = (ShareWebMedia) shareMedia;
173 | type = "webpage";
174 |
175 | //web object
176 | WXWebpageObject webpageObject = new WXWebpageObject();
177 | webpageObject.webpageUrl = shareWebMedia.getWebPageUrl();
178 |
179 | msg.mediaObject = webpageObject;
180 | msg.title = shareWebMedia.getTitle();
181 | msg.description = shareWebMedia.getDescription();
182 | msg.thumbData = BitmapUtils.bitmap2Bytes(shareWebMedia.getThumb());
183 | } else if(shareMedia instanceof ShareTextMedia) { //文字分享
184 | ShareTextMedia shareTextMedia = (ShareTextMedia) shareMedia;
185 | type = "text";
186 |
187 | //text object
188 | WXTextObject textObject = new WXTextObject();
189 | textObject.text = shareTextMedia.getText();
190 |
191 | msg.mediaObject = textObject;
192 | msg.description = shareTextMedia.getText();
193 | } else if(shareMedia instanceof ShareImageMedia) { //图片分享
194 | ShareImageMedia shareImageMedia = (ShareImageMedia) shareMedia;
195 | type = "image";
196 |
197 | //image object
198 | WXImageObject imageObject = new WXImageObject();
199 | //image限制10M
200 | imageObject.imageData = BitmapUtils.compressBitmap(BitmapUtils.bitmap2Bytes(shareImageMedia.getImage()), 10 * 1024 * 1024);
201 |
202 | msg.mediaObject = imageObject;
203 |
204 | //直接缩放图片
205 | Bitmap thumb = Bitmap.createScaledBitmap(shareImageMedia.getImage(), 200, 200, true);
206 | msg.thumbData = BitmapUtils.bitmap2Bytes(thumb);
207 | thumb.recycle();
208 | } else if(shareMedia instanceof ShareMusicMedia) { //音乐分享
209 | ShareMusicMedia shareMusicMedia = (ShareMusicMedia) shareMedia;
210 | type = "music";
211 |
212 | WXMusicObject musicObject = new WXMusicObject();
213 | musicObject.musicUrl = shareMusicMedia.getMusicUrl();
214 |
215 | msg.mediaObject = musicObject;
216 | msg.title = shareMusicMedia.getTitle();
217 | msg.description = shareMusicMedia.getDescription();
218 | msg.thumbData = BitmapUtils.bitmap2Bytes(shareMusicMedia.getThumb());
219 | } else if(shareMedia instanceof ShareVideoMedia) { //视频分享
220 | ShareVideoMedia shareVideoMedia = (ShareVideoMedia) shareMedia;
221 | type = "video";
222 |
223 | WXVideoObject videoObject = new WXVideoObject();
224 | videoObject.videoUrl = shareVideoMedia.getVideoUrl();
225 |
226 | msg.mediaObject = videoObject;
227 | msg.title = shareVideoMedia.getTitle();
228 | msg.description = shareVideoMedia.getDescription();
229 | msg.thumbData = BitmapUtils.bitmap2Bytes(shareVideoMedia.getThumb());
230 | } else {
231 | if(this.mShareListener != null) {
232 | this.mShareListener.onError(this.mConfig.getName(), "weixin is not support this shareMedia");
233 | }
234 | return ;
235 | }
236 |
237 | //压缩缩略图到32kb
238 | if(msg.thumbData != null && msg.thumbData.length > '耀') { //微信sdk里面判断的大小
239 | msg.thumbData = BitmapUtils.compressBitmap(msg.thumbData, '耀');
240 | }
241 |
242 | //发起request
243 | SendMessageToWX.Req req = new SendMessageToWX.Req();
244 | req.message = msg;
245 | req.transaction = buildTransaction(type);
246 | mLastTransaction = req.transaction;
247 |
248 | if(this.mConfig.getName() == PlatformType.WEIXIN) { //分享好友
249 | req.scene = SendMessageToWX.Req.WXSceneSession;
250 | } else if(this.mConfig.getName() == PlatformType.WEIXIN_CIRCLE) { //分享朋友圈
251 | req.scene = SendMessageToWX.Req.WXSceneTimeline;
252 | }
253 |
254 | if(!this.mWXApi.sendReq(req)) {
255 | if(this.mShareListener != null) {
256 | this.mShareListener.onError(this.mConfig.getName(), "sendReq fail");
257 | }
258 | LogUtils.e("wxapi sendReq fail");
259 | }
260 | }
261 |
262 | protected void onShareCallback(com.tencent.mm.opensdk.modelmsg.SendMessageToWX.Resp resp) {
263 | switch (resp.errCode) {
264 | case BaseResp.ErrCode.ERR_OK: //分享成功
265 | if(this.mShareListener != null) {
266 | this.mShareListener.onComplete(this.mConfig.getName());
267 | }
268 | break;
269 |
270 | case BaseResp.ErrCode.ERR_USER_CANCEL: //分享取消
271 | if(this.mShareListener != null) {
272 | this.mShareListener.onCancel(this.mConfig.getName());
273 | }
274 | break;
275 |
276 | default: //分享失败
277 | CharSequence err = TextUtils.concat(new CharSequence[]{"weixin share error (", String.valueOf(resp.errCode), "):", resp.errStr});
278 | if(mShareListener != null) {
279 | mShareListener.onError(this.mConfig.getName(), err.toString());
280 | }
281 | break;
282 | }
283 | }
284 |
285 | private String buildTransaction(String type) {
286 | return type == null?String.valueOf(System.currentTimeMillis()):type + System.currentTimeMillis();
287 | }
288 |
289 | public IWXAPI getWXApi() {
290 | return this.mWXApi;
291 | }
292 |
293 | public IWXAPIEventHandler getWXEventHandler() {
294 | return this.mEventHandler;
295 | }
296 | }
297 |
--------------------------------------------------------------------------------
/social_sdk/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | social_sdk
3 |
4 |
--------------------------------------------------------------------------------
/social_sdk/src/test/java/com/tsy/sdk/social/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.tsy.sdk.social;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------