Compare commits

..

400 Commits
v1.46 ... v2.2

Author SHA1 Message Date
ac3e2375bc 解决关闭下载按钮时,下载按钮还显示问题 2016-12-16 16:56:16 +08:00
3b8e0fcad2 ... 2016-12-06 16:47:39 +08:00
f8e3158e8f 统一下载按钮状态的设置 2016-12-06 16:42:17 +08:00
7bb5f380a7 Merge branch '2.2' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.2 2016-12-06 15:59:06 +08:00
618077c128 解决跳转意见反馈无content问题 2016-12-06 15:58:42 +08:00
khy
23aa0ebde7 Merge remote-tracking branch 'origin/2.2' into 2.2 2016-12-06 11:41:43 +08:00
khy
17e98407c7 修复模拟器短信分享闪退Bug 2016-12-06 11:40:50 +08:00
6d8605ed4d 解决非apk2、download开头的https导致的无法下载问题 2016-12-05 14:05:44 +08:00
d02a136e2f Merge branch '2.2' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.2 2016-12-03 16:01:27 +08:00
1a9b23ca10 解决下载存储apk在data/data目录下导致的apk安装解析出错问题 2016-12-03 15:55:42 +08:00
khy
3d82162b4d 修复平台名字为null问题 2016-12-02 17:39:21 +08:00
khy
39a42e224a 换肤微调 2016-12-02 09:39:43 +08:00
khy
f93e5d38f2 修复原创文章闪退bug,换肤文案后台控制 2016-12-01 20:53:47 +08:00
khy
2f4688cb13 Merge remote-tracking branch 'origin/2.2' into 2.2 2016-12-01 14:46:29 +08:00
khy
24c41107d2 修改点赞逻辑,评论数据同步 2016-12-01 14:45:55 +08:00
9eef163e70 https修改 2016-12-01 11:46:09 +08:00
khy
e82f202a17 消息分享图片增加占位符 2016-11-30 11:22:47 +08:00
khy
da8ca7dbfb 合并整理 2016-11-30 10:44:37 +08:00
khy
0fcf70a2bf Merge remote-tracking branch 'origin/2.2' into 2.2
# Conflicts:
#	app/src/main/java/com/gh/gamecenter/MessageDetailActivity.java
#	app/src/main/java/com/gh/gamecenter/adapter/MessageDetailAdapter.java
#	app/src/main/java/com/gh/gamecenter/newsdetail/NewsDetailAdapter.java
2016-11-30 10:39:35 +08:00
khy
68f8bee146 文章详情增加评论入口 2016-11-30 10:29:35 +08:00
e35a0ffc17 问题修复 2016-11-29 10:59:37 +08:00
21f1a161c9 Merge branch '2.2' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.2
Conflicts:
	app/src/main/java/com/gh/gamecenter/adapter/MessageDetailAdapter.java
2016-11-29 10:59:15 +08:00
a31d2cd28b 去除volley 中TAG的滥用导致无法重复加载同一url,项目整理 2016-11-29 10:49:45 +08:00
47f978a4fa 删除无用文件 2016-11-29 10:47:40 +08:00
c2f2672421 增加跳转意见反馈页面带content参数 2016-11-28 17:25:53 +08:00
aaf6598e43 onSaveInstanceState保存参数 2016-11-28 11:35:03 +08:00
f77a4eb3cb 删除静态searchHint的使用 2016-11-28 11:22:57 +08:00
3435da0124 增加意见反馈页面的跳转支持 2016-11-28 11:21:55 +08:00
d705a3172b 修复无限启动助手问题 2016-11-28 11:20:49 +08:00
khy
82cf8cb877 调用系统短信分享,删除shareSDK 2016-11-24 18:30:34 +08:00
khy
2dabd5492f 版本更新推送增加了一个“从不”的选项,修复微信好友分享不能扫描二维码问题 2016-11-24 17:19:23 +08:00
khy
64827028b5 接入微博分享官方SDK 2016-11-24 11:14:53 +08:00
khy
753ca3abc0 优化软键盘弹出,进入消息详情时定位到评论,修复海马模拟器无法显示评论内容 2016-11-23 12:02:15 +08:00
a6bf61bc48 。。。 2016-11-21 18:54:30 +08:00
0d79bc2600 。。。 2016-11-21 18:51:57 +08:00
3273e9879b 。。。 2016-11-21 18:47:47 +08:00
9c8898faa4 Merge branch '2.2' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.2
Conflicts:
	app/src/main/java/com/gh/common/util/PostCommentUtils.java
	app/src/main/java/com/gh/gamecenter/MessageDetailActivity.java
	app/src/main/java/com/gh/gamecenter/adapter/MessageDetailAdapter.java
	app/src/main/java/com/gh/gamecenter/entity/UserEntity.java
2016-11-21 18:45:44 +08:00
0ed314ed81 文件修改整理 2016-11-21 18:29:36 +08:00
khy
14fa92e0be Merge remote-tracking branch 'origin/2.2' into 2.2 2016-11-21 18:27:30 +08:00
khy
aeb5346606 消息相关优化汇总1120(3,6未完成) 2016-11-21 18:27:08 +08:00
0ab734f777 添加换肤 2016-11-21 18:21:20 +08:00
72a4b4e267 文件还原 2016-11-21 17:46:28 +08:00
7052c6f68b 文件删除 2016-11-21 17:17:23 +08:00
4beba85de4 Merge remote-tracking branch 'origin/2.2' into 2.2 2016-11-21 17:12:00 +08:00
51edbd9baa 版本回滚到commit 88bb8949dd 2016-11-21 17:08:14 +08:00
khy
e249968662 Merge remote-tracking branch 'origin/2.2' into 2.2 2016-11-21 16:41:07 +08:00
khy
567634c958 亚瑟王换肤 2016-11-21 16:40:28 +08:00
2a92c10777 修改下载按钮文案显示逻辑,修改多版本显示顺序逻辑,更换引导图 2016-11-21 11:27:27 +08:00
7c801366ef 一键修复下载成功跳转至首页 2016-11-21 09:27:54 +08:00
bbffe7737b 修复搜索界面崩溃bug 2016-11-21 09:07:20 +08:00
khy
88bb8949dd 消息webView下载跳转自带浏览器,分享卡片修复图片混乱 2016-11-18 18:32:21 +08:00
d7d9027afa Merge branch '2.2' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.2
Conflicts:
	app/src/main/java/com/gh/gamecenter/MessageDetailActivity.java
	app/src/main/java/com/gh/gamecenter/adapter/MessageDetailAdapter.java
2016-11-18 11:27:01 +08:00
khy
1917462ea3 成功添加评论后,修改资讯-关注列表评论数缓存。修复点赞复用bug 2016-11-17 19:43:10 +08:00
4c69888938 消息详情代码整理 2016-11-17 17:47:38 +08:00
639ca433a2 提取FragmentAdapter为独立类 2016-11-17 16:25:03 +08:00
khy
44c1a2adb6 成功添加评论后,更新资讯-关注评论数 2016-11-17 09:34:10 +08:00
6369c480f9 Merge branch '2.2' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.2
Conflicts:
	app/src/main/java/com/gh/gamecenter/news/News1FragmentAdapter.java
2016-11-16 19:17:12 +08:00
b2a7de0a72 去掉viewMap,在实体中添加views解决
修复部分问题
2016-11-16 19:13:40 +08:00
khy
19825aa844 解决插件弹窗平台图片大小不一致问题 2016-11-16 16:42:51 +08:00
khy
14ece26b85 编辑评论时增加提示文案 2016-11-16 14:31:54 +08:00
9a17352156 Merge branch '2.2' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.2
Conflicts:
	app/src/main/java/com/gh/common/util/PostCommentUtils.java
2016-11-16 14:28:56 +08:00
b9eb8de88a 解决token 401问题 2016-11-16 14:22:07 +08:00
khy
04cfbcb7e4 调整评论,消息分享,关闭下载的游戏不要隐藏下载按钮 2016-11-16 12:08:26 +08:00
d74d91532b 添加网页跳转助手支持 2016-11-16 11:44:33 +08:00
khy
f28a54506e 解决冲突 2016-11-16 10:22:06 +08:00
khy
b6797131e7 Merge remote-tracking branch 'origin/2.2' into 2.2
# Conflicts:
#	app/src/main/java/com/gh/gamecenter/adapter/MessageDetailAdapter.java
#	app/src/main/java/com/gh/gamecenter/news/News1FragmentAdapter.java
#	app/src/main/java/com/gh/gamecenter/news/NewsConcernViewHolder.java
#	app/src/main/res/layout/news_digest_item.xml
2016-11-16 10:11:25 +08:00
khy
20a5f25901 评论和分享优化, 设置增加“自动关注”的开关选项 2016-11-16 09:19:02 +08:00
6ccc3e5cc6 添加首页轮播图数据统计 2016-11-14 19:01:27 +08:00
9eb68e641c 增加游戏详情和文章详情的插件游戏的下载按钮显示状态 2016-11-14 14:30:43 +08:00
3f5a94e710 修改后台或用户打开下载后不会再回到关闭下载的状态 2016-11-14 14:08:42 +08:00
22e51f1216 news模块修改(完成) 2016-11-14 13:58:02 +08:00
7060c906a7 TAG问题修复 2016-11-11 21:17:30 +08:00
e61c265418 Merge branch '2.2' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.2
Conflicts:
	app/src/main/java/com/gh/common/util/MessageShareUtils.java
2016-11-11 21:16:54 +08:00
1149751ae4 news模块修改2(未完成) 2016-11-11 21:13:41 +08:00
khy
d35a798a80 解决冲突代码 2016-11-11 18:31:27 +08:00
khy
175b07875a Merge remote-tracking branch 'origin/2.2' into 2.2
# Conflicts:
#	app/src/main/java/com/gh/gamecenter/adapter/viewholder/FooterViewHolder.java
#	app/src/main/java/com/gh/gamecenter/news/News1FragmentAdapter.java
2016-11-11 18:25:23 +08:00
khy
8cb2ecd113 消息评论功能 基本完成 2016-11-11 18:17:09 +08:00
362de65b36 Merge branch '2.2' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.2 2016-11-09 19:10:06 +08:00
c753663079 news模块修改(未完成) 2016-11-09 19:09:30 +08:00
khy
f243d98094 Merge remote-tracking branch 'origin/2.2' into 2.2 2016-11-09 10:07:12 +08:00
d711a9a14c 增加timestamp,缓存机制,和404处理 2016-11-08 18:58:14 +08:00
khy
e399a81ee3 完成消息分享功能 2016-11-08 16:33:01 +08:00
f030f88029 提交Retrofit网络架构(未完成) 2016-11-07 18:58:15 +08:00
54f2959d6a 提取DATA_HOST 2016-11-07 11:25:56 +08:00
d5a63da257 Merge branch '2.2' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.2 2016-11-07 10:56:56 +08:00
2a09f39fdb . 2016-11-07 10:56:25 +08:00
khy
61a22cc910 更换框架 2016-11-05 18:52:04 +08:00
7c3a8fda4b 解决downloadOffText从digest中获取的bug,应该从detail中获取 2016-11-05 10:42:20 +08:00
khy
c8ff5bf624 版本升级到2.2 2016-11-04 17:31:15 +08:00
dfd791ffb5 解决handleMessage中getActivity()为null崩溃bug 2016-11-04 17:11:39 +08:00
345800ba25 解决mac为:::::导致的bug 2016-11-04 17:01:20 +08:00
4c3a5492c7 去除Hotfix热更模块 2016-11-04 16:51:09 +08:00
khy
7862426144 光环助手更新数据统计 2016-11-01 09:59:03 +08:00
6e196262a5 10.31 push 2016-10-31 09:57:59 +08:00
11abd6d60f 下载事件统计,添加该游戏已安装数 2016-10-28 11:23:42 +08:00
54df9912eb Merge branch '2.1' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.1 2016-10-28 09:00:14 +08:00
b46e1f3291 解决安装游戏不显示在已安装列表问题 2016-10-28 08:59:53 +08:00
khy
98eb063ea1 增加摘要字段 2016-10-27 19:21:10 +08:00
khy
ac29a19ee8 增加关注资讯摘要判断 2016-10-27 19:12:44 +08:00
khy
553d005ed0 Merge remote-tracking branch 'origin/2.1' into 2.1 2016-10-27 19:01:09 +08:00
khy
96e59d764a 游戏截图支持缩放 2016-10-27 19:00:34 +08:00
cb3c3eb046 更新提示Dialog 修改 2016-10-27 11:45:26 +08:00
8d50f12886 dialog xml 添加白色背景 2016-10-27 10:40:52 +08:00
c8821f2f54 屏蔽“光环助手”游戏 的下载 2016-10-26 18:11:44 +08:00
b3e2f3545d 修复部分bug 2016-10-26 18:03:09 +08:00
383b7bce21 添加防止重复奔溃导致的助手重复重启 2016-10-26 14:59:28 +08:00
ab9a8fd106 修改错误上传逻辑,修改第一次启动判断字段 2016-10-26 10:54:43 +08:00
2954260722 合并 2016-10-25 18:44:01 +08:00
6f78ba604f 添加自动恢复一次下载 2016-10-25 18:21:51 +08:00
4471d95482 文件整理,删除无用资源 2016-10-25 16:39:11 +08:00
khy
929038fc30 更换引导图 2016-10-25 16:30:46 +08:00
khy
c2cf64dfa0 Merge remote-tracking branch 'origin/2.1' into 2.1
# Conflicts:
#	app/src/main/java/com/gh/gamecenter/news/News4Fragment.java
2016-10-25 14:56:42 +08:00
khy
719177b816 初始化关注 2016-10-25 14:50:14 +08:00
190296e533 ... 2016-10-25 11:34:32 +08:00
f1f33112fc Merge branch '2.1' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.1
Conflicts:
	app/src/main/java/com/gh/common/util/DialogUtils.java
	app/src/main/java/com/gh/gamecenter/news/News4Fragment.java
2016-10-25 11:34:00 +08:00
b1fdeeef65 ... 2016-10-25 11:31:42 +08:00
63b8e9551c ... 2016-10-25 11:29:50 +08:00
f6758d4d3a ... 2016-10-25 11:25:06 +08:00
e873b539eb ... 2016-10-25 11:24:31 +08:00
95a3d7b494 ... 2016-10-25 11:23:48 +08:00
1578925613 ... 2016-10-25 11:23:27 +08:00
f3ee2d2cf0 添加downloadOffText,检查下载上传数据是否完整 2016-10-25 09:32:39 +08:00
khy
39d71f3627 优化界面 2016-10-24 17:48:20 +08:00
khy
e52caa013d 优化游戏截图 2016-10-24 10:03:13 +08:00
18d88ab298 Merge branch '2.1' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.1 2016-10-21 18:54:24 +08:00
khy
b768f5f661 优化占位符 2016-10-21 18:47:32 +08:00
b756410982 去除无用import 2016-10-21 18:03:31 +08:00
bcc58481ed Merge branch '2.1' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.1
Conflicts:
	app/src/main/java/com/gh/gamecenter/CropImageActivity.java
	app/src/main/java/com/gh/gamecenter/MainActivity.java
	app/src/main/java/com/gh/gamecenter/news/News4Fragment.java
	app/src/main/java/com/gh/gamecenter/newsdetail/NewsDetailAdapter.java
2016-10-21 18:03:01 +08:00
2c6fd5d0d8 添加BitmapUtils 2016-10-21 17:38:14 +08:00
24238acf0e 检查for循环中的remove,检查response的length != 0 2016-10-21 16:44:40 +08:00
khy
089399307f 取消点击图片背景 2016-10-21 16:13:23 +08:00
khy
385d9155f7 Merge remote-tracking branch 'origin/2.1' into 2.1 2016-10-21 16:09:46 +08:00
khy
6eaef8388b 切换Fresco框架 2016-10-21 16:09:06 +08:00
3100d6aede Merge branch '2.1' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.1 2016-10-20 14:24:17 +08:00
35b62c2bc6 添加安装游戏后检查是否可以进行插件化功能、检查GamEntity getEntryMao方法返回null判断 2016-10-20 14:23:56 +08:00
ded2fcdc7d 添加链接为空的情况处理 2016-10-19 15:22:24 +08:00
0479cfca18 添加链接404 Not Found 处理 2016-10-19 14:16:22 +08:00
4f0a2dd3c8 插件化判断修改 2016-10-19 11:49:17 +08:00
khy
e082ad97ac 增加打开QQ临时会话Dialog 2016-10-19 11:33:41 +08:00
40d8f17ce7 统一ITEM TYPE 2016-10-19 10:58:48 +08:00
khy
140f876164 资讯-关注,推荐关注小版块功能更改(推荐关注游戏改为已安装的游戏+光环助手) 2016-10-18 09:29:18 +08:00
khy
5fa0fa8d17 Merge branch '2.1' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.1 2016-10-17 10:53:14 +08:00
da8ac35932 解决搜索的游戏无apk还显示下载按钮的问题 2016-10-16 09:25:10 +08:00
9e6491b86b 去除无用import 2016-10-14 18:45:22 +08:00
fcdb0e3d80 解决recommendGameList为null奔溃bug 2016-10-14 18:36:55 +08:00
e42e4ee96d Merge branch '2.1' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.1 2016-10-14 18:28:07 +08:00
a9d42403d9 我的关注热门游戏推荐添加已安装但未关注的游戏推荐 2016-10-14 18:27:53 +08:00
561dd33044 解决两个游戏具有相同包名apk导致的问题 2016-10-13 18:14:30 +08:00
khy
c5618bb3db 资讯列表,大图布局调整 2016-10-13 18:05:58 +08:00
khy
d9f5ba517d 调整资讯-关注-推荐小版块布局 2016-10-13 15:25:27 +08:00
054ceda63a 修改时间戳添加方式 2016-10-13 11:07:17 +08:00
ad0efd98ff 更换获取更新接口 2016-10-13 10:59:08 +08:00
khy
f0b473db2c issues97:资讯-关注的内容为空时,增加推荐关注的小板块 2016-10-12 18:54:18 +08:00
58324c5d24 添加批量添加关注方法 2016-10-12 18:33:44 +08:00
82d960c586 添加点击"下载中"跳转到下载管理定位到相应位置 2016-10-11 16:48:19 +08:00
ec9219ac7f 修改暂停的下载也算下载 2016-10-11 14:41:59 +08:00
28e7bd5304 统一HOST版本号 2016-10-11 11:35:12 +08:00
4e4c2cd788 统一USER_HOST 2016-10-11 10:46:55 +08:00
896c4e980c 添加下载状态通知功能 2016-10-11 10:07:04 +08:00
4262ec7386 非插件游戏不显示platform 2016-10-10 16:35:40 +08:00
08744c55ce 退出时,添加检查是否有已下载完成游戏,有则提示安装 2016-10-10 15:32:16 +08:00
6031161452 添加游戏下载的开始时间和完成时间 2016-10-10 15:08:12 +08:00
55c657aba6 资讯-关注图片添加点击事件,点击缩略图是直接全屏查看大图 2016-10-10 11:51:37 +08:00
c4e01140a2 解决反馈重复发送问题 2016-10-10 09:43:48 +08:00
c9cdf51b51 2.1正式开始 2016-10-09 15:57:24 +08:00
de3ab708e9 2.0正式封包 2016-10-09 15:18:33 +08:00
52f2dd22f2 统计下载出错log 2016-10-09 15:18:32 +08:00
8aa90935d8 解决上传头像文件时服务器返回403抛异常无法获取返回流问题 2016-10-09 15:18:17 +08:00
b8ae608d79 解决新闻详情点击分享图标奔溃问题 2016-10-09 15:18:16 +08:00
15070aab45 解决测试标签溢出换行问题 2016-10-09 15:18:16 +08:00
khy
9fb2da406a 优化https下载 2016-10-08 17:10:58 +08:00
khy
4488726b12 Merge remote-tracking branch 'origin/2.1' into 2.1 2016-10-08 14:36:58 +08:00
khy
6ade459c40 https忽略证书认证 2016-10-08 14:36:21 +08:00
47914f94ac 修复部分bug 2016-09-29 18:32:55 +08:00
e5e6a07e24 下载按钮修改为默认开 2016-09-29 09:41:19 +08:00
dda8fe032c 多页加载数据的页面,添加去除重复数据机制 2016-09-28 19:30:31 +08:00
09a0eabc48 url添加Timestamp逻辑修改 2016-09-28 18:47:14 +08:00
6546b580e9 增加打包渠道 2016-09-28 17:57:15 +08:00
93521840bc 数据收集添加device_id字段 2016-09-28 17:56:38 +08:00
5f2b84d88c 更换检查更新接口和控制下载按钮状态接口 2016-09-28 17:55:25 +08:00
794784e253 2.1正式开始 2016-09-28 08:47:51 +08:00
96bfeda954 2.0正式封包 2016-09-28 08:42:13 +08:00
ada909ec8a 下载被删除事件逻辑判断修改 2016-09-27 18:28:00 +08:00
5064a76aa5 DownloadDialog整理 2016-09-27 18:23:05 +08:00
20cc2f478f 我的光环,无安装、无关注时页面显示逻辑修改 2016-09-26 22:35:31 +08:00
f818e4033d notifyItemRemoved、notifyItemInserted使用检查 2016-09-26 22:07:45 +08:00
0736fc6b91 plugin、subject页面添加监听下载被删除事件 2016-09-26 19:05:37 +08:00
7bef401e6a 屏蔽删除下载时的notifyItemRemoved,该为notifyDataSetChanged 2016-09-26 18:32:47 +08:00
ea51e5e443 解决推送新闻崩溃问题 2016-09-26 18:24:19 +08:00
eccc0eb167 2.1版本开始 2016-09-26 16:55:09 +08:00
afa3f1d705 2.0封包 2016-09-26 16:23:59 +08:00
ce94de1214 MainActivity整理 2016-09-24 18:34:47 +08:00
3d3b596962 广播跳转助手逻辑修改 2016-09-24 16:50:50 +08:00
b42e0df218 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0
Conflicts:
	app/src/main/java/com/gh/gamecenter/MainActivity.java
	app/src/main/java/com/gh/gamecenter/receiver/ActivitySkipReceiver.java
2016-09-24 15:57:21 +08:00
7da78b6e4a 插件化安装按钮显示背景修改,下载添加是否是插件字段 2016-09-24 15:55:03 +08:00
khy
0b63f8d4a2 Merge remote-tracking branch 'origin/2.0' into 2.0 2016-09-24 15:18:07 +08:00
khy
1aa9ddbb48 微调布局 2016-09-24 15:16:03 +08:00
5e44460112 处理下载网络异常导致的奔溃问题,和奔溃后进入助手下载状态显示错误问题 2016-09-23 18:14:20 +08:00
39350b2cfb 去掉MainActivity的entryMap、uninstallMap,使用下载是添加packageNam来进行获取DownloadEntity 2016-09-23 14:49:44 +08:00
154f7b5a54 已安装游戏判断空逻辑修改,修复RecyclerView的Inconsistency detected.问题 2016-09-22 22:43:28 +08:00
94adc2c922 启动页面图片替换,启动页面修改,修复部分问题 2016-09-22 19:06:38 +08:00
80e8ca0c36 解决冲突 2016-09-22 08:56:11 +08:00
358a3f84e6 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0
Conflicts:
	app/src/main/java/com/gh/gamecenter/PluginActivity.java
	app/src/main/java/com/gh/gamecenter/adapter/PluginAdapter.java
2016-09-22 08:55:53 +08:00
7629d9f429 修改插件化界面获取插件化游戏逻辑 2016-09-21 22:02:48 +08:00
da87e974f4 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0 2016-09-21 18:48:44 +08:00
6cd2397b27 修改下载统计事件的entrance 2016-09-21 18:48:26 +08:00
khy
d053fc9fea 微调布局 2016-09-21 18:26:32 +08:00
khy
979a4b808b Merge remote-tracking branch 'origin/2.0' into 2.0 2016-09-21 16:28:58 +08:00
khy
bdfda12d68 增加接受插件广播的接收器 2016-09-21 16:28:25 +08:00
c8211dbdd8 修改Queue的TAG为static fianl 对象(cancelQueue中判断的条件为TAG为统一对象才可取消) 2016-09-21 14:16:50 +08:00
4a0332a948 去除无用import 2016-09-21 09:00:08 +08:00
c17f13d467 去除无用import 2016-09-21 08:59:49 +08:00
khy
9efa6f163d DetailActivity 添加QQ分享回调 2016-09-20 18:49:40 +08:00
khy
560dee201f Merge remote-tracking branch 'origin/2.0' into 2.0
# Conflicts:
#	app/src/main/java/com/gh/gamecenter/GameDetailActivity.java
2016-09-20 18:36:56 +08:00
khy
f6371537ed QQ 和 微信分享添加回调 ,Issue #79 分享功能问题汇总(2) 2016-09-20 18:34:09 +08:00
5a31813a45 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0 2016-09-20 18:29:35 +08:00
384af8a9db 细节修复、部分bug修复 2016-09-20 18:29:19 +08:00
khy
186f594d1d Merge remote-tracking branch 'origin/2.0' into 2.0 2016-09-20 11:17:58 +08:00
khy
497cd6a494 解决微信分享图片太大无法分享和出现黑框问题,优化界面 2016-09-20 11:17:40 +08:00
471afcf0be 去处无用import 2016-09-19 22:29:25 +08:00
8724d3eff7 统一新闻详情底部栏——DetailActivity 2016-09-19 22:28:10 +08:00
29ba7a512e 细节修复、部分bug修复 2016-09-19 18:53:04 +08:00
9fbd5ee72b 去除无用资源 2016-09-19 15:31:54 +08:00
ed867884b0 登录后才能修改昵称、头像 2016-09-19 13:32:15 +08:00
8019b22fc4 添加第一次启动注册设备 2016-09-19 13:26:34 +08:00
0bcef534d0 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0
Conflicts:
	app/src/main/java/com/gh/common/util/TokenUtils.java
2016-09-19 13:25:54 +08:00
69033c0657 修复插件化问题 2016-09-19 13:07:47 +08:00
khy
63c86bbacb 优化存储和获取DeviceID 2016-09-19 12:00:20 +08:00
khy
251e19d751 Merge remote-tracking branch 'origin/2.0' into 2.0 2016-09-19 09:52:51 +08:00
khy
12279501b4 布局优化,存储和获取DeviceID 2016-09-19 09:52:08 +08:00
3c512273f0 游戏详情添加开服信息 2016-09-18 18:20:57 +08:00
597651248a 解决小米4无法画间隔问题 2016-09-18 16:57:13 +08:00
a80c577f1f 添加修改用户头像,昵称 2016-09-18 11:57:01 +08:00
a09c8e329a Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0 2016-09-14 20:22:38 +08:00
2174451e97 修改用户头像为CircleImageView 2016-09-14 20:22:22 +08:00
khy
ee562eb3b7 修改属性名 2016-09-14 18:00:20 +08:00
khy
03e05b3e35 Merge remote-tracking branch 'origin/2.0' into 2.0
# Conflicts:
#	app/src/main/java/com/gh/gamecenter/GameDetailActivity.java
#	app/src/main/java/com/gh/gamecenter/NewsDetailActivity.java
#	app/src/main/res/layout/gamedetail_item_top.xml
2016-09-14 17:56:32 +08:00
khy
385a206f6b 增加QQ,微信独立分享,界面优化 2016-09-14 17:46:18 +08:00
202a78526c 安装完游戏自动关注游戏 2016-09-14 17:21:29 +08:00
eb7fe78410 搜索数据收集 2016-09-14 16:31:28 +08:00
e0f79490eb 劫持数据上传、删除Concern...Request.java 2016-09-14 15:59:18 +08:00
1acf79baae 数据收集createdOn时间获取修改、添加game_id字段(在有game字段的地方) 2016-09-14 11:43:39 +08:00
405056cbd3 新闻详情整理、我的光环界面修改 2016-09-13 18:48:30 +08:00
fc68b9add5 DownloadEntry修改为DownloadEntity 2016-09-13 07:23:02 +08:00
d95d5d5e6b 添加安装、卸载游戏处理 2016-09-09 19:52:53 +08:00
69d86affd0 解决合并后的bug 2016-09-09 18:31:02 +08:00
9f5374f4fd Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0
Conflicts:
	app/src/main/java/com/gh/gamecenter/NewsDetailActivity.java
	app/src/main/res/drawable/progressbar_normal_radius_style.xml
	app/src/main/res/layout/fragment_news.xml
	app/src/main/res/layout/plugin_container_fragments.xml
2016-09-09 18:27:32 +08:00
f858ba0b70 整理 2016-09-09 18:23:54 +08:00
khy
b9a2374f8f Issue :游戏详情-插件介绍显示优化 2016-09-09 16:47:22 +08:00
khy
73c0af47db Merge remote-tracking branch 'origin/2.0' into 2.0
# Conflicts:
#	app/src/main/java/com/gh/gamecenter/GameDetailsActivity.java
#	app/src/main/java/com/gh/gamecenter/NewsDetailActivity.java
2016-09-09 10:34:21 +08:00
khy
72f62b595d Issue 68:游戏详情优化汇总 2016-09-09 10:30:14 +08:00
5316164f00 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0 2016-09-09 08:28:49 +08:00
a14646d2e2 游戏详情、新闻详情下载按钮的修改 2016-09-09 08:28:24 +08:00
1135334a95 资讯-关注页面整理 2016-09-08 22:24:03 +08:00
5462167d85 gamedetails_item_loading修改为gamedetail_item_loading 2016-09-08 18:50:33 +08:00
b7c3856785 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0 2016-09-08 18:48:56 +08:00
92ad0838e7 游戏详情整理、Config.isShow()修改 2016-09-08 18:48:22 +08:00
khy
ae405d54d5 修改轮播图点的选中颜色 2016-09-08 16:50:38 +08:00
khy
d9ea9cf1ba Merge remote-tracking branch 'origin/2.0' into 2.0
# Conflicts:
#	app/src/main/res/drawable-hdpi/home1_selected.png
#	app/src/main/res/drawable-hdpi/home1_unselected.png
#	app/src/main/res/drawable-hdpi/home2_selected.png
#	app/src/main/res/drawable-hdpi/home2_unselected.png
#	app/src/main/res/drawable-hdpi/home3_selected.png
#	app/src/main/res/drawable-hdpi/home3_unselected.png
#	app/src/main/res/drawable/oval_hint_dn.xml
#	app/src/main/res/drawable/oval_hint_up.xml
#	app/src/main/res/layout/activity_main.xml
2016-09-08 16:46:13 +08:00
khy
5c4a65d278 Issue UI优化汇总完成 2016-09-08 16:37:32 +08:00
cbc543b981 修改多版本下载时,使用移动网络的提示方式 2016-09-08 11:05:56 +08:00
a22f59aab6 去掉setClickable 2016-09-08 09:19:12 +08:00
9b7c5e7756 去掉setClickable 2016-09-08 09:18:42 +08:00
e2591a54d6 DataWatcher修改 2016-09-08 09:11:22 +08:00
9180089787 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0 2016-09-07 18:52:30 +08:00
bd892a4cf1 解决final int position导致的bug 2016-09-07 18:52:21 +08:00
khy
1dd895ebef 修复微信好友和微信朋友圈无法分享问题(正式打包生效) 2016-09-07 18:17:22 +08:00
khy
c416adc980 Merge remote-tracking branch 'origin/2.0' into 2.0 2016-09-07 11:29:59 +08:00
khy
6737b17e43 修正游戏和新闻大图显示不全问题 2016-09-07 11:27:48 +08:00
3300d61a53 修改下载管理相关文件名、修复查看大图单击无法退出问题、资讯-攻略去重导致的奔溃bug 2016-09-07 11:23:27 +08:00
defbbc7b44 资讯-关注添加阅读量 2016-09-07 09:50:04 +08:00
a77e1ebf61 搜索为空提示修改、排序数字居中修改 2016-09-06 18:35:59 +08:00
6834be0909 合并 2016-09-06 18:21:27 +08:00
9d3640f6b9 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0
Conflicts:
	app/src/main/java/com/gh/gamecenter/GameDetailsActivity.java
2016-09-06 18:21:13 +08:00
4e392eeb14 根据issues整理项目 2016-09-06 18:15:41 +08:00
khy
4ce778f76f 修复下载BUG,修复资讯-关注BUG,修改游戏详情-资讯攻略标签背景 2016-09-06 17:49:46 +08:00
khy
160bb20eed Merge remote-tracking branch 'origin/2.0' into 2.0 2016-09-06 10:24:19 +08:00
khy
27c73369da 分享文案修改 2016-09-06 10:23:01 +08:00
6cbb033326 统一gameMap、statusMap 2016-09-05 18:57:16 +08:00
khy
bfd31516ba 分享模块,下载合集微调 2016-09-05 11:14:24 +08:00
da664e5869 文件整理、修改 2016-09-04 18:35:43 +08:00
cae1f78025 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0 2016-09-02 18:46:12 +08:00
8b282eaf8a 文件整理、修改 2016-09-02 18:40:45 +08:00
b5b65ecd41 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0
Conflicts:
	app/src/main/res/drawable/oval_hint_up.xml
	app/src/main/res/layout/game_download_dialog.xml
2016-09-02 18:38:36 +08:00
khy
87b47a9c31 下载合集 修改二级版本背景,微调布局 2016-09-02 18:11:48 +08:00
6dd0c75cdc 文件整理 2016-09-02 17:14:05 +08:00
khy
5f3f2139c1 下载合集删除无用Log 2016-09-02 17:05:22 +08:00
khy
ef97c913cf 下载合集 2016-09-02 16:57:20 +08:00
b1df05ea47 合并后解决冲突、bug 2016-08-31 14:57:45 +08:00
a270946ce2 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0
Conflicts:
	app/src/main/java/com/gh/common/util/ImageUtils.java
	app/src/main/java/com/gh/gamecenter/GameDetailsActivity.java
	app/src/main/java/com/gh/gamecenter/game/Game1FragmentAdapter.java
	app/src/main/java/com/gh/gamecenter/game/GameListAdapter.java
	app/src/main/java/com/gh/gamecenter/game/NewGame2FragmentAdapter.java
	app/src/main/java/com/gh/gamecenter/gamedetails/GameDetailsFragment.java
	app/src/main/java/com/gh/gamecenter/gamedetails/GameInformationFragment.java
	app/src/main/java/com/gh/gamecenter/gamedetails/GameStrategyFragment.java
	app/src/main/res/drawable/border_white_bg.xml
	app/src/main/res/layout/game_news_type_list_item.xml
	app/src/main/res/layout/home_consolegame_item.xml
	app/src/main/res/layout/home_game_test_item.xml
2016-08-31 14:46:50 +08:00
efc19441cd 文件整理 2016-08-31 14:41:42 +08:00
khy
803ec482fb 合集 2016-08-31 14:33:10 +08:00
khy
dac71dfd55 游戏新闻,游戏新闻搜索 2016-08-31 14:32:09 +08:00
khy
85b7ebdcc7 Merge remote-tracking branch 'origin/2.0' into 2.0
# Conflicts:
#	app/src/main/AndroidManifest.xml
#	app/src/main/java/com/gh/gamecenter/GameDetailsActivity.java
#	app/src/main/java/com/gh/gamecenter/NewGameDetailsActivity.java
2016-08-31 14:24:53 +08:00
khy
800bc52c0e 游戏-插件,推荐 卡片化。删除旧版游戏详情 2016-08-30 11:35:33 +08:00
d4498fb573 修改提示文本 2016-08-29 18:28:04 +08:00
2bd6c38bf6 游戏新闻界面,去除无用import 2016-08-29 18:05:39 +08:00
5dfbfe6cf5 主页底部按钮修改 2016-08-29 15:24:58 +08:00
f47768b8db 游戏详情页面和新闻详情页面下载进度条去掉暂停继续等操作,变为下载中,直接跳转到下载管理页面 2016-08-29 15:14:11 +08:00
2ba951bb42 Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0 2016-08-29 14:27:55 +08:00
39733689c6 提示文本修改 2016-08-29 14:27:42 +08:00
khy
c97bdbe203 关注BUG修改 2016-08-29 14:25:10 +08:00
6cfe7ff889 解决下载管理页面点击删除游戏报错 2016-08-29 13:54:34 +08:00
d5763ddbd6 解决合并产生的bug 2016-08-29 12:26:20 +08:00
khy
59ac399f9e 合并 2016-08-29 12:16:41 +08:00
khy
094a96ab78 关注模块,游戏推荐,资讯-关注,全部资讯,新闻搜索 2016-08-29 12:03:08 +08:00
26b5d00a72 主页图标替换 2016-08-29 11:59:24 +08:00
74e281b0c4 合并后解决错误代码 2016-08-29 11:28:23 +08:00
c6bd6e4b0c Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0
Conflicts:
	app/src/main/java/com/gh/common/util/DialogUtils.java
2016-08-29 10:38:05 +08:00
e3fc761414 游戏-插件页面,未完成 2016-08-29 10:28:33 +08:00
khy
16a65ffa93 游戏详情页面(包括关注工具类) 2016-08-27 18:44:36 +08:00
khy
63f0b0528c 修改弹窗样式(下载提示,插件化安装,正文字号,意见反馈,网络劫持,清除缓存) 2016-08-27 18:17:40 +08:00
khy
000c97881c 资讯,原创页面卡片化,修改新闻类型背景 2016-08-27 17:55:30 +08:00
20e9fcf172 设置界面的switchbutton修改 2016-08-18 15:29:02 +08:00
04851d5df3 设置界面增加 "一键修复下载" 按钮 2016-08-18 12:00:37 +08:00
9c29be3378 意见反馈界面修改 2016-08-18 11:59:56 +08:00
9d1c5a1184 重命名SearchListViewHolder为CardListViewHolder 2016-08-18 10:55:08 +08:00
56f7fd9a31 资讯攻略界面修改 2016-08-18 10:53:10 +08:00
8d9d28e1c9 重命名resue_actionbar.xml 为 reuse_actionbar.xml 2016-08-17 14:14:11 +08:00
47a14dfd40 搜索界面修改 2016-08-17 14:11:15 +08:00
9d0e0f4f2d 圆角角度修改,新增暂停、插件化中等样式 2016-08-16 15:55:01 +08:00
2543736e82 下载管理界面修改 2016-08-16 15:53:44 +08:00
84f8008167 下载进度条显示时,不隐藏标签列表,隐藏des内容 2016-08-15 15:12:04 +08:00
11676bff83 修改代码格式 2016-08-15 15:10:05 +08:00
a7c9ec51ed Merge branch '2.0' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 2.0 2016-08-15 14:21:22 +08:00
d077b6d880 下载显示逻辑修改(去掉继续、暂停,变为下载中,点击跳转下载管理页面),添加下载按钮样式 2016-08-15 14:21:10 +08:00
4ce9e8be3f 修改我的光环界面 2016-08-15 14:17:41 +08:00
khy
b2ee32b4ab 修改设置页面,更改提示更新app弹窗(ps:还有新闻详情页面分享按钮图片) 2016-08-14 16:40:39 +08:00
khy
0b705bd311 更改新闻详情页面 2016-08-14 16:34:34 +08:00
9ae9f307bc 修改首页actionbar 2016-08-12 10:16:48 +08:00
khy
83cbb60cb7 关注页面弹窗样式修改 2016-08-12 10:00:14 +08:00
khy
43d476786f 增加cardview框架,SDK版本提升到21,修改单机页面,修改游戏标签样式,修改下载进度条 圆角变直角 2016-08-12 09:52:07 +08:00
322f13072c 删除Trace,Utils增加log方法 2016-08-12 09:43:20 +08:00
khy
0861208b64 其他APP 跳转到光环助手某个页面 2016-08-12 09:33:57 +08:00
e08b9469d0 去除无用import 2016-08-11 14:16:53 +08:00
c9a7379847 修改log输出方式 - 剩余处理 2016-08-11 14:16:18 +08:00
b211d15b17 修改log输出方式 2016-08-11 14:10:41 +08:00
99cfa2080f 打开调试开关、修改ImageUtils错误参数bug、修改版本号为2.0 2016-08-11 09:15:33 +08:00
39fecb09a7 注释掉域名解析代码、修改.gitignore文件(添加忽略misc.xml文件) 2016-08-01 10:04:41 +08:00
42cbb4f6ec 修改游戏详情退出后奔溃bug 2016-07-25 18:32:05 +08:00
335dac3481 修改资讯-关注无游戏奔溃bug 2016-07-25 17:56:34 +08:00
24014feef0 修改渠道为GH_TEST,去除无用import 2016-07-22 14:23:01 +08:00
f74ae2a8cf 修改插件化提示框显示位置为所有界面,修复卸载后不自动跳安装bug,修复下载量超100%bug,添加打包渠道106 2016-07-22 13:57:11 +08:00
8eca878a8b Merge branch '1.50' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 1.50 2016-07-19 19:03:54 +08:00
khy
33ce47b438 调整游戏模块布局,搜索框索引优化 2016-07-19 19:03:17 +08:00
d2702c9d4a 游戏接口添加timestamp 2016-07-19 17:33:57 +08:00
cbc7a144a4 添加点击事件统计 2016-07-19 17:06:44 +08:00
a9f078865e 压缩启动图 2016-07-19 16:28:42 +08:00
khy
18330df2f0 修改主页轮播点的位置以及大小,修改引导页的启动模式 2016-07-19 16:02:52 +08:00
b0e401bbbd bug修复 2016-07-19 11:04:56 +08:00
1b03e434a7 合并后代码恢复 2016-07-19 09:56:03 +08:00
87c5c5a0d8 Merge branch '1.50' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 1.50
Conflicts:
	app/src/main/java/com/gh/gamecenter/game/Game1FragmentAdapter.java
2016-07-19 09:53:40 +08:00
b915ea01be 专题数据处理 2016-07-19 09:42:06 +08:00
khy
f0f12cf8ff 专题列表增加上拉加载,资讯大图处理,游戏列表优化 2016-07-18 18:27:36 +08:00
303f5b8f58 搜索数据实时上传 2016-07-15 19:14:06 +08:00
bff4d80c27 添加点击新闻-阅读统计 2016-07-15 19:04:16 +08:00
7cbdf69188 2016-07-15 17:56:45 +08:00
58c6a9a5d5 Merge branch '1.50' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 1.50 2016-07-15 15:58:13 +08:00
khy
e0c08e94f3 调整游戏模块布局,搜索框索引优化 2016-07-15 15:38:51 +08:00
15ad3e7d39 修改插件化全部提示逻辑 2016-07-15 15:37:47 +08:00
khy
4ce8d1ea95 修改游戏-插件页面主题名称变色BUG 2016-07-14 15:48:29 +08:00
khy
37af534904 Merge remote-tracking branch 'origin/1.50' into 1.50
# Conflicts:
#	app/src/main/java/com/gh/gamecenter/game/Game1FragmentAdapter.java
2016-07-13 17:39:18 +08:00
khy
8de6a6a789 首页游戏页面布局结构修改,修复HttpDns解析失败无法下载BUG 2016-07-13 17:38:31 +08:00
e033e20dbf 修复单机游戏apk为null奔溃bug 2016-07-12 11:10:57 +08:00
42d0d9c60b 资讯-关注中我的游戏跳转到游戏详情的资讯页面 2016-07-11 18:56:54 +08:00
5559a47f80 Merge branch '1.50' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 1.50 2016-07-11 18:43:55 +08:00
c37c50d0c1 修改插件提示逻辑问题 2016-07-11 18:43:22 +08:00
khy
5b5341f9e1 细节优化,关注右侧增加箭头,关注底部按钮修改样式 2016-07-11 18:28:13 +08:00
khy
848b4e44d5 Merge remote-tracking branch 'origin/1.50' into 1.50
# Conflicts:
#	app/src/main/java/com/gh/gamecenter/NewsActivity.java
2016-07-11 17:29:00 +08:00
khy
fa6cc8dfaf 增加 正文字号设置,加载Gif,Httpdns防止网络劫持,游戏截图横屏修改 2016-07-11 17:26:40 +08:00
3c83b4ad5c 资讯模块、整理完成 2016-07-08 14:10:45 +08:00
6c3e042edc 游戏模块,整理完成 2016-07-07 14:59:23 +08:00
4feff1600e 优化dialog,统一dialog显示 2016-07-06 11:16:37 +08:00
e7f510941f 修改HotcardAdapter为SubjectAdapter 2016-07-06 10:01:54 +08:00
2a4c8a01b9 统一viewholder 2016-07-06 09:52:32 +08:00
b3d6148c8c Merge branch '1.47' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 1.47
Conflicts:
	app/src/main/java/com/gh/gamecenter/game/Game2FragmentAdapter.java
2016-07-06 09:52:15 +08:00
d4dac2d681 。。。 2016-07-06 09:46:26 +08:00
02599ad7cc 忽略/.idea文件夹下的文件 2016-07-06 09:40:54 +08:00
bb790ad579 去除无用import 2016-07-06 09:38:36 +08:00
6ec976ccb6 项目整理 2016-07-06 09:37:33 +08:00
khy
84c30364fc Merge remote-tracking branch 'origin/1.47' into 1.47 2016-07-06 09:16:31 +08:00
khy
8df31781e9 游戏-推荐 对接接口 2016-07-06 09:15:04 +08:00
380d38073e 修改版本代号 2016-07-04 09:46:50 +08:00
78e295ce7e 游戏-推荐点击更多事件 2016-07-02 19:14:19 +08:00
627a896ddb 删除无用文件,游戏-插件集成下载模块、更多模块,屏蔽gif代码 2016-07-02 18:47:20 +08:00
khy
929f12fa18 游戏-推荐 添加列表排序 2016-07-02 11:46:50 +08:00
c0550746b1 去除无用import 2016-07-01 17:43:28 +08:00
602c30d87c Merge branch '1.47' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 1.47 2016-07-01 17:39:54 +08:00
e7ff7a3083 ... 2016-07-01 17:37:41 +08:00
d86155383b 游戏-插件、资讯-关注、资讯顶部栏 2016-07-01 17:34:27 +08:00
khy
4074ae5452 游戏-推荐 添加动态数据 2016-07-01 17:32:35 +08:00
bf87e7187d Merge branch '1.47' of https://git.oschina.net/dreamhua/GH-ASSISTv1.45 into 1.47 2016-07-01 08:55:45 +08:00
5c09b03d60 启动界面修改 2016-07-01 08:55:10 +08:00
khy
b3b7641959 修改游戏模块以及资讯模块 2016-06-30 17:57:14 +08:00
b0a9a52288 修改原创刷新退出奔溃bug 2016-06-30 17:08:39 +08:00
35a915dda1 修改游戏详情退出奔溃bug 2016-06-30 17:01:12 +08:00
1210911a3a 打开调试开关,删除README.md,打开多渠道打包 2016-06-30 16:59:53 +08:00
khy
b7bc0efe28 设置正文字体大小,在新闻详情手势改变字体大小 2016-06-27 10:21:21 +08:00
khy
b31131a00b 加载GIF的配置文件 2016-06-27 10:17:21 +08:00
khy
228d0394c3 加载GIF 2016-06-27 09:55:27 +08:00
798 changed files with 36071 additions and 39868 deletions

6
.gitignore vendored
View File

@ -1,8 +1,8 @@
/.idea
.idea/misc.xml
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
/captures

4
.idea/gradle.xml generated
View File

@ -10,16 +10,12 @@
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/buildSrc" />
<option value="$PROJECT_DIR$/hackdex" />
</set>
</option>
<option name="myModules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/buildSrc" />
<option value="$PROJECT_DIR$/hackdex" />
</set>
</option>
</GradleProjectSettings>

2
.idea/misc.xml generated
View File

@ -37,7 +37,7 @@
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">

2
.idea/modules.xml generated
View File

@ -4,8 +4,6 @@
<modules>
<module fileurl="file://$PROJECT_DIR$/GH-ASSISTv1.45.iml" filepath="$PROJECT_DIR$/GH-ASSISTv1.45.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/buildSrc/buildSrc.iml" filepath="$PROJECT_DIR$/buildSrc/buildSrc.iml" />
<module fileurl="file://$PROJECT_DIR$/hackdex/hackdex.iml" filepath="$PROJECT_DIR$/hackdex/hackdex.iml" />
</modules>
</component>
</project>

View File

@ -1 +0,0 @@
#GH-ASSISTv1.45

View File

@ -1,45 +1,15 @@
apply plugin: 'com.android.application'
task('processWithJavassist') << {
String classPath = file('build/intermediates/classes/debug')//项目编译class所在目录
dodola.patch.PatchClass.process(classPath, project(':hackdex').buildDir
.absolutePath + '/intermediates/classes/debug')//第二个参数是hackdex的class所在目录
}
task buildJar(dependsOn: ['compileReleaseJavaWithJavac'], type: Jar) {
baseName = "news"
//后缀名
extension = "jar"
//最终的 Jar 包名,如果没设置,默认为 [baseName]-[appendix]-[version]-[classifier].[extension]
archiveName = "news.jar";
//需打包的资源所在的路径集
def srcClassDir = [project.buildDir.absolutePath + "/intermediates/classes/debug"];
from srcClassDir
//去除路径集下部分的资源
exclude "com/gh/gamecenter/BuildConfig.class"
exclude "com/gh/gamecenter/R.class"
exclude "com/gh/gamecenter/BuildConfig/\$*.class"
exclude "com/gh/gamecenter/R/\$*.class"
//只导入资源路径集下的部分资源
include "com/gh/gamecenter/NewsActivity.class"
include "com/gh/gamecenter/NewsActivity\$*.class"
//注: exclude include 支持可变长参数
}
android {
compileSdkVersion 19
compileSdkVersion 21
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.gh.gamecenter"
minSdkVersion 14
targetSdkVersion 19
versionCode 12
versionName "1.46"
targetSdkVersion 21
versionCode 17
versionName "2.2"
// 默认的渠道
// manifestPlaceholders = [CHANNEL_VALUE: "GH_TEST"]
@ -65,31 +35,93 @@ android {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
// signingConfig signingConfigs.release
signingConfig signingConfigs.release
}
}
// applicationVariants.all { variant ->
// variant.dex.dependsOn << processWithJavassist //在执行dx命令之前将代码打入到class中
// }
/**
* 渠道打包
* 渠道打包
*/
// productFlavors {
// "GH_200"{
// manifestPlaceholders = [CHANNEL_VALUE: "GH_200"]
// }
// }
// productFlavors {
// GH_200 {}
// }
// productFlavors.all { flavor ->
// flavor.manifestPlaceholders = [CHANNEL_VALUE: name]//命令 gradlew assembleRelease
// }
productFlavors {
GH_100 {}
GH_101 {}
GH_102 {}
GH_103 {}
GH_104 {}
GH_106 {}
GH_107 {}
GH_108 {}
GH_109 {}
GH_110 {}
GH_111 {}
GH_113 {}
GH_114 {}
GH_115 {}
GH_116 {}
GH_117 {}
GH_118 {}
GH_119 {}
GH_120 {}
GH_121 {}
GH_123 {}
GH_127 {}
GH_200 {}
GH_201 {}
GH_202 {}
GH_203 {}
GH_204 {}
GH_205 {}
GH_222 {}
GH_307 {}
GH_TEST {}
}
productFlavors.all { flavor ->
flavor.manifestPlaceholders = [CHANNEL_VALUE: name]//命令 gradlew assembleRelease
}
}
//butterknife
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
apply plugin: 'com.neenbedankt.android-apt'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:21.0.0'
compile 'com.android.support:cardview-v7:21.0.0'
// fresco图片框架
compile 'com.facebook.fresco:fresco:0.12.0'
compile 'com.facebook.fresco:animated-gif:0.12.0'
// Retrofit2所需要的包
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
// okhttp
compile 'com.squareup.okhttp3:okhttp:3.2.0'
// ConverterFactory的Gson依赖包
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
// ConverterFactory的String依赖包
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'
// ConverterFactory的RxJava依赖包
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
// gson
compile 'com.google.code.gson:gson:2.8.0'
// OrmLite数据库
compile 'com.j256.ormlite:ormlite-android:5.0'
compile 'com.j256.ormlite:ormlite-core:5.0'
// butterknife
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
// RxJava && RxAndroid
compile 'io.reactivex:rxandroid:1.1.0'
compile 'io.reactivex:rxjava:1.1.0'
// RxBinding
compile 'com.jakewharton.rxbinding:rxbinding:0.3.0'
// compile 'com.jakewharton.rxbinding:rxbinding-appcompat-v7:0.3.0'
// compile 'com.jakewharton.rxbinding:rxbinding-design:0.3.0'
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
app/libs/libammsdk.jar Normal file

Binary file not shown.

BIN
app/libs/open_sdk_r5756.jar Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -38,15 +38,6 @@
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<!-- 小米推送需要的权限 -->
<uses-permission android:name="com.gh.gamecenter.permission.MIPUSH_RECEIVE" />
<!-- 添加权限 -->
<!-- 允许程序发送SMS短信 -->
<uses-permission android:name="android.permission.SEND_SMS" />
<!-- 允许程序监控一个将收到短信息,记录或处理 -->
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<!-- 允许程序读取短信息 -->
<uses-permission android:name="android.permission.READ_SMS" />
<!-- 请求访问使用照相设备 -->
<uses-permission android:name="android.permission.CAMERA" />
<permission
android:name="com.gh.gamecenter.permission.MIPUSH_RECEIVE"
@ -61,7 +52,6 @@
<application
android:name="com.gh.base.AppController"
android:allowBackup="true"
android:icon="@drawable/logo"
android:label="@string/app_name"
android:theme="@style/AppThemeNormal" >
@ -71,7 +61,8 @@
android:value="81DB144D555386A38A70B833537EC256" />
<meta-data
android:name="TD_CHANNEL_ID"
android:value="GH_200" />
android:value="${CHANNEL_VALUE}"/>
<!--android:value="${CHANNEL_VALUE}"-->
<!-- MTA -->
<meta-data
@ -79,7 +70,8 @@
android:value="APV567FTBS7J"/>
<meta-data
android:name="InstallChannel"
android:value="GH_127"/>
android:value="${CHANNEL_VALUE}"/>
<!--android:value="${CHANNEL_VALUE}"-->
<activity
android:name="com.gh.gamecenter.SplashScreenActivity"
@ -93,6 +85,74 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.gh.gamecenter.MainActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustResize"/>
<activity
android:name="com.gh.gamecenter.DownloadManagerActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.ViewImageActivity"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />
<activity
android:name="com.gh.gamecenter.SearchActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name="com.gh.gamecenter.GameDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.NewsDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SettingActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SuggestionActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name="com.gh.gamecenter.ConcernActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SubjectActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.PluginActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.NewsSearchActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.GameNewsActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.CropImageActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.WebActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.ShareCardPicActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.ShareCardActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.MessageDetailActivity"
android:screenOrientation="portrait"/>
<activity android:name="com.gh.gamecenter.SkipActivity"
android:theme="@android:style/Theme.Translucent">
<intent-filter>
<data android:scheme="ghzhushou"/>
<category android:name="android.intent.category.DEFAULT"/>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity>
<activity
android:name="com.mob.tools.MobUIShell"
android:configChanges="keyboardHidden|orientation|screenSize"
@ -109,53 +169,54 @@
</intent-filter>
</activity>
<activity
android:name=".WXEntryActivity"
android:name="com.gh.gamecenter.wxapi.WXEntryActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.MainActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait" />
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="sdksample"/>
</intent-filter>
</activity>
<!-- QQ 分享 -->
<activity
android:name="com.gh.gamecenter.DownloadManagerActivity"
android:screenOrientation="portrait" />
android:name="com.tencent.tauth.AuthActivity"
android:launchMode="singleTask"
android:noHistory="true" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="tencent1104659243" />
</intent-filter>
</activity>
<activity
android:name="com.gh.gamecenter.ViewImageActivity"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />
android:name="com.tencent.connect.common.AssistActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="behind"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<!--微博分享-->
<activity
android:name="com.gh.gamecenter.SearchActivity"
android:name="com.sina.weibo.sdk.component.WeiboSdkBrowser"
android:configChanges="keyboardHidden|orientation"
android:windowSoftInputMode="adjustResize"
android:exported="false" >
</activity>
<activity
android:name="com.gh.gamecenter.WeiBoShareActivity"
android:configChanges="keyboardHidden|orientation"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name="com.gh.gamecenter.NewsOrRaidersActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.GameDetailsActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.NewsActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.GameActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SettingActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SuggestionActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name="com.gh.gamecenter.ConcernActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.HotCardActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.OriginalActivity"
android:screenOrientation="portrait" />
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:exported="true"
android:launchMode="singleTop">
<intent-filter>
<action android:name="com.sina.weibo.sdk.action.ACTION_SDK_REQ_ACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver android:name="com.gh.gamecenter.receiver.InstallAndUninstallReceiver" >
<intent-filter>
@ -174,10 +235,17 @@
</intent-filter>
</receiver>
<receiver
android:name="com.gh.gamecenter.receiver.UninstallReceiver"
android:name="com.gh.gamecenter.receiver.DownloadReceiver"
android:exported="false" >
<intent-filter>
<action android:name="com.gh.gamecenter.UNINSTALL" />
<action android:name="com.gh.gamecenter.DOWNLOAD" />
</intent-filter>
</receiver>
<receiver
android:name="com.gh.gamecenter.receiver.InstallReceiver"
android:exported="false" >
<intent-filter>
<action android:name="com.gh.gamecenter.INSTALL" />
</intent-filter>
</receiver>
<receiver android:name="com.gh.gamecenter.receiver.NetworkStateReceiver" >
@ -216,20 +284,15 @@
</intent-filter>
</receiver>
<receiver
android:name="com.xiaomi.push.service.receivers.PingReceiver"
android:exported="false"
android:process=":pushservice" >
android:name="com.gh.gamecenter.receiver.ActivitySkipReceiver"
android:exported="true" >
<intent-filter>
<action android:name="com.xiaomi.push.PING_TIMER" />
</intent-filter>
</receiver>
<receiver android:name="com.gh.gamecenter.receiver.SmsReceiver" >
<intent-filter android:priority="1000" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="com.gh.gamecenter.ACTIVITYSKIP" />
</intent-filter>
</receiver>
<service android:name="com.gh.download.DownloadService" />
<service
android:name="com.gh.download.DownloadService" />
<service
android:name="com.xiaomi.push.service.XMPushService"
android:enabled="true"

View File

@ -1,129 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<DevInfor>
<!--
说明:
1、表格中的第一项
<ShareSDK
AppKey="api20" />
是必须的其中的AppKey是您在ShareSDK上注册的开发者帐号的AppKey
2、所有集成到您项目的平台都应该为其在表格中填写相对应的开发者信息以新浪微博为例
<SinaWeibo
Id="1"
SortId="1"
AppKey="568898243"
AppSecret="38a4f8204cc784f81f9f0daaf31e02e3"
RedirectUrl="http://www.mob.com"
Enable="true" />
其中的SortId是此平台在分享列表中的位置由开发者自行定义可以是任何整型数字数值越大
越靠后AppKey、AppSecret和RedirectUrl是您在新浪微博上注册开发者信息和应用后得到的信息
Id是一个保留的识别符整型ShareSDK不使用此字段供您在自己的项目中当作平台的识别符。
Enable字段表示此平台是否有效布尔值默认为true如果Enable为false即便平台的jar包
已经添加到应用中,平台实例依然不可获取。
各个平台注册应用信息的地址如下:
新浪微博 http://open.weibo.com
腾讯微博 http://dev.t.qq.com
QQ空间 http://connect.qq.com/intro/login/
微信好友 http://open.weixin.qq.com
Facebook https://developers.facebook.com
Twitter https://dev.twitter.com
人人网 http://dev.renren.com
开心网 http://open.kaixin001.com
搜狐微博 http://open.t.sohu.com
网易微博 http://open.t.163.com
豆瓣 http://developers.douban.com
有道云笔记 http://note.youdao.com/open/developguide.html#app
印象笔记 https://dev.evernote.com/
Linkedin https://developer.linkedin.com
FourSquare https://developer.foursquare.com/
搜狐随身看 https://open.sohu.com/
Flickr http://www.flickr.com/services/
Pinterest http://developers.pinterest.com/
Tumblr http://www.tumblr.com/developers
Dropbox https://www.dropbox.com/developers
Instagram http://instagram.com/developer#
VKontakte http://vk.com/dev
易信好友 http://open.yixin.im/
明道 http://open.mingdao.com/
Line http://media.line.me/zh-hant/
Pocket http://getpocket.com/developer/apps/new
-->
<ShareSDK
AppKey = "6f286c8a261a"/> <!-- 修改成你在sharesdk后台注册的应用的appkey"-->
<!-- ShareByAppClient标识是否使用微博客户端分享默认是false -->
<SinaWeibo
Id="1"
SortId="1"
AppKey="568898243"
AppSecret="38a4f8204cc784f81f9f0daaf31e02e3"
RedirectUrl="http://www.sharesdk.cn"
ShareByAppClient="false"
Enable="true" />
<TencentWeibo
Id="2"
SortId="2"
AppKey="801307650"
AppSecret="ae36f4ee3946e1cbb98d6965b0b2ff5c"
RedirectUri="http://sharesdk.cn"
Enable="true" />
<!-- ShareByAppClient标识是否使用微博客户端分享默认是false -->
<QZone
Id="3"
SortId="3"
AppId="1104659243"
AppKey="OfjHS7bWyxPiH0t8"
ShareByAppClient="true"
Enable="true" />
<!--
Wechat微信和WechatMoments微信朋友圈的appid是一样的
注意开发者不能用我们这两个平台的appid,否则分享不了
微信测试的时候微信测试需要先签名打包出apk,
sample测试微信要先签名打包keystore在sample项目中密码123456
BypassApproval是绕过审核的标记设置为true后AppId将被忽略故不经过
审核的应用也可以执行分享,但是仅限于分享文字和图片,不能分享其他类型,
默认值为false。此外微信收藏不支持此字段。
-->
<Wechat
Id="4"
SortId="4"
AppId="wx4868b35061f87885"
AppSecret="64020361b8ec4c99936c0e3999a9f249"
BypassApproval="true"
Enable="true" />
<WechatMoments
Id="5"
SortId="5"
AppId="wx4868b35061f87885"
AppSecret="64020361b8ec4c99936c0e3999a9f249"
BypassApproval="true"
Enable="true" />
<WechatFavorite
Id="6"
SortId="6"
AppId="wx4868b35061f87885"
AppSecret="64020361b8ec4c99936c0e3999a9f249"
Enable="true" />
<!-- ShareByAppClient标识是否使用微博客户端分享默认是false -->
<QQ
Id="7"
SortId="7"
AppId="1104659243"
AppKey="OfjHS7bWyxPiH0t8"
ShareByAppClient="true"
Enable="true" />
</DevInfor>

Binary file not shown.

View File

@ -429,7 +429,9 @@ class AdapterHelper implements OpReorderer.Callback {
if (DEBUG) {
Log.d(TAG, "postponing " + op);
}
// Utils.log("add UpdateOp to PostponedList");
mPostponedList.add(op);
// Utils.log("op" + op.positionStart + "=" + op.itemCount);
switch (op.cmd) {
case UpdateOp.ADD:
mCallback.offsetPositionsForAdd(op.positionStart, op.itemCount);

View File

@ -3296,10 +3296,16 @@ public class RecyclerView extends ViewGroup {
}
if (holder == null) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
// final int offsetPosition = position;
// Utils.log("offsetPosition position = " + position);
// Utils.log("offsetPosition = " + offsetPosition);
// Utils.log("offsetPosition count = " + mAdapter.getItemCount());
// Utils.log("offsetPosition count = " + mState.getItemCount());
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
+ "position " + position + "(offset:" + offsetPosition + ")."
+ "state:" + mState.getItemCount());
+ "state:" + mState.getItemCount()
+ "adpter:" + mAdapter.getClass().getName());
}
final int type = mAdapter.getItemViewType(offsetPosition);

View File

@ -106,7 +106,7 @@ public class BasicNetwork implements Network {
responseHeaders = convertHeaders(httpResponse.getAllHeaders());
// Handle cache validation.
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
if (request.getUrl().startsWith(Config.HOST + "v2/version")) {
if (request.getUrl().startsWith(Config.HOST + "support/upgrade")) {
if (request.getCacheEntry() != null) {
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,
request.getCacheEntry().data, responseHeaders, true);

View File

@ -176,9 +176,8 @@ public class DiskBasedCache implements Cache {
public synchronized void modify(String key, byte[] data) {
File file = getFileForKey(key);
CountingInputStream cis = null;
try {
cis = new CountingInputStream(new FileInputStream(file));
CountingInputStream cis = new CountingInputStream(new FileInputStream(file));
CacheHeader e = CacheHeader.readHeader(cis); // eat header
Entry entry = e.toCacheEntry(data);
cis.close();

View File

@ -5,7 +5,6 @@ import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Process;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
@ -14,41 +13,86 @@ import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.gh.base.GHPushMessageReceiver.PushHandler;
import com.gh.common.constant.Config;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DexUtils;
import com.gh.common.util.HotFix;
import com.gh.common.util.HttpsUtils;
import com.gh.common.util.Utils;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
// xiaomi push appid
public static final String APP_ID = "2882303761517352993";
// xiaomi push appkey
public static final String APP_KEY = "5451735292993";
private static PushHandler handler = null;
private static AppController mInstance;
private static ArrayMap<String, Object> objectMap = new ArrayMap<>();
private static ArrayMap<String, Object> objectMap = new ArrayMap<String, Object>();
private RequestQueue mRequestQueue;
private ArrayList<Activity> list = new ArrayList<>();
private boolean isFinish = false;
@Override
public void onCreate() {
super.onCreate();
//初始化Fresco
Fresco.initialize(this);
DataUtils.init(this);
HttpsUtils.initHttpsUrlConnection(this);
AppUncaHandler uncaHandler = new AppUncaHandler(this);
Thread.setDefaultUncaughtExceptionHandler(uncaHandler);
mInstance = this;
// 注册push服务注册成功后会向GHPushMessageReceiver发送广播
// 可以从GHPushMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息
if (shouldInit()) {
MiPushClient.registerPush(this, APP_ID, APP_KEY);
}
LoggerInterface newLogger = new LoggerInterface() {
@Override
public void setTag(String tag) {
// ignore
}
@Override
public void log(String content, Throwable t) {
Log.d(TAG, content, t);
}
@Override
public void log(String content) {
Log.d(TAG, content);
}
};
Logger.setLogger(this, newLogger);
}
public static void put(String key, Object object) {
if (objectMap == null) {
objectMap = new ArrayMap<>();
}
objectMap.put(key, object);
}
public static Object get(String key, boolean isRemove) {
if (objectMap == null) {
return null;
}
if (isRemove) {
return objectMap.remove(key);
} else {
@ -57,13 +101,12 @@ public class AppController extends Application {
}
public static void remove(String key) {
if (objectMap == null) {
return;
}
objectMap.remove(key);
}
private ArrayList<Activity> list = new ArrayList<Activity>();
private boolean isFinish = false;
/**
* Activity关闭时删除Activity列表中的Activity对象
*/
@ -98,66 +141,6 @@ public class AppController extends Application {
Process.killProcess(Process.myPid());
}
@Override
public void onCreate() {
super.onCreate();
File dexPath = new File(getDir("dex", Context.MODE_PRIVATE), "hackdex_dex.jar");
DexUtils.prepareAssetsDex(this, dexPath, "hackdex_dex.jar");
HotFix.patch(this, dexPath.getAbsolutePath(), "dodola.hackdex.AntilazyLoad");
SharedPreferences sp = this.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
File directory = new File(this.getFilesDir().getAbsolutePath() + File.separator + "hotfix");
if (directory.exists()) {
File[] files = directory.listFiles();
for (File file : files) {
Utils.log("dex file = " + file.getName());
String clazz = sp.getString(file.getName(), null);
if (clazz != null) {
dexPath = new File(getDir("dex", Context.MODE_PRIVATE), file.getName());
DexUtils.prepareDex(this, dexPath, file);
HotFix.patch(this, dexPath.getAbsolutePath(), clazz);
Utils.log(file.getName() + " patch success");
}
}
}
DataUtils.init(this);
AppUncaHandler uncaHandler = new AppUncaHandler(this);
Thread.setDefaultUncaughtExceptionHandler(uncaHandler);
mInstance = this;
// 注册push服务注册成功后会向GHPushMessageReceiver发送广播
// 可以从GHPushMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息
if (shouldInit()) {
MiPushClient.registerPush(this, APP_ID, APP_KEY);
}
LoggerInterface newLogger = new LoggerInterface() {
@Override
public void setTag(String tag) {
// ignore
}
@Override
public void log(String content, Throwable t) {
Log.d(TAG, content, t);
}
@Override
public void log(String content) {
Log.d(TAG, content);
}
};
Logger.setLogger(this, newLogger);
if (handler == null) {
handler = new PushHandler(this);
}
}
public static String getProcessName(Context cxt, int pid) {
ActivityManager am = (ActivityManager) cxt
.getSystemService(Context.ACTIVITY_SERVICE);
@ -177,6 +160,18 @@ public class AppController extends Application {
return mInstance;
}
public static <T> void addToRequestQueue(Request<T> request) {
request.setTag(TAG);
getInstance().addRequest(request);
}
public static void canclePendingRequests(String tag) {
if (TextUtils.isEmpty(tag)) {
tag = TAG;
}
getInstance().cancleRequest(tag);
}
public <T> void addRequest(Request<T> request) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
@ -189,50 +184,6 @@ public class AppController extends Application {
mRequestQueue.cancelAll(tag);
}
}
public static <T> void addToRequestQueue(Request<T> request) {
request.setTag(TAG);
getInstance().addRequest(request);
}
public static <T> void addToRequestQueue(Request<T> request, String tag) {
request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getInstance().addRequest(request);
}
public static <T> void addToRequestQueue(Request<T> request, Object obj) {
String tag = null;
if (obj != null) {
tag = obj.getClass().getSimpleName();
}
addToRequestQueue(request, tag);
}
public static <T> void addToRequestQueue(Request<T> request, Class<?> clazz) {
String tag = null;
if (clazz != null) {
tag = clazz.getSimpleName();
}
addToRequestQueue(request, tag);
}
public static void canclePendingRequests(String tag) {
if (tag != null) {
getInstance().cancleRequest(tag);
}
}
public static void canclePendingRequests(Object obj) {
if (obj != null) {
getInstance().cancleRequest(obj.getClass().getSimpleName());
}
}
public static void canclePendingRequests(Class<?> clazz) {
if (clazz != null) {
getInstance().cancleRequest(clazz.getSimpleName());
}
}
private boolean shouldInit() {
ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
@ -248,8 +199,4 @@ public class AppController extends Application {
return false;
}
public static PushHandler getHandler() {
return handler;
}
}

View File

@ -4,11 +4,14 @@ import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.gh.common.constant.Config;
import com.gh.common.util.FileUtils;
import com.gh.common.util.NetworkUtils;
import com.gh.gamecenter.SplashScreenActivity;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.tencent.stat.StatService;
@ -55,18 +58,25 @@ public class AppUncaHandler implements UncaughtExceptionHandler {
e.printStackTrace();
}
Intent intent = new Intent(appController.getApplicationContext(),
SplashScreenActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent restartIntent = PendingIntent.getActivity(
appController.getApplicationContext(), 0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
// 退出程序并重启
AlarmManager mgr = (AlarmManager) appController
.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
restartIntent); // 1秒钟后重启应用
// 防止重复奔溃导致助手一直重启20秒内不做处理
SharedPreferences sp = appController.getApplicationContext().getSharedPreferences(
Config.PREFERENCE, Context.MODE_PRIVATE);
long time = sp.getLong("last_restart_time", 0);
if (System.currentTimeMillis() - time > 20 * 1000) {
sp.edit().putLong("last_restart_time", System.currentTimeMillis()).apply();
Intent intent = new Intent(appController.getApplicationContext(),
SplashScreenActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent restartIntent = PendingIntent.getActivity(
appController.getApplicationContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// 退出程序并重启
AlarmManager mgr = (AlarmManager) appController
.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
restartIntent); // 1秒钟后重启应用
}
appController.finishActivity();
}
}
@ -78,19 +88,17 @@ public class AppUncaHandler implements UncaughtExceptionHandler {
// MTA主动上传错误
StatService.reportError(appController.getApplicationContext(), errorMsg);
Map<String, Object> map = new HashMap<String, Object>();
// WIFI实时上传错误数据
Map<String, Object> map = new HashMap<>();
map.put("content", errorMsg);
map.put("createdOn", System.currentTimeMillis() / 1000);
map.put("type", android.os.Build.MODEL);
map.put("system", android.os.Build.VERSION.SDK_INT + "="
+ android.os.Build.VERSION.RELEASE);
DataCollectionManager.onEvent(appController.getApplicationContext(),
"error", map, false);
map.put("system", android.os.Build.VERSION.SDK_INT + "=" + android.os.Build.VERSION.RELEASE);
DataCollectionManager.onEvent(appController.getApplicationContext(), "error", map,
NetworkUtils.isWifiConnected(appController.getApplicationContext()));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss",
Locale.getDefault());
File file = new File(FileUtils.getLogPath(
appController.getApplicationContext(),
// 保存到本地
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault());
File file = new File(FileUtils.getLogPath(appController.getApplicationContext(),
format.format(new Date()) + "_gh_assist" + ".log"));
FileWriter writer = null;
try {
@ -109,6 +117,7 @@ public class AppUncaHandler implements UncaughtExceptionHandler {
}
}
}
}
/**

View File

@ -5,7 +5,6 @@ import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
@ -20,32 +19,32 @@ import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.RunningUtils;
import com.gh.common.util.ShareUtils;
import com.gh.common.util.Utils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBShowDialog;
import com.gh.gamecenter.listener.OnCallBackListener;
import com.gh.gamecenter.manager.SystemBarTintManager;
import com.gh.gamecenter.manager.SystemBarTintManager.SystemBarConfig;
import java.lang.reflect.Field;
import java.util.ArrayList;
import cn.sharesdk.framework.ShareSDK;
import de.greenrobot.event.EventBus;
import onekeyshare.OnekeyShare;
import onekeyshare.themes.classic.PlatformPage;
public class BaseActivity extends Activity {
private String LOG = this.getClass().getName();
private boolean LOG_ON = true;
public class BaseActivity extends Activity implements OnCallBackListener {
private SystemBarTintManager tintManager;
private boolean isPause;
private SystemBarTintManager tintManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppLog("onCreate");
Utils.log(this.getClass().getSimpleName());
AppController.getInstance().addActivity(this);
EventBus.getDefault().register(this);
@ -63,7 +62,7 @@ public class BaseActivity extends Activity {
setTranslucentStatus(true);
tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.theme_colors);
tintManager.setStatusBarTintResource(R.color.theme);
SystemBarConfig config = tintManager.getConfig();
contentView.setPadding(0, config.getPixelInsetTop(false), 0,
config.getPixelInsetBottom());
@ -118,12 +117,6 @@ public class BaseActivity extends Activity {
AppController.getInstance().removeActivity(this);
}
public void AppLog(String str) {
if (LOG_ON) {
Log.i(LOG, str);
}
}
public void toast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
@ -145,60 +138,44 @@ public class BaseActivity extends Activity {
window.setAttributes(winParams);
}
public void showShare(String url, String title, String icon, String entrance, String type) {
//如果是游戏分享newsTitle默认为空
public void showShare(String url, String gameName, String icon, String newsTitle, ArrayList<String> tag, String entrance, String type) {
if (isShowShare){
return;
//判断是否是官方版
boolean isPlugin = false;
if (tag != null){
for (String s : tag) {
if (!"官方版".equals(s)){
isPlugin = true;
}
}
}
ShareSDK.initSDK(this);
OnekeyShare oks = new OnekeyShare();
// 关闭sso授权
oks.disableSSOWhenAuthorize();
ShareUtils.getInstance(this).showShareWindows(new View(this), url, gameName, icon, newsTitle, isPlugin);
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
// oks.setNotification(R.drawable.ic_launcher,
// getString(R.string.app_name));
// title标题印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle(title);
// titleUrl是标题的网络链接仅在人人网和QQ空间使用
oks.setTitleUrl(url);
// text是分享文本所有平台都需要这个字段
oks.setText(title + " " + url);
// imagePath是图片的本地路径Linked-In以外的平台都支持此参数
// oks.setImagePath(icon);//确保SDcard下面存在此张图片
oks.setImageUrl(icon);
// url仅在微信包括好友和朋友圈中使用
oks.setUrl(url);
// comment是我对这条分享的评论仅在人人网和QQ空间使用
oks.setComment("精彩尽在" + url);
// site是分享此内容的网站名称仅在QQ空间使用
oks.setSite(this.getString(R.string.app_name));
// siteUrl是分享此内容的网站地址仅在QQ空间使用
oks.setSiteUrl(url);
oks.setOnFinishListener(new PlatformPage.OnFinishListener() {
@Override
public void onFinish() {
Utils.log("onFinish");
isShowShare = false;
}
});
// 启动分享GUI
oks.show(this);
DataUtils.onEvent(this, "内容分享", title);
isShowShare = true;
if (newsTitle == null){
DataUtils.onEvent(this, "内容分享", gameName);
}else {
DataUtils.onEvent(this, "内容分享", newsTitle);
}
}
private boolean isShowShare = false;
public void onEventMainThread(EBShowDialog showDialog) {
public void onEventMainThread(final EBShowDialog showDialog) {
if (!isPause && this.getClass().getName().equals(RunningUtils.getTopActivity(this))) {
if ("hijack".equals(showDialog.getType())) {
DialogUtils.showHijackDialog(this);
} else if ("delete".equals(showDialog.getType())) {
DialogUtils.showDeleteDialog(this, showDialog.getPath());
DialogUtils.showQqSessionDialog(this, null);// 建议用户联系客服
} else if ("plugin".equals(showDialog.getType())) {
DialogUtils.showPluginDialog(this, new DialogUtils.ConfiremListener(){
@Override
public void onConfirem() {
if (FileUtils.isEmptyFile(showDialog.getPath())) {
Toast.makeText(BaseActivity.this, "解析包出错(可能被误删了),请重新下载", Toast.LENGTH_SHORT).show();
} else {
startActivity(PackageUtils.getUninstallIntent(BaseActivity.this, showDialog.getPath()));
}
}
});
}
}
}
@ -212,35 +189,35 @@ public class BaseActivity extends Activity {
@Override
protected void onPause() {
super.onPause();
AppLog("onPause");
DataUtils.onPause(this);
isPause = true;
}
@Override
protected void onRestart() {
super.onRestart();
AppLog("onRestart");
}
@Override
protected void onResume() {
super.onResume();
AppLog("onResume");
DataUtils.onResume(this);
isPause = false;
DownloadManager.getInstance(this).initGameMap();
}
@Override
protected void onStart() {
super.onStart();
AppLog("onStart");
public void loadDone() {
}
@Override
protected void onStop() {
super.onStop();
AppLog("onStop");
public void loadDone(Object obj) {
}
@Override
public void loadError() {
}
@Override
public void loadEmpty() {
}
}

View File

@ -0,0 +1,421 @@
package com.gh.base;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.GameUtils;
import com.gh.common.util.NetworkUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PlatformUtils;
import com.gh.common.util.ShareUtils;
import com.gh.common.view.DownloadDialog;
import com.gh.download.DataWatcher;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.PackageManager;
import com.tencent.tauth.Tencent;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2016/9/19.
* 游戏详情、新闻详情基类(控制底部下载栏)
*/
public abstract class BaseDetailActivity extends BaseActivity implements View.OnClickListener {
protected TextView actionbar_tv_title;
protected RecyclerView detail_rv_show;
protected LinearLayout detail_ll_bottom;
protected TextView detail_tv_download;
protected ProgressBar detail_pb_progressbar;
protected TextView detail_tv_per;
protected LinearLayout reuse_ll_loading;
protected LinearLayout reuse_no_connection;
protected ImageView iv_share;
protected GameEntity gameEntity;
protected DownloadEntity mDownloadEntity;
protected String entrance;
protected String name;
protected String title;
protected String downloadAddWord;
protected String downloadOffText;
protected Handler handler = new Handler();
private DataWatcher dataWatcher = new DataWatcher() {
@Override
public void onDataChanged(DownloadEntity downloadEntity) {
if (gameEntity != null && gameEntity.getApk().size() == 1) {
String url = gameEntity.getApk().get(0).getUrl();
if (url.equals(downloadEntity.getUrl())) {
if (!"pause".equals(DownloadManager.getInstance(BaseDetailActivity.this).
getStatus(downloadEntity.getUrl()))) {
mDownloadEntity = downloadEntity;
invalidate();
}
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
entrance = getIntent().getStringExtra("entrance");
View contentView = View.inflate(this, R.layout.activity_detail, null);
// 添加分享图标
iv_share = new ImageView(this);
iv_share.setImageResource(R.drawable.share_icon);
iv_share.setOnClickListener(this);
iv_share.setVisibility(View.GONE);
iv_share.setPadding(DisplayUtils.dip2px(this, 13),DisplayUtils.dip2px(this, 11)
,DisplayUtils.dip2px(this, 11),DisplayUtils.dip2px(this, 13));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
DisplayUtils.dip2px(this, 48), DisplayUtils.dip2px(this, 48));
params.addRule( RelativeLayout.CENTER_VERTICAL);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT );
RelativeLayout reuse_actionbar = (RelativeLayout) contentView.findViewById(
R.id.reuse_actionbar);
reuse_actionbar.addView(iv_share, params);
init(contentView);
actionbar_tv_title = (TextView) findViewById(R.id.actionbar_tv_title);
detail_rv_show = (RecyclerView) findViewById(R.id.detail_rv_show);
detail_ll_bottom = (LinearLayout) findViewById(R.id.detail_ll_bottom);
detail_tv_download = (TextView) findViewById(R.id.detail_tv_download);
detail_pb_progressbar = (ProgressBar) findViewById(R.id.detail_pb_progressbar);
detail_tv_per = (TextView) findViewById(R.id.detail_tv_per);
reuse_ll_loading = (LinearLayout) findViewById(R.id.reuse_ll_loading);
reuse_no_connection = (LinearLayout) findViewById(R.id.reuse_no_connection);
detail_ll_bottom.setOnClickListener(this);
detail_tv_download.setOnClickListener(this);
detail_pb_progressbar.setOnClickListener(this);
detail_tv_per.setOnClickListener(this);
reuse_no_connection.setOnClickListener(this);
}
//接收QQ或者QQ空间分享回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == com.tencent.connect.common.Constants.REQUEST_QQ_SHARE
|| requestCode == com.tencent.connect.common.Constants.REQUEST_QZONE_SHARE) {
Tencent.onActivityResultData(requestCode, resultCode, data, ShareUtils.getInstance(this).QqShareListener);
}
}
@Override
protected void onResume() {
super.onResume();
if (gameEntity != null
&& gameEntity.getApk() != null
&& gameEntity.getApk().size() == 1) {
initDownload(true);
}
DownloadManager.getInstance(this).addObserver(dataWatcher);
}
@Override
protected void onPause() {
super.onPause();
DownloadManager.getInstance(this).removeObserver(dataWatcher);
}
protected void initDownload(boolean isCheck) {
if (Config.isShow(this)) {
detail_ll_bottom.setVisibility(View.VISIBLE);
detail_rv_show.setPadding(0, 0, 0,
DisplayUtils.dip2px(getApplicationContext(), 44));
} else {
detail_ll_bottom.setVisibility(View.GONE);
detail_rv_show.setPadding(0, 0, 0, 0);
}
if (gameEntity != null && "光环助手".equals(gameEntity.getName())) {
detail_ll_bottom.setVisibility(View.GONE);
detail_rv_show.setPadding(0, 0, 0, 0);
} else if (gameEntity == null || gameEntity.getApk().isEmpty()) {
detail_tv_download.setVisibility(View.VISIBLE);
detail_pb_progressbar.setVisibility(View.GONE);
detail_tv_per.setVisibility(View.GONE);
if (TextUtils.isEmpty(downloadOffText)) {
detail_tv_download.setText("暂无下载");
} else {
detail_tv_download.setText(downloadOffText);
}
detail_tv_download.setBackgroundResource(R.drawable.game_item_btn_pause_style);
detail_tv_download.setTextColor(0xFF999999);
detail_tv_download.setClickable(false);
} else {
detail_tv_download.setVisibility(View.VISIBLE);
detail_pb_progressbar.setVisibility(View.GONE);
detail_tv_per.setVisibility(View.GONE);
boolean isInstalled = false;
if (gameEntity.getApk() != null && gameEntity.getApk().size() == 1
&& PackageManager.isInstalled(gameEntity.getApk().get(0).getPackageName())) {
isInstalled = true;
}
if (isInstalled) {
if (PackageManager.isCanUpdate(gameEntity.getId(), gameEntity.getApk().get(0).getPackageName())) {
if (TextUtils.isEmpty(downloadAddWord)) {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_download_style);
detail_tv_download.setText(String.format("更新《%s》",
gameEntity.getName()));
} else {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_download_style);
detail_tv_download.setText(String.format("更新《%s》%s",
gameEntity.getName(), downloadAddWord));
}
} else {
if (gameEntity.getTag() != null && gameEntity.getTag().size() != 0
&& !TextUtils.isEmpty(gameEntity.getApk().get(0).getGhVersion())
&& !PackageUtils.isSignature(this, gameEntity.getApk().get(0).getPackageName())) {
if (TextUtils.isEmpty(downloadAddWord)) {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_plugin_style);
detail_tv_download.setText(String.format("插件化《%s》",
gameEntity.getName()));
} else {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_plugin_style);
detail_tv_download.setText(String.format("插件化《%s》%s",
gameEntity.getName(), downloadAddWord));
}
} else {
if (TextUtils.isEmpty(downloadAddWord)) {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_launch_style);
detail_tv_download.setText(String.format("启动《%s》",
gameEntity.getName()));
} else {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_launch_style);
detail_tv_download.setText(String.format("启动《%s》%s",
gameEntity.getName(), downloadAddWord));
}
}
}
} else {
String status = GameUtils.getDownloadBtnText(this, gameEntity);
if ("插件化".equals(status)) {
detail_tv_download.setBackgroundResource(R.drawable.game_item_btn_plugin_style);
} else if ("打开".equals(status)) {
detail_tv_download.setBackgroundResource(R.drawable.game_item_btn_launch_style);
} else {
detail_tv_download.setBackgroundResource(R.drawable.game_item_btn_download_style);
}
if (TextUtils.isEmpty(downloadAddWord)) {
detail_tv_download.setText(String.format(status + "《%s》",
gameEntity.getName()));
} else {
detail_tv_download.setText(String.format(status + "《%s》%s",
gameEntity.getName(), downloadAddWord));
}
}
}
if (isCheck && gameEntity != null
&& gameEntity.getApk() != null
&& gameEntity.getApk().size() == 1) {
String url = gameEntity.getApk().get(0).getUrl();
DownloadEntity downloadEntity = DownloadManager.getInstance(getApplicationContext()).get(url);
if (downloadEntity != null) {
mDownloadEntity = downloadEntity;
detail_tv_download.setVisibility(View.GONE);
detail_pb_progressbar.setVisibility(View.VISIBLE);
detail_tv_per.setVisibility(View.VISIBLE);
invalidate();
}
}
}
private void invalidate() {
detail_pb_progressbar.setProgress((int) (mDownloadEntity.getPercent() * 10));
detail_tv_per.setTextColor(0xFFFFFFFF);
switch (mDownloadEntity.getStatus()) {
case downloading:
case pause:
case timeout:
case neterror:
case waiting:
detail_tv_per.setText("下载中");
break;
case done:
detail_tv_per.setText("安装");
if (mDownloadEntity.isPluggable()
&& PackageManager.isInstalled(mDownloadEntity.getPackageName())) {
detail_pb_progressbar.setProgressDrawable(getResources().getDrawable(R.drawable.progressbar_plugin_radius_style));
} else {
detail_pb_progressbar.setProgressDrawable(getResources().getDrawable(R.drawable.progressbar_normal_radius_style));
}
break;
case cancel:
case hijack:
case notfound:
initDownload(false);
break;
default:
break;
}
}
// 接收下载被删除消息
public void onEvent(EBDownloadStatus status) {
if ("delete".equals(status.getStatus())
&& gameEntity != null
&& gameEntity.getApk() != null
&& gameEntity.getApk().size() == 1) {
String url = gameEntity.getApk().get(0).getUrl();
if (url.equals(status.getUrl())) {
initDownload(false);
}
}
}
// 接受安装、卸载消息
public void onEventMainThread(EBPackage busFour) {
if (gameEntity != null
&& gameEntity.getApk() != null
&& gameEntity.getApk().size() == 1) {
String packageName = gameEntity.getApk().get(0).getPackageName();
if (packageName.equals(busFour.getPackageName())) {
initDownload(false);
}
}
}
@Override
public void onClick(View v) {
if (v == detail_tv_download) {
if (gameEntity != null && !gameEntity.getApk().isEmpty()) {
if (gameEntity.getApk().size() == 1) {
if (NetworkUtils.isWifiConnected(this)) {
download();
} else {
DialogUtils.showDownloadDialog(this, new DialogUtils.ConfiremListener() {
@Override
public void onConfirem() {
download();
}
});
}
} else {
DownloadDialog.getInstance(this)
.showPopupWindow(v, gameEntity, entrance, name + ":" + title);
}
} else {
toast("稍等片刻~!游戏正在上传中...");
}
} else if (v == detail_pb_progressbar || v == detail_tv_per) {
String str = detail_tv_per.getText().toString();
if ("下载中".equals(str)) {
Intent intent = new Intent(this, DownloadManagerActivity.class);
intent.putExtra("url", gameEntity.getApk().get(0).getUrl());
startActivity(intent);
} else if ("安装".equals(str)) {
PackageUtils.launchSetup(this, mDownloadEntity.getPath());
}
}
}
private void download() {
String str = detail_tv_download.getText().toString();
if (str.contains("启动")) {
Map<String, Object> kv = new HashMap<>();
kv.put("版本", gameEntity.getApk().get(0).getPlatform());
kv.put("页面", name);
DataUtils.onEvent(BaseDetailActivity.this, "游戏启动", gameEntity.getName(), kv);
PackageUtils.launchApplicationByPackageName(this, gameEntity.getApk().get(0).getPackageName());
} else {
String method;
if (str.contains("更新")) {
method = "更新";
} else if (str.contains("插件化")) {
method = "插件化";
} else {
method = "下载";
}
ApkEntity apkEntity = gameEntity.getApk().get(0);
String msg = FileUtils.isCanDownload(this, apkEntity.getSize());
if (TextUtils.isEmpty(msg)) {
Map<String, Object> kv = new HashMap<>();
kv.put("版本", apkEntity.getPlatform());
kv.put("状态", "下载开始");
DataUtils.onEvent(BaseDetailActivity.this, "游戏下载", gameEntity.getName(), kv);
Map<String, Object> kv2 = new HashMap<>();
kv2.put("版本", apkEntity.getPlatform());
kv2.put("状态", "下载开始");
kv2.put("页面", name);
kv2.put("位置", entrance);
DataUtils.onEvent(BaseDetailActivity.this, "游戏下载位置", gameEntity.getName(), kv2);
Map<String, Object> kv3 = new HashMap<>();
kv3.put(entrance, "下载数");
kv3.put(entrance, "下载开始");
DataUtils.onEvent(BaseDetailActivity.this, "应用数据", gameEntity.getName(), kv3);
Map<String, Object> map = new HashMap<>();
map.put("game", gameEntity.getName());
map.put("game_id", gameEntity.getId());
map.put("method", method.equals("下载") ? "正常" : method);
map.put("platform", PlatformUtils.getInstance(getApplicationContext())
.getPlatformName(gameEntity.getApk().get(0).getPlatform()));
map.put("status", "开始");
map.put("location", name + ":" + title);
map.put("entrance", entrance);
map.put("btn_status", method);
map.put("network", NetworkUtils.getConnectedType(this));
DataCollectionManager.onEvent(this, "download", map);
DownloadManager.createDownload(this, apkEntity, gameEntity, method, entrance, name + ":" + title);
detail_tv_download.setVisibility(View.GONE);
detail_pb_progressbar.setVisibility(View.VISIBLE);
detail_tv_per.setVisibility(View.VISIBLE);
detail_pb_progressbar.setProgress(0);
detail_tv_per.setText("0.0%");
DownloadManager.getInstance(BaseDetailActivity.this).putStatus(apkEntity.getUrl(), "downloading");
} else {
toast(msg);
}
}
}
}

View File

@ -0,0 +1,127 @@
package com.gh.base;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.gh.common.util.Utils;
import com.gh.gamecenter.listener.OnCallBackListener;
import java.lang.reflect.Field;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
/**
* Created by LGT on 2016/9/4.
* Fragment 基类
*/
public class BaseFragment extends Fragment implements OnCallBackListener {
// private Unbinder unbinder;
protected View view;
protected Handler handler = new Handler();
protected boolean isEverpause;
protected void init(int layout, boolean flag) {
view = View.inflate(getActivity(), layout, null);
// unbinder = ButterKnife.bind(this, view);
if (flag) {
//简化findViewById
try {
Class<?> clazz = this.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
int id = Utils.getId(field.getName());
if (id != -1) {
Utils.log("reflect name = " + field.getName());
field.setAccessible(true);
Class<?> fieldType = field.getType();
Object injectedValue = fieldType.cast(view.findViewById(id));
field.set(this, injectedValue);
field.setAccessible(false);
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
ButterKnife.bind(this, view);
}
}
protected void init(int layout) {
init(layout, true);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isEverpause = false;
EventBus.getDefault().register(this);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
if(container != null){
container.removeView(view);
}
return view;
}
public boolean isEverpause() {
return isEverpause;
}
@Override
public void onPause() {
super.onPause();
isEverpause = true;
}
@Override
public void onResume() {
super.onResume();
isEverpause = false;
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
// unbinder.unbind();
}
@Override
public void loadDone() {
}
@Override
public void loadDone(Object obj) {
}
@Override
public void loadError() {
}
@Override
public void loadEmpty() {
}
}

View File

@ -5,7 +5,6 @@ import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
@ -20,30 +19,29 @@ import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.RunningUtils;
import com.gh.common.util.ShareUtils;
import com.gh.common.util.Utils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBShowDialog;
import com.gh.gamecenter.manager.SystemBarTintManager;
import com.gh.gamecenter.manager.SystemBarTintManager.SystemBarConfig;
import java.lang.reflect.Field;
import java.util.ArrayList;
import cn.sharesdk.framework.ShareSDK;
import de.greenrobot.event.EventBus;
import onekeyshare.OnekeyShare;
import onekeyshare.themes.classic.PlatformPage;
public class BaseFragmentActivity extends FragmentActivity {
private String LOG = this.getClass().getName();
private boolean LOG_ON = false;
private boolean isPause;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppLog("onCreate");
Utils.log(this.getClass().getSimpleName());
AppController.getInstance().addActivity(this);
EventBus.getDefault().register(this);
@ -61,7 +59,7 @@ public class BaseFragmentActivity extends FragmentActivity {
setTranslucentStatus(true);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.theme_colors);
tintManager.setStatusBarTintResource(R.color.theme);
SystemBarConfig config = tintManager.getConfig();
contentView.setPadding(0, config.getPixelInsetTop(false), 0,
config.getPixelInsetBottom());
@ -111,12 +109,6 @@ public class BaseFragmentActivity extends FragmentActivity {
AppController.getInstance().removeActivity(this);
}
public void AppLog(String str) {
if (LOG_ON) {
Log.i(LOG, str);
}
}
public void toast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
@ -138,60 +130,43 @@ public class BaseFragmentActivity extends FragmentActivity {
window.setAttributes(winParams);
}
public void showShare(String url, String title, String icon, String entrance, String type) {
//如果是游戏分享newsTitle默认为空
public void showShare(String url, String gameName, String icon, String newsTitle, ArrayList<String> tag, String entrance, String type) {
if (isShowShare){
return;
//判断是否是官方版
boolean isPlugin = false;
if (tag != null){
for (String s : tag) {
if (!"官方版".equals(s)){
isPlugin = true;
}
}
}
ShareSDK.initSDK(this);
OnekeyShare oks = new OnekeyShare();
// 关闭sso授权
oks.disableSSOWhenAuthorize();
ShareUtils.getInstance(this).showShareWindows(new View(this), url, gameName, icon, newsTitle, isPlugin);
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
// oks.setNotification(R.drawable.ic_launcher,
// getString(R.string.app_name));
// title标题印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle(title);
// titleUrl是标题的网络链接仅在人人网和QQ空间使用
oks.setTitleUrl(url);
// text是分享文本所有平台都需要这个字段
oks.setText(title + " " + url);
// imagePath是图片的本地路径Linked-In以外的平台都支持此参数
// oks.setImagePath(icon);//确保SDcard下面存在此张图片
oks.setImageUrl(icon);
// url仅在微信包括好友和朋友圈中使用
oks.setUrl(url);
// comment是我对这条分享的评论仅在人人网和QQ空间使用
oks.setComment("精彩尽在" + url);
// site是分享此内容的网站名称仅在QQ空间使用
oks.setSite(this.getString(R.string.app_name));
// siteUrl是分享此内容的网站地址仅在QQ空间使用
oks.setSiteUrl(url);
oks.setOnFinishListener(new PlatformPage.OnFinishListener() {
@Override
public void onFinish() {
Utils.log("onFinish");
isShowShare = false;
}
});
// 启动分享GUI
oks.show(this);
DataUtils.onEvent(this, "内容分享", title);
isShowShare = true;
if (newsTitle == null){
DataUtils.onEvent(this, "内容分享", gameName);
}else {
DataUtils.onEvent(this, "内容分享", newsTitle);
}
}
private boolean isShowShare = false;
public void onEventMainThread(EBShowDialog showDialog) {
public void onEventMainThread(final EBShowDialog showDialog) {
if (!isPause && this.getClass().getName().equals(RunningUtils.getTopActivity(this))) {
if ("hijack".equals(showDialog.getType())) {
DialogUtils.showHijackDialog(this);
} else if ("delete".equals(showDialog.getType())) {
DialogUtils.showDeleteDialog(this, showDialog.getPath());
DialogUtils.showQqSessionDialog(this, null);// 建议用户联系客服
} else if ("plugin".equals(showDialog.getType())) {
DialogUtils.showPluginDialog(this, new DialogUtils.ConfiremListener(){
@Override
public void onConfirem() {
if (FileUtils.isEmptyFile(showDialog.getPath())) {
Toast.makeText(BaseFragmentActivity.this, "解析包出错(可能被误删了),请重新下载", Toast.LENGTH_SHORT).show();
} else {
startActivity(PackageUtils.getUninstallIntent(BaseFragmentActivity.this, showDialog.getPath()));
}
}
});
}
}
}
@ -205,34 +180,16 @@ public class BaseFragmentActivity extends FragmentActivity {
@Override
protected void onPause() {
super.onPause();
AppLog("onPause");
DataUtils.onPause(this);
isPause = true;
}
@Override
protected void onRestart() {
super.onRestart();
AppLog("onRestart");
}
@Override
protected void onResume() {
super.onResume();
AppLog("onResume");
DataUtils.onResume(this);
isPause = false;
DownloadManager.getInstance(this).initGameMap();
}
@Override
protected void onStart() {
super.onStart();
AppLog("onStart");
}
@Override
protected void onStop() {
super.onStop();
AppLog("onStop");
}
}

View File

@ -1,6 +1,5 @@
package com.gh.base;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
@ -10,11 +9,8 @@ import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
@ -22,8 +18,6 @@ import com.gh.common.util.FileUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.Utils;
import com.gh.gamecenter.R;
import com.xiaomi.mipush.sdk.ErrorCode;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageReceiver;
@ -63,17 +57,6 @@ import java.util.Locale;
*/
public class GHPushMessageReceiver extends PushMessageReceiver {
private String mRegId;
private long mResultCode = -1;
private String mReason;
private String mCommand;
private String mMessage;
private String mTopic;
private String mAlias;
private String mAccount;
private String mStartTime;
private String mEndTime;
@Override
public void onReceivePassThroughMessage(Context context,
MiPushMessage message) {
@ -86,15 +69,12 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
Utils.log("channel = " + channel);
// 1判断渠道号是否一致或是否为ALL
String TD_CHANNEL_ID = (String) PackageUtils.getMetaData(context, context.getPackageName(), "TD_CHANNEL_ID");
if ("ALL".equals(channel)
|| TD_CHANNEL_ID
.equalsIgnoreCase(channel)) {
if ("ALL".equals(channel) || channel.equalsIgnoreCase(TD_CHANNEL_ID)) {
String type = jsonObject.getString("type");
Utils.log("type = " + type);
if ("NEWS".equals(type)) {
// 新闻推送
JSONArray jsonArray = jsonObject
.getJSONArray("package");
JSONArray jsonArray = jsonObject.getJSONArray("package");
ArrayMap<String, Boolean> map = getInstalledMapFromLocal(context);
for (int i = 0; i < jsonArray.length(); i++) {
Boolean b = map.get(jsonArray.getString(i));
@ -119,14 +99,11 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
if (gh_version != null) {
gh_version = gh_version.substring(2);
// 判断gh_version是否相同
if (gh_version.equals(apk
.getString("gh_version"))) {
if (gh_version.equals(apk.getString("gh_version"))) {
// 判断version是否相同
String version = PackageUtils
.getVersionByPackage(context,
packageName);
if (version.equals(apk
.getString("version"))) {
String version = PackageUtils.getVersionByPackage(
context, packageName);
if (apk.getString("version").equals(version)) {
// 版本相同,无需显示插件更新,继续查看是否有可更新的游戏包
continue;
}
@ -147,24 +124,10 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
e.printStackTrace();
}
Log.v(AppController.TAG, "onReceivePassThroughMessage is called. "
+ message.toString());
String log = context.getString(R.string.recv_passthrough_message,
message.getContent());
if (!TextUtils.isEmpty(message.getTopic())) {
mTopic = message.getTopic();
} else if (!TextUtils.isEmpty(message.getAlias())) {
mAlias = message.getAlias();
}
Message msg = Message.obtain();
msg.obj = log;
AppController.getHandler().sendMessage(msg);
Log.v(AppController.TAG, "onReceivePassThroughMessage is called. " + message.toString());
}
private void showNotification(Context context, JSONObject jsonObject, int id)
throws JSONException {
private void showNotification(Context context, JSONObject jsonObject, int id) throws JSONException {
Intent intent = new Intent();
intent.setAction("com.gh.gamecenter.NOTIFICATION");
intent.putExtra("notifyId", id);
@ -185,7 +148,8 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
RemoteViews remoteViews = null;
if (Build.MANUFACTURER.equals("Meizu")
&& (Build.MODEL.startsWith("m") || Build.MODEL.startsWith("MX"))) {
&& (Build.MODEL.startsWith("m")
|| Build.MODEL.startsWith("MX"))) {
remoteViews = new RemoteViews(context.getPackageName(),
R.layout.notification_meizu);
SimpleDateFormat format = new SimpleDateFormat("HH:mm",
@ -193,8 +157,8 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
remoteViews.setTextViewText(R.id.time, format.format(new Date()));
} else if (Build.MANUFACTURER.equals("Xiaomi")
&& (Build.MODEL.startsWith("MI")
|| Build.MODEL.startsWith("HM") || Build.MODEL
.startsWith("Redmi"))) {
|| Build.MODEL.startsWith("HM")
|| Build.MODEL.startsWith("Redmi"))) {
// 小米系统
remoteViews = new RemoteViews(context.getPackageName(),
R.layout.notification_xiaomi);
@ -211,27 +175,39 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
String path = context.getCacheDir() + File.separator
+ url.substring(url.lastIndexOf("/") + 1);
try {
FileUtils.downloadFile(url, path);
int result = FileUtils.downloadFile(url, path);
if (result == -1) {
// 下载出错使用光环logo
path = null;
}
} catch (IOException e) {
// 下载出错使用光环logo
path = null;
e.printStackTrace();
}
if (remoteViews != null) {
remoteViews.setImageViewBitmap(R.id.icon,
BitmapFactory.decodeFile(path));
// remoteViews.setImageViewResource(R.id.icon, R.drawable.me_icon);
remoteViews.setTextViewText(R.id.title,
jsonObject.getString("pushTitle"));
remoteViews.setTextViewText(R.id.intro,
jsonObject.getString("pushDesc"));
if (path == null) {
remoteViews.setImageViewBitmap(R.id.icon, BitmapFactory.decodeResource(context.getResources(), R.drawable.logo));
} else {
remoteViews.setImageViewBitmap(R.id.icon, BitmapFactory.decodeFile(path));
}
remoteViews.setTextViewText(R.id.title, jsonObject.getString("pushTitle"));
remoteViews.setTextViewText(R.id.intro, jsonObject.getString("pushDesc"));
notification.contentView = remoteViews;
} else {
notification = new NotificationCompat.Builder(context)
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo_black)
.setTicker(jsonObject.getString("pushTitle"))
.setContentTitle(jsonObject.getString("pushTitle"))
.setContentText(jsonObject.getString("pushDesc"))
.setContentIntent(pendingIntent)
.setLargeIcon(BitmapFactory.decodeFile(path)).build();
.setContentIntent(pendingIntent);
if (path == null) {
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo));
} else {
builder.setLargeIcon(BitmapFactory.decodeFile(path));
}
notification = builder.build();
}
notification.defaults = Notification.DEFAULT_SOUND;// 添加系统默认声音
@ -240,7 +216,7 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
}
private ArrayMap<String, Boolean> getInstalledMapFromLocal(Context context) {
ArrayMap<String, Boolean> map = new ArrayMap<String, Boolean>();
ArrayMap<String, Boolean> map = new ArrayMap<>();
ArrayList<String> list = getAllPackageName(context);
for (String str : list) {
map.put(str, true);
@ -249,7 +225,7 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
}
private ArrayList<String> getAllPackageName(Context context) {
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list = new ArrayList<>();
List<PackageInfo> packageInfos = context.getPackageManager()
.getInstalledPackages(0);
for (int i = 0, size = packageInfos.size(); i < size; i++) {
@ -266,21 +242,6 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
MiPushMessage message) {
Log.v(AppController.TAG, "onNotificationMessageClicked is called. "
+ message.toString());
String log = context.getString(R.string.click_notification_message,
message.getContent());
if (!TextUtils.isEmpty(message.getTopic())) {
mTopic = message.getTopic();
} else if (!TextUtils.isEmpty(message.getAlias())) {
mAlias = message.getAlias();
}
Message msg = Message.obtain();
if (message.isNotified()) {
msg.obj = log;
}
AppController.getHandler().sendMessage(msg);
}
@Override
@ -288,105 +249,12 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
MiPushMessage message) {
Log.v(AppController.TAG, "onNotificationMessageArrived is called. "
+ message.toString());
String log = context.getString(R.string.arrive_notification_message,
message.getContent());
if (!TextUtils.isEmpty(message.getTopic())) {
mTopic = message.getTopic();
} else if (!TextUtils.isEmpty(message.getAlias())) {
mAlias = message.getAlias();
}
Message msg = Message.obtain();
msg.obj = log;
AppController.getHandler().sendMessage(msg);
}
@Override
public void onCommandResult(Context context, MiPushCommandMessage message) {
Log.v(AppController.TAG,
"onCommandResult is called. " + message.toString());
String command = message.getCommand();
List<String> arguments = message.getCommandArguments();
String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments
.get(0) : null);
String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments
.get(1) : null);
String log = "";
if (MiPushClient.COMMAND_REGISTER.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mRegId = cmdArg1;
log = context.getString(R.string.register_success);
} else {
log = context.getString(R.string.register_fail);
}
} else if (MiPushClient.COMMAND_SET_ALIAS.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mAlias = cmdArg1;
log = context.getString(R.string.set_alias_success, mAlias);
} else {
log = context.getString(R.string.set_alias_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_UNSET_ALIAS.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mAlias = cmdArg1;
log = context.getString(R.string.unset_alias_success, mAlias);
} else {
log = context.getString(R.string.unset_alias_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_SET_ACCOUNT.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mAccount = cmdArg1;
log = context.getString(R.string.set_account_success, mAccount);
} else {
log = context.getString(R.string.set_account_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_UNSET_ACCOUNT.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mAccount = cmdArg1;
log = context.getString(R.string.unset_account_success,
mAccount);
} else {
log = context.getString(R.string.unset_account_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mTopic = cmdArg1;
log = context.getString(R.string.subscribe_topic_success,
mTopic);
} else {
log = context.getString(R.string.subscribe_topic_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_UNSUBSCRIBE_TOPIC.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
log = context.getString(R.string.unsubscribe_topic_success,
mTopic);
} else {
log = context.getString(R.string.unsubscribe_topic_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_SET_ACCEPT_TIME.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mStartTime = cmdArg1;
mEndTime = cmdArg2;
log = context.getString(R.string.set_accept_time_success,
mStartTime, mEndTime);
} else {
log = context.getString(R.string.set_accept_time_fail,
message.getReason());
}
} else {
log = message.getReason();
}
Message msg = Message.obtain();
msg.obj = log;
AppController.getHandler().sendMessage(msg);
Log.v(AppController.TAG, "onCommandResult is called. "
+ message.toString());
}
@Override
@ -394,47 +262,6 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
MiPushCommandMessage message) {
Log.v(AppController.TAG, "onReceiveRegisterResult is called. "
+ message.toString());
String command = message.getCommand();
List<String> arguments = message.getCommandArguments();
String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments
.get(0) : null);
String log;
if (MiPushClient.COMMAND_REGISTER.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mRegId = cmdArg1;
log = context.getString(R.string.register_success);
} else {
log = context.getString(R.string.register_fail);
}
} else {
log = message.getReason();
}
Message msg = Message.obtain();
msg.obj = log;
AppController.getHandler().sendMessage(msg);
}
@SuppressLint("SimpleDateFormat")
public static String getSimpleDate() {
return new SimpleDateFormat("MM-dd hh:mm:ss").format(new Date());
}
public static class PushHandler extends Handler {
private Context context;
public PushHandler(Context context) {
this.context = context;
}
@Override
public void handleMessage(Message msg) {
String s = (String) msg.obj;
if (!TextUtils.isEmpty(s)) {
// Toast.makeText(context, s, Toast.LENGTH_LONG).show();
}
}
}
}

View File

@ -0,0 +1,247 @@
package com.gh.base;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.ConcernActivity;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.SearchActivity;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.PackageManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
/**
* Created by LGT on 2016/9/9.
* 工具栏 搜索控制
*/
public class HomeFragment extends Fragment implements View.OnClickListener {
protected View view;
protected LinearLayout home_ll_top;
protected View home_slide_line;
protected ViewPager home_vp_content;
protected LinearLayout.LayoutParams lparams;
protected Handler handler = new Handler();
private TextView downloadHint;
private TextView searchHint;
private String hint;
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (!TextUtils.isEmpty(hint)) {
outState.putString("hint", hint);
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
hint = savedInstanceState.getString("hint");
}
view = View.inflate(getActivity(), R.layout.fragment_home, null);
SharedPreferences sp = getActivity().getSharedPreferences(
Config.PREFERENCE, Context.MODE_PRIVATE);
LinearLayout home_actionbar = (LinearLayout) view.findViewById(R.id.home_actionbar);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, sp.getInt("actionbar_height",
DisplayUtils.dip2px(getActivity(), 48)));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
int top = DisplayUtils.getInternalDimensionSize(getResources(), "status_bar_height");
home_actionbar.setPadding(0, top, 0, 0);
lparams.height += top;
}
home_actionbar.setLayoutParams(lparams);
initActionBar();
home_ll_top = (LinearLayout) view.findViewById(R.id.home_ll_top);
home_slide_line = view.findViewById(R.id.home_slide_line);
home_vp_content = (ViewPager) view.findViewById(R.id.home_vp_content);
EventBus.getDefault().register(this);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
if (container != null) {
container.removeView(view);
}
return view;
}
private void initActionBar() {
view.findViewById(R.id.actionbar_rl_download).setOnClickListener(this);
view.findViewById(R.id.actionbar_iv_search).setOnClickListener(this);
view.findViewById(R.id.actionbar_notification).setOnClickListener(this);
if (Config.isShow(getActivity())) {
view.findViewById(R.id.actionbar_rl_download).setVisibility(View.VISIBLE);
} else {
view.findViewById(R.id.actionbar_rl_download).setVisibility(View.GONE);
}
downloadHint = (TextView) view.findViewById(R.id.action_tip);
int updateSize = PackageManager.getUpdateListSize();
int downloadSize = DownloadManager.getInstance(getActivity()).getAll().size();
if (downloadSize != 0) {
downloadHint.setVisibility(View.VISIBLE);
downloadHint.setText(String.valueOf(downloadSize));
} else if (updateSize != 0) {
downloadHint.setVisibility(View.VISIBLE);
downloadHint.setText(String.valueOf(updateSize));
} else {
downloadHint.setVisibility(View.GONE);
}
searchHint = (TextView) view.findViewById(R.id.actionbar_search_input);
searchHint.setOnClickListener(this);
if (!TextUtils.isEmpty(hint)) {
searchHint.setHint(hint);
}
}
@Override
public void onClick(View v) {
final int id = v.getId();
if (id == R.id.actionbar_notification) {
DataUtils.onEvent(getActivity(), "主页", "关注图标");
Map<String, Object> map = new HashMap<>();
map.put("location", "关注图标");
map.put("page", "主页");
DataCollectionManager.onEvent(getActivity(), "click-item", map);
startActivity(new Intent(getActivity(), ConcernActivity.class));
} else if (id == R.id.actionbar_rl_download) {
DataUtils.onEvent(getActivity(), "主页", "下载图标");
Map<String, Object> map = new HashMap<>();
map.put("location", "下载图标");
map.put("page", "主页");
DataCollectionManager.onEvent(getActivity(), "click-item", map);
startActivity(new Intent(getActivity(), DownloadManagerActivity.class));
} else if (id == R.id.actionbar_search_input) {
DataUtils.onEvent(getActivity(), "主页", "搜索框");
Map<String, Object> map = new HashMap<>();
map.put("location", "搜索框");
map.put("page", "主页");
DataCollectionManager.onEvent(getActivity(), "click-item", map);
Intent goSearch = new Intent(getActivity(), SearchActivity.class);
goSearch.putExtra("clicked", false);
goSearch.putExtra("hint", hint);
startActivity(goSearch);
} else if (id == R.id.actionbar_iv_search) {
DataUtils.onEvent(getActivity(), "主页", "搜索图标");
Map<String, Object> map = new HashMap<>();
map.put("location", "搜索图标");
map.put("page", "主页");
DataCollectionManager.onEvent(getActivity(), "click-item", map);
Intent searchIntent = new Intent(getActivity(), SearchActivity.class);
searchIntent.putExtra("clicked", true);
searchIntent.putExtra("hint", hint);
startActivity(searchIntent);
}
}
// 打开下载按钮事件
public void onEventMainThread(EBReuse reuse) {
if ("Refresh".equals(reuse.getType())) {
if (Config.isShow(getActivity())) {
view.findViewById(R.id.actionbar_rl_download).setVisibility(View.VISIBLE);
} else {
view.findViewById(R.id.actionbar_rl_download).setVisibility(View.GONE);
}
}
}
public void setHint(String hint) {
if (!TextUtils.isEmpty(hint)) {
this.hint = hint;
if (searchHint != null) {
searchHint.setHint(hint);
}
}
}
public void onEventMainThread(EBDownloadStatus status) {
int updateSize = PackageManager.getUpdateListSize();
int downloadSize = DownloadManager.getInstance(getActivity()).getAll().size();
if (downloadSize != 0) {
downloadHint.setVisibility(View.VISIBLE);
downloadHint.setText(String.valueOf(downloadSize));
} else if (updateSize != 0) {
downloadHint.setVisibility(View.VISIBLE);
downloadHint.setText(String.valueOf(updateSize));
} else {
downloadHint.setVisibility(View.GONE);
}
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
List<Fragment> list = getChildFragmentManager().getFragments();
if (list != null) {
if (hidden) {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
transaction.hide(fragment);
}
} else {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
transaction.show(fragment);
}
}
}
transaction.commit();
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}

View File

@ -1,16 +1,20 @@
package com.gh.common.constant;
import com.gh.gamecenter.SplashScreenActivity;
import android.content.Context;
import android.content.SharedPreferences;
public final class Config {
// test host dev.ghzhushou.com/api
public static final String HOST = "http://api.ghzhushou.com/";
// public static final String HOST = "http://115.28.145.16:9001/";
public class Config {
public static final String HOST = "http://api.ghzhushou.com/v2d2/";
public static final String USER_HOST = "http://user.ghzhushou.com/v1d0/";
public static final String COMMENT_HOST = "http://comment.ghzhushou.com/v1d0/";
public static final String DATA_HOST = "http://data.ghzhushou.com/";
public static final String PREFERENCE = "ghzhushou";
// public static final boolean isShow = true;
public static final boolean isShow = SplashScreenActivity.isShow;
public static boolean isShow(Context context) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
return sp.getBoolean("isShow", true);
}
}

View File

@ -38,4 +38,5 @@ public class Constants {
public static final int SEARCH_CD = 5 * 60 * 1000;
//评论 cd间隔
public static final int COMMENT_CD = 60 * 1000;
}

View File

@ -0,0 +1,24 @@
package com.gh.common.constant;
/**
* Created by LGT on 2016/10/16.
*/
public class ItemViewType {
public static final int COLUMN_HEADER = 0; // 专题头部布局
public static final int GAME_SLIDE = 1; // 滚动图布局
public static final int GAME_NORMAL = 2; // 正常游戏布局
public static final int GAME_TEST = 3; // 测试游戏布局
public static final int GAME_IMAGE = 4; // 游戏大图布局
public static final int NEWS_HEADER = 5; // 新闻头部布局
public static final int NEWS_TEXT = 6; // 新闻文本布局
public static final int NEWS_IMAGE = 7; // 新闻带图布局
public static final int NEWS_IMAGE1 = 8; // 新闻带一张小图布局
public static final int NEWS_IMAGE2 = 9; // 新闻带三张小图布局
public static final int NEWS_IMAGE3 = 10; // 新闻带一张大图布局
public static final int NEWS_DIGEST = 11; // 新闻摘要布局
public static final int SEARCH_NORMAL = 12; // 搜索正常布局
public static final int SEARCH_DELETE = 13; // 清空历史记录布局
public static final int LOADING = 14; // 加载布局
}

View File

@ -0,0 +1,77 @@
package com.gh.common.util;
import android.content.Context;
import android.content.SharedPreferences;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
/**
* Created by khy on 2016/11/24.
* 该类定义了微博授权时所需要的参数。
*/
public class AccessTokenKeeper {
private static final String PREFERENCES_NAME = "com_weibo_sdk_android";
private static final String KEY_UID = "uid";
private static final String KEY_ACCESS_TOKEN = "access_token";
private static final String KEY_EXPIRES_IN = "expires_in";
private static final String KEY_REFRESH_TOKEN = "refresh_token";
/**
* 保存 Token 对象到 SharedPreferences。
*
* @param context 应用程序上下文环境
* @param token Token 对象
*/
public static void writeAccessToken(Context context, Oauth2AccessToken token) {
if (null == context || null == token) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
SharedPreferences.Editor editor = pref.edit();
editor.putString(KEY_UID, token.getUid());
editor.putString(KEY_ACCESS_TOKEN, token.getToken());
editor.putString(KEY_REFRESH_TOKEN, token.getRefreshToken());
editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());
editor.commit();
}
/**
* 从 SharedPreferences 读取 Token 信息。
*
* @param context 应用程序上下文环境
*
* @return 返回 Token 对象
*/
public static Oauth2AccessToken readAccessToken(Context context) {
if (null == context) {
return null;
}
Oauth2AccessToken token = new Oauth2AccessToken();
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
token.setUid(pref.getString(KEY_UID, ""));
token.setToken(pref.getString(KEY_ACCESS_TOKEN, ""));
token.setRefreshToken(pref.getString(KEY_REFRESH_TOKEN, ""));
token.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0));
return token;
}
/**
* 清空 SharedPreferences 中 Token信息。
*
* @param context 应用程序上下文环境
*/
public static void clear(Context context) {
if (null == context) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
}
}

View File

@ -0,0 +1,87 @@
package com.gh.common.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import java.io.IOException;
/**
* Created by LGT on 2016/10/21.
*/
public class BitmapUtils {
/**
* 根据文件路径返回bitmap
* @param filepath 文件路径
* @param w 宽
* @param h 高
* @return bitmap
*/
public static Bitmap getBitmapByFile(String filepath, int w, int h) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
// 设置为ture只获取图片大小
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
// 返回为空
BitmapFactory.decodeFile(filepath, options);
int width = options.outWidth;
int height = options.outHeight;
float scaleWidth = 0.f, scaleHeight = 0.f;
if (width > w || height > h) {
// 缩放
scaleWidth = ((float) width) / w;
scaleHeight = ((float) height) / h;
}
options.inJustDecodeBounds = false;
int scale = (int) Math.ceil(Math.max(scaleWidth, scaleHeight));
if (scale % 2 == 1) {
scale += 1;
}
options.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filepath, options);
bitmap = rotatePicture(filepath, bitmap);
if (bitmap != null) {
return bitmap;
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Bitmap rotatePicture(String path, Bitmap bitmap) {
int rotate = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
if (rotate != 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
} else {
return bitmap;
}
}
}

View File

@ -0,0 +1,98 @@
package com.gh.common.util;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.gamecenter.ViewImageActivity;
import java.util.ArrayList;
import java.util.List;
/**
* Created by khy on 2016/11/8.
*
* 初始化资讯关注-内容图片
*
**/
public class ConcernContentUtils {
public static void addContentPic(int width, LinearLayout linearLayout, List<String> list, Context context) {
int count = list.size();
LinearLayout ll;
int index = 0;
for (int i = 0, size = (int) Math.ceil(list.size() / 3.0f); i < size; i++) {
switch (count % 3) {
case 0:
ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.HORIZONTAL);
for (int j = 0; j < 3; j++) {
ll.addView(getImageView(list, index, width, 0, context));
index += 1;
}
linearLayout.addView(ll);
count -= 3;
break;
case 1:
linearLayout.addView(getImageView(list, index, width, 1, context));
count -= 1;
index += 1;
break;
case 2:
ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.HORIZONTAL);
for (int j = 0; j < 2; j++) {
ll.addView(getImageView(list, index, width, 2, context));
index += 1;
}
linearLayout.addView(ll);
count -= 2;
break;
}
}
}
private static SimpleDraweeView getImageView(final List<String> list, final int position, int width, int type, final Context context) {
SimpleDraweeView imageView;
if (type == 0) {
imageView = new SimpleDraweeView(context);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
0, width / 3 - DisplayUtils.dip2px(context, 4));
lparams.setMargins(DisplayUtils.dip2px(context, 2), 0,
DisplayUtils.dip2px(context, 2), DisplayUtils.dip2px(context, 4));
lparams.weight = 1;
imageView.setLayoutParams(lparams);
ImageUtils.getInstance().display(context.getResources(), imageView, ScalingUtils.ScaleType.CENTER_CROP, list.get(position));
} else if (type == 1) {
imageView = new SimpleDraweeView(context);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(width, width / 2);
lparams.setMargins(DisplayUtils.dip2px(context, 2), 0,
DisplayUtils.dip2px(context, 2), DisplayUtils.dip2px(context, 4));
imageView.setLayoutParams(lparams);
ImageUtils.getInstance().display(context.getResources(), imageView, ScalingUtils.ScaleType.CENTER_CROP, list.get(position));
} else {
imageView = new SimpleDraweeView(context);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
0, width / 2 - DisplayUtils.dip2px(context, 4));
lparams.setMargins(DisplayUtils.dip2px(context, 2), 0,
DisplayUtils.dip2px(context, 2), DisplayUtils.dip2px(context, 4));
lparams.weight = 1;
imageView.setLayoutParams(lparams);
ImageUtils.getInstance().display(context.getResources(), imageView, ScalingUtils.ScaleType.CENTER_CROP, list.get(position));
}
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent checkIntent = new Intent(context, ViewImageActivity.class);
checkIntent.putExtra("urls", (ArrayList<String>) list);
checkIntent.putExtra("current", position);
checkIntent.putExtra("ScaleType", "FIT_CENTER");
context.startActivity(checkIntent);
}
});
return imageView;
}
}

View File

@ -0,0 +1,154 @@
package com.gh.common.util;
import android.content.Context;
import android.telephony.TelephonyManager;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import com.gh.gamecenter.volley.extended.StringExtendedRequest;
import org.json.JSONArray;
import java.util.UUID;
/**
* Created by khy on 2016/8/24.
*/
public class ConcernUtils {
public static void loadConcernData(final String url, final DownJsonListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
if (listener != null){
listener.downSucced(response.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null){
listener.downFailed();
}
}
});
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
}).start();
}
public static void postConcernGameId(final String gameId, final String postUrl, final DownJsonListener listener){
new Thread(new Runnable() {
@Override
public void run() {
JSONArray data = new JSONArray();
data.put(gameId);
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.POST, postUrl, data.toString(),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (listener != null) {
listener.downSucced("关注成功");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null) {
listener.downFailed();
}
}
});
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
}).start();
}
public static void deleteConcernData(final String url, final DownJsonListener listener){
new Thread(new Runnable() {
@Override
public void run() {
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.DELETE, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (listener != null) {
listener.downSucced("删除成功");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null) {
listener.downFailed();
}
}
});
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
}).start();
}
public static void updateConcernData(final String url, final JSONArray data, final DownJsonListener listener){
new Thread(new Runnable() {
@Override
public void run() {
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.PUT, url, data.toString(),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (listener != null) {
listener.downSucced("更新设备关注成功");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null) {
listener.downFailed();
}
}
});
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
}).start();
}
public interface DownJsonListener {
void downSucced(String str);
void downFailed();
}
// 获取设备号ID
public static String uuid(Context context){
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
return deviceUuid.toString();
}
}

View File

@ -21,14 +21,14 @@ public class DataUtils {
public static void init(Application application) {
//TalkingData
//dubug true release false
TCAgent.LOG_ON = false;
TCAgent.LOG_ON = true;
TCAgent.init(application);
TCAgent.setReportUncaughtExceptions(true);
//MTA
// 打开debug开关可查看mta上报日志或错误
// dubug true release false
StatConfig.setDebugEnable(false);
StatConfig.setDebugEnable(true);
// 收集未处理的异常
StatConfig.setAutoExceptionCaught(true);
// 设置数据上报策略
@ -55,7 +55,7 @@ public class DataUtils {
for (String key : var3.keySet()) {
prop.setProperty(key, var3.get(key) + "");
}
StatService.trackCustomBeginKVEvent(var0, var1, prop);
StatService.trackCustomKVEvent(var0, var1, prop);
}
public static void onPause(Activity var0) {

View File

@ -15,14 +15,16 @@ public class DeviceUtils {
StringBuffer buffer = new StringBuffer();
String imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
if (!TextUtils.isEmpty(imei)) {
buffer.append("imei=" + imei);
buffer.append("imei=");
buffer.append(imei);
}
String android_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
if (!TextUtils.isEmpty(android_id)) {
if (buffer.length() != 0) {
buffer.append(",");
}
buffer.append("android_id=" + android_id);
buffer.append("android_id=");
buffer.append(android_id);
}
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String mac = wm.getConnectionInfo().getMacAddress();
@ -30,7 +32,8 @@ public class DeviceUtils {
if (buffer.length() != 0) {
buffer.append(",");
}
buffer.append("mac=" + mac);
buffer.append("mac=");
buffer.append(mac);
}
return buffer.toString();
}

View File

@ -17,6 +17,7 @@ import java.io.OutputStream;
* Created by sunpengfei on 15/11/4.
*/
public class DexUtils {
private static final int BUF_SIZE = 2048;
public static boolean prepareAssetsDex(Context context, File dexInternalStoragePath, String dex_file) {
@ -53,7 +54,7 @@ public class DexUtils {
}
}
public static boolean prepareDex(Context context, File dexInternalStoragePath, File dex_file) {
public static boolean prepareDex(File dexInternalStoragePath, File dex_file) {
BufferedInputStream bis = null;
OutputStream dexWriter = null;
@ -86,4 +87,5 @@ public class DexUtils {
return false;
}
}
}

View File

@ -1,15 +1,17 @@
package com.gh.common.util;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import com.gh.gamecenter.MainActivity;
import com.gh.gamecenter.R;
public class DialogUtils {
@ -26,142 +28,158 @@ public class DialogUtils {
return dialog;
}
public static void showDialog(final Context context, final String path) {
private static boolean isShow = false;
public static void showWarningDialog(Context context, String title, CharSequence msg, String cancel, String confirm,
final ConfiremListener cmListener, final CancelListener clListener) {
if (isShow) {
return;
}
isShow = true;
final Dialog dialog = new Dialog(context);
View view = View.inflate(context,
R.layout.search_history_delete_dialog, null);
TextView title = (TextView) view.findViewById(R.id.delete_dialog_title);
title.setText("卸载");
TextView content = (TextView) view
.findViewById(R.id.delete_dialog_message);
content.setText("您已安装了官方原版,该版本与插件版本冲突,是否卸载官方原版?");
View view = View.inflate(context, R.layout.common_alertdialog, null);
TextView cancel = (TextView) view
.findViewById(R.id.delete_dialog_cancel);
cancel.setText("忽略");
cancel.setOnClickListener(new OnClickListener() {
// 标题
TextView alertdialog_title = (TextView) view.findViewById(R.id.alertdialog_title);
alertdialog_title.setText(title);
// 内容
TextView alertdialog_content = (TextView) view.findViewById(R.id.alertdialog_content);
alertdialog_content.setText(msg);
// 取消按钮
TextView alertdialog_cannel = (TextView) view.findViewById(R.id.alertdialog_cannel);
alertdialog_cannel.setText(cancel);
alertdialog_cannel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (clListener != null) {
clListener.onCancel();
}
}
});
TextView confirem = (TextView) view
.findViewById(R.id.delete_dialog_confirm);
confirem.setText("卸载");
confirem.setOnClickListener(new OnClickListener() {
// 确定按钮
TextView alertdialog_confirm = (TextView) view.findViewById(R.id.alertdialog_confirm);
alertdialog_confirm.setText(confirm);
alertdialog_confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Utils.log("packageName = "
+ PackageUtils.getPackageNameByPath(context, path));
MainActivity.uninstallMap.put(
PackageUtils.getPackageNameByPath(context, path), path);
context.startActivity(PackageUtils.getUninstallIntent(context,
path));
dialog.dismiss();
if (cmListener != null) {
cmListener.onConfirem();
}
}
});
dialog.setOnDismissListener(new Dialog.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
isShow = false;
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
}
private static boolean isShowHijackDialog = false;
public static void showHijackDialog(final Context context) {
if (!isShowHijackDialog) {
final Dialog dialog = new Dialog(context);
View view = View.inflate(context,
R.layout.search_history_delete_dialog, null);
TextView title = (TextView) view
.findViewById(R.id.delete_dialog_title);
title.setText("警告");
TextView content = (TextView) view
.findViewById(R.id.delete_dialog_message);
content.setText("您当前网络环境异常,下载地址已被替换(网络劫持),请更换网络环境进行下载。");
TextView cancel = (TextView) view
.findViewById(R.id.delete_dialog_cancel);
cancel.setText("取消");
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView confirem = (TextView) view
.findViewById(R.id.delete_dialog_confirm);
confirem.setText("确定");
confirem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 跳转wifi管理界面
Intent intent = new Intent("android.settings.WIFI_SETTINGS");
context.startActivity(intent);
dialog.dismiss();
}
});
dialog.setOnDismissListener(new Dialog.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
isShowHijackDialog = false;
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
isShowHijackDialog = true;
}
showWarningDialog(context, "警告", "您当前网络环境异常,下载地址已被替换(网络劫持),请更换网络环境进行下载。",
new ConfiremListener() {
@Override
public void onConfirem() {
// 跳转wifi管理界面
Intent intent = new Intent("android.settings.WIFI_SETTINGS");
context.startActivity(intent);
}
});
}
private static boolean isShowDeleteDialog = false;
public static void showDeleteDialog(final Context context, final String path) {
if (!isShowDeleteDialog) {
final Dialog dialog = new Dialog(context);
View view = View.inflate(context,
R.layout.search_history_delete_dialog, null);
TextView title = (TextView) view.findViewById(R.id.delete_dialog_title);
title.setText("卸载");
TextView content = (TextView) view
.findViewById(R.id.delete_dialog_message);
content.setText("您已安装了官方原版,该版本与插件版本冲突,是否卸载官方原版?");
TextView cancel = (TextView) view
.findViewById(R.id.delete_dialog_cancel);
cancel.setText("忽略");
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView confirem = (TextView) view
.findViewById(R.id.delete_dialog_confirm);
confirem.setText("卸载");
confirem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.uninstallMap.put(
PackageUtils.getPackageNameByPath(context, path), path);
context.startActivity(PackageUtils.getUninstallIntent(context,
path));
dialog.dismiss();
}
});
dialog.setOnDismissListener(new Dialog.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
isShowDeleteDialog = false;
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
isShowDeleteDialog = true;
// 网络劫持时 打开QQ客户端创建临时会话
public static void showQqSessionDialog(final Context context, String qq) {
if (qq == null) {
qq = "2586716223";// 默认客服QQ
}
final String finalQq = qq;
showWarningDialog(context, "警告", "您当前网络环境异常,下载地址可能被运营商恶意替换(网络劫持)" +
"如多次下载失败请联系客服获取正确的下载地址客服QQ" + qq + ""
, "取消", "前往QQ", new ConfiremListener() {
@Override
public void onConfirem() {
if (ShareUtils.isQQClientAvailable(context)) {
//安装了QQ会直接调用QQ打开手机QQ进行会话 QQ号2586716223
String str = "mqqwpa://im/chat?chat_type=wpa&uin=" + finalQq + "&version=1&src_type=web&web_src=oicqzone.com";
Uri uri = Uri.parse(str);
Intent it = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(it);
} else {
//没有安装QQ 复制账号
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setText(finalQq);
Utils.toast(context,"已复制" + finalQq);
}
}
}, null);
}
public static void showWarningDialog(Context context, String title, CharSequence msg, final ConfiremListener listener) {
showWarningDialog(context, title, msg, "取消", "确定", listener, null);
}
public static void showDownloadDialog(Context context, ConfiremListener listener) {
showWarningDialog(context, "下载提示", "您当前使用的网络为2G/3G/4G开始下载将会消耗移动流量确定下载", listener);
}
public static void showCancelDialog(Context context, final ConfiremListener listener) {
Spanned content = Html.fromHtml("取消关注游戏后,您将无法及时收到游戏" +
"<font color='#ff0000'>攻略</font>、" +
"<font color='#ff0000'>资讯</font>等最新动态提醒。");
showWarningDialog(context, "取消关注", content, "暂不取消", "确定取消", listener, null);
}
public static void showPluginDialog(Context context, final ConfiremListener listener) {
Spanned spanned = Html.fromHtml("您将进行插件化安装以实现插件功能,此过程将"
+ "<font color=\"#ff0000\">卸载</font>" + "当前使用的版本并"
+ "<font color=\"#ff0000\">安装插件版本</font>");
showWarningDialog(context, "插件化安装", spanned, listener);
}
public static void showDisclaimerDialog(Context context, String content) {
final Dialog disclaimerDialog = new Dialog(context);
View view = View.inflate(context, R.layout.dialog_disclaimer, null);
// TextView title = (TextView) view.findViewById(R.id.disclaimer_title);
// title.setText("免责声明");
TextView message = (TextView) view.findViewById(R.id.disclaimer_message);
Spanned spanned = Html.fromHtml(content);
message.setText(spanned);
view.findViewById(R.id.disclaimer_confirm).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
disclaimerDialog.dismiss();
}
});
disclaimerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
disclaimerDialog.setContentView(view);
disclaimerDialog.show();
}
public interface ConfiremListener{
void onConfirem();
}
public interface CancelListener{
void onCancel();
}
}

View File

@ -25,7 +25,7 @@ public class DisplayUtils {
* 将px值转换为sp值保证文字大小不变
*
* @param pxValue
* @param fontScale
* @param pxValue
* DisplayMetrics类中属性scaledDensity
* @return
*/
@ -38,7 +38,7 @@ public class DisplayUtils {
* 将sp值转换为px值保证文字大小不变
*
* @param spValue
* @param fontScale
* @param spValue
* DisplayMetrics类中属性scaledDensity
* @return
*/

File diff suppressed because it is too large Load Diff

View File

@ -5,9 +5,10 @@ import android.os.Environment;
import android.os.StatFs;
import android.os.StrictMode;
import org.apache.http.HttpStatus;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
@ -38,10 +39,14 @@ public class FileUtils {
File file = new File(dir + File.separator + TEST_FILE_NAME);
if (!file.exists()) {
try {
file.createNewFile();
if (!file.createNewFile()) {
// cannot create file
Utils.log("cannot create file");
dir = null;
}
} catch (IOException e) {
e.printStackTrace();
//cannot create file
// cannot create file
Utils.log("cannot create file");
dir = null;
}
@ -50,6 +55,11 @@ public class FileUtils {
if (dir == null) {
String baseDir = context.getFilesDir().getAbsolutePath();
dir = checkDir(baseDir + File.separator + "gh-download");
try {
Runtime.getRuntime().exec("chmod 755 " + dir);
} catch (IOException e) {
e.printStackTrace();
}
}
return dir;
}
@ -76,7 +86,10 @@ public class FileUtils {
private static String checkDir(String dir) {
File directory = new File(dir);
if (!directory.exists() || !directory.isDirectory()) {
if (directory.exists() && !directory.isDirectory()) {
directory.delete();
}
if (!directory.exists()) {
directory.mkdirs();
}
return dir;
@ -96,21 +109,6 @@ public class FileUtils {
}
return true;
}
public static void checkDirExists(String dirName) {
File file = Environment.getExternalStorageDirectory();
if (file.isDirectory()) {
File[] fs = file.listFiles();
for (int i = 0; i < fs.length; i++) {
if (fs[i].isDirectory()
&& fs[i].getName().equalsIgnoreCase(dirName)
&& !fs[i].getName().equals(dirName)) {
fs[i].delete();
break;
}
}
}
}
public static boolean isMounted() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
@ -134,15 +132,13 @@ public class FileUtils {
@SuppressWarnings("deprecation")
public static float getFreeSpaceByPath(String path) {
StatFs statfs = new StatFs(path);
long blockSize = statfs.getBlockSize();
long availableBlocks = statfs.getAvailableBlocks();
return availableBlocks * blockSize / 1024f / 1024f;
}
public static String isCanDownload(String size) {
public static String isCanDownload(Context context, String size) {
String msg = null;
String packageSizeStr = "";
for (int i = 0; i < size.length(); i++) {
@ -154,8 +150,7 @@ public class FileUtils {
if (packageSizeStr.length() != 0) {
packageSize = Float.valueOf(packageSizeStr);
}
float freeSpace = getFreeSpaceByPath(Environment
.getExternalStorageDirectory().getAbsolutePath());
float freeSpace = getFreeSpaceByPath(getDownloadDir(context));
if (freeSpace < packageSize) {
msg = "手机存储空间不足,无法进行下载!";
}
@ -168,8 +163,7 @@ public class FileUtils {
DataInputStream dis = null;
FileOutputStream fos = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url)
.openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(5 * 1000);
@ -193,7 +187,7 @@ public class FileUtils {
dis.close();
}
return code;
} catch (Exception e) {
} catch (IOException e) {
e.printStackTrace();
return -1;
} finally {
@ -207,7 +201,7 @@ public class FileUtils {
}
// 上传文件
public static String uploadFile(String url, String filePath, String token) {
public static JSONObject uploadFile(String url, String filePath, String token) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = UUID.randomUUID().toString().replaceAll("-", "")
@ -220,21 +214,23 @@ public class FileUtils {
* post method must write something to the connection
*/
connection.setDoOutput(true);
/* Read from the connection. Default is true. */
// Read from the connection. Default is true.
connection.setDoInput(true);
/* Post cannot use caches */
// Post cannot use caches
connection.setUseCaches(false);
/* Set the post method. Default is GET */
// Set the post method. Default is GET
connection.setRequestMethod("POST");
/* 设置请求属性 */
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(5 * 1000);
// 设置请求属性
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
if (token != null) {
connection.setRequestProperty("Auth", token);
connection.setRequestProperty("TOKEN", token);
}
/* 设置StrictMode 否则HTTPURLConnection连接失败因为这是在主进程中进行网络连接 */
// 设置StrictMode 否则HTTPURLConnection连接失败因为这是在主进程中进行网络连接
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
@ -243,60 +239,144 @@ public class FileUtils {
Utils.log("name = " + file.getName());
Utils.log("length = " + file.length());
}
/* 设置DataOutputStreamgetOutputStream中默认调用connect() */
// 设置DataOutputStreamgetOutputStream中默认调用connect()
DataOutputStream dos = new DataOutputStream(
connection.getOutputStream()); // output
// to
// the
// connection
// to the connection
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; "
+ "name=\"Filedata\";filename=\"" + file.getName() + "\""
+ end);
dos.writeBytes(end);
/* 取得文件的FileInputStream */
// 取得文件的FileInputStream
FileInputStream fStream = new FileInputStream(file);
/* 设置每次写入8192bytes */
// 设置每次写入8192bytes
int bufferSize = 8192;
byte[] buffer = new byte[bufferSize]; // 8k
int length = -1;
/* 从文件读取数据至缓冲区 */
int length;
// 从文件读取数据至缓冲区
while ((length = fStream.read(buffer)) != -1) {
/* 将资料写入DataOutputStream中 */
// 将资料写入DataOutputStream中
dos.write(buffer, 0, length);
}
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* 关闭流写入的东西自动生成Http正文 */
// 关闭流写入的东西自动生成Http正文
fStream.close();
/* 关闭DataOutputStream */
// 关闭DataOutputStream
dos.flush();
dos.close();
/* 从返回的输入流读取响应信息 */
InputStream is = connection.getInputStream(); // input from the
// connection
// 正式建立HTTP连接
Utils.log("con.getResponseCode() = " + connection.getResponseCode());
InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException ioe) {
inputStream = connection.getErrorStream();
}
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
while ((ch = inputStream.read()) != -1) {
b.append((char) ch);
}
/* 显示网页响应内容 */
// 显示网页响应内容
Utils.log("content = " + b.toString().trim());
// {"status":"success","url":"http:\/\/api.ghzhushou.com\/temp\/5688e548d7859e6f278b4567.jpg"}
if (connection.getResponseCode() == HttpStatus.SC_OK) {
int statusCode = connection.getResponseCode();
Utils.log("statusCode = " + statusCode);
if (statusCode == 200) {
// {"icon":"http:\/\/gh-test-1.oss-cn-qingdao.aliyuncs.com\/pic\/57e4f4d58a3200042d29492f.jpg"}
JSONObject response = new JSONObject(b.toString().trim());
if ("success".equals(response.getString("status"))) {
return response.getString("url");
}
response.put("statusCode", 200);
return response;
} else if (statusCode == 403) {
JSONObject response = new JSONObject(b.toString().trim());
response.put("statusCode", 403);
return response;
} else if (statusCode == 401) {
JSONObject response = new JSONObject();
response.put("statusCode", 401);
return response;
}
} catch (Exception e) {
/* 显示异常信息 */
// 显示异常信息
e.printStackTrace();
Utils.log("Fail:" + e);
}
return null;
}
// 读取文件返回byte[]
public static byte[] readFile(File file) {
if (file == null) {
return null;
}
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len;
while ((len = fis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.flush();
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// 根据byte[],保存文件
public static void saveFile(File file, byte[] data) {
if (file == null || data == null) {
return;
}
ByteArrayInputStream bis = null;
FileOutputStream fos = null;
try {
bis = new ByteArrayInputStream(data);
fos = new FileOutputStream(file);
byte[] buffer = new byte[2048];
int len;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

View File

@ -0,0 +1,108 @@
package com.gh.common.util;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.TextView;
import com.gh.base.AppController;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.manager.PackageManager;
/**
* Created by LGT on 2016/9/29.
*/
public class GameUtils {
/**
* 启动游戏详情页面
*/
public static void startGameDetailActivity(Context context, GameEntity gameEntity, String entrance) {
AppController.put("GameEntity", gameEntity);
Intent intent = new Intent(context, GameDetailActivity.class);
intent.putExtra("entrance", entrance);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 启动游戏详情页面
*/
public static void startGameDetailActivity(Context context, String gameId, String entrance) {
Intent intent = new Intent(context, GameDetailActivity.class);
intent.putExtra("gameId", gameId);
intent.putExtra("entrance", entrance);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 设置下载按钮状态
*/
public static void setDownloadBtnStatus(Context context, GameEntity gameEntity, TextView downloadBtn) {
String status = getDownloadBtnText(context, gameEntity);
downloadBtn.setTextColor(Color.WHITE);
downloadBtn.setText(status);
if ("插件化".equals(status)) {
downloadBtn.setBackgroundResource(R.drawable.game_item_btn_plugin_style);
} else if ("打开".equals(status)) {
downloadBtn.setBackgroundResource(R.drawable.game_item_btn_launch_style);
} else {
downloadBtn.setBackgroundResource(R.drawable.game_item_btn_download_style);
}
}
/**
* 获取下载按钮文案
*/
public static String getDownloadBtnText(Context context, GameEntity gameEntity) {
int doneCount = 0; // 下载完成数量
int pluginCount = 0; // 可插件化数量
int updateCount = 0; // 可更新数量
int installCount = 0; // 已安装数量
DownloadEntity downloadEntity;
Object gh_id;
for (ApkEntity apkEntity : gameEntity.getApk()) {
downloadEntity = DownloadManager.getInstance(context).get(apkEntity.getUrl());
if (downloadEntity != null) {
if (downloadEntity.getStatus().equals(DownloadStatus.done)) {
doneCount++;
} else if (downloadEntity.isPluggable()) {
pluginCount++;
} else if (downloadEntity.isUpdate()) {
updateCount++;
}
}
if (PackageManager.isCanUpdate(gameEntity.getId(), apkEntity.getPackageName())) {
updateCount++;
}
if (PackageManager.isInstalled(apkEntity.getPackageName())) {
gh_id = PackageUtils.getMetaData(context, apkEntity.getPackageName(), "gh_id");
if (!PackageUtils.isSignature(context, apkEntity.getPackageName())) {
pluginCount++;
} else if (gh_id == null || gh_id.equals(gameEntity.getId())) {
installCount++;
}
}
}
if (doneCount != 0) {
return "安装";
} else if (pluginCount != 0) {
return "插件化";
} else if (updateCount != 0) {
return "更新";
} else if (installCount != 0) {
return "打开";
} else {
return "下载";
}
}
}

View File

@ -26,66 +26,50 @@ import java.util.TimeZone;
*/
public class GameViewUtils {
public static void setLabelList(Context context, LinearLayout labelLayout,
List<String> tag) {
public static void setLabelList(Context context, LinearLayout labelLayout, List<String> tag) {
labelLayout.removeAllViews();
if (tag == null || tag.isEmpty()) {
labelLayout.addView(getGameTagView(context, "官方版"));
labelLayout.addView(getGameTagView(context, "官方版", 0));
} else {
for (int i = 0, size = tag.size() > 3 ? 3 : tag.size(); i < size; i++) {
labelLayout.addView(getGameTagView(context, tag.get(i)));
if (i == size - 1) {
labelLayout.addView(getGameTagView(context, tag.get(i), 0));
} else {
labelLayout.addView(getGameTagView(context, tag.get(i), DisplayUtils.dip2px(context, 5)));
}
}
}
}
// 获取游戏标签列表视图
public static void setLabelList(Context context, LinearLayout labelLayout,
String tag) {
labelLayout.removeAllViews();
// 添加tag标签
if (tag != null && !tag.isEmpty()) {
String[] tags = tag.split(",");
for (int i = 0; i < tags.length; i++) {
labelLayout.addView(getGameTagView(context, tags[i]));
}
}
}
public static TextView getGameTagView(Context context, String tagStr) {
LayoutParams lp = new LayoutParams(
public static TextView getGameTagView(Context context, String tagStr, int rightMargin) {
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, DisplayUtils.dip2px(context, 5), 0);
lparams.rightMargin = rightMargin;
TextView tag = new TextView(context);
tag.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
tag.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
tag.setSingleLine(true);
tag.setText(tagStr);
if ("官方版".equals(tagStr) || "已关注".equals(tagStr)) {
tag.setBackgroundResource(R.drawable.border_red_bg);
tag.setTextColor(0xffbc2132);
} else if ("已安装".equals(tagStr)) {
tag.setBackgroundResource(R.drawable.border_blue_bg);
tag.setTextColor(0xff1BA4FC);
} else {
tag.setBackgroundResource(R.drawable.border_green_bg);
tag.setTextColor(0xff2ec991);
tag.setTextColor(context.getResources().getColor(R.color.tag_green));
} else {
tag.setBackgroundResource(R.drawable.border_blue_bg);
tag.setTextColor(context.getResources().getColor(R.color.theme));
}
tag.setLayoutParams(lp);
tag.setPadding(DisplayUtils.dip2px(context, 4),
DisplayUtils.dip2px(context, 2),
DisplayUtils.dip2px(context, 4),
DisplayUtils.dip2px(context, 2));
tag.setLayoutParams(lparams);
tag.setPadding(DisplayUtils.dip2px(context, 3),
0,
DisplayUtils.dip2px(context, 3),
DisplayUtils.dip2px(context, 1));
return tag;
}
public static String getGameTestDate(long testTime) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd",
Locale.CHINA);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
String testDate;
try {
long today = format.parse(format.format(new Date())).getTime();
long day = Long.parseLong(testTime + "000");

View File

@ -15,8 +15,7 @@ public class GzipUtils {
/*
* 数据压缩
*/
public static void compress(InputStream is, OutputStream os)
throws IOException {
public static void compress(InputStream is, OutputStream os) throws IOException {
GZIPOutputStream gos = null;
try {
gos = new GZIPOutputStream(os);
@ -38,8 +37,7 @@ public class GzipUtils {
/*
* 数据解压缩
*/
public static void decompress(InputStream is, OutputStream os)
throws IOException {
public static void decompress(InputStream is, OutputStream os) throws IOException {
GZIPInputStream gis = null;
try {
gis = new GZIPInputStream(is);
@ -112,4 +110,5 @@ public class GzipUtils {
}
}
}
}

View File

@ -16,6 +16,7 @@ import dalvik.system.PathClassLoader;
/* compiled from: ProGuard */
public final class HotFix {
public static void patch(Context context, String patchDexFile, String patchClassName) {
if (patchDexFile != null && new File(patchDexFile).exists()) {
try {
@ -153,4 +154,5 @@ public final class HotFix {
}
return newInstance;
}
}

View File

@ -0,0 +1,137 @@
package com.gh.common.util;
import android.content.Context;
import com.gh.gamecenter.R;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.internal.tls.OkHostnameVerifier;
/**
* Created by khy on 2016/10/8.
*
*/
public class HttpsUtils {
private static final TrustManager[] TRUST_MANAGERS = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
private static final HostnameVerifier HOSTNAME_VERIFIER = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
private static SSLSocketFactory mSSLSocketFactory;
private static HostnameVerifier mHostnameVerifier;
public static void initHttpsUrlConnection(Context context) {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyStore keyStore = getHttpsKeyStore(context);
if (keyStore != null) {
String algorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
tmf.init(keyStore);
sslContext.init(null, tmf.getTrustManagers(), null);
mHostnameVerifier = OkHostnameVerifier.INSTANCE;
} else {
sslContext.init(null, TRUST_MANAGERS, null);
mHostnameVerifier = HOSTNAME_VERIFIER;
}
mSSLSocketFactory = sslContext.getSocketFactory();
// HttpsURLConnection.setDefaultSSLSocketFactory(mSSLSocketFactory);
// HttpsURLConnection.setDefaultHostnameVerifier(mHostnameVerifier);
} catch (Exception e) {
e.printStackTrace();
}
}
private static KeyStore getHttpsKeyStore(Context context) {
InputStream is = null;
try {
is = context.getResources().openRawResource(R.raw.download);
//读取证书
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificateFactory.generateCertificate(is);
Certificate certificate = certificateFactory.generateCertificate(is);
//创建一个证书库,并将证书导入证书库
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("trust", certificate);
return keyStore;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static HttpsURLConnection getHttpsURLConnection(URL url) throws Exception {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
if ("apk2.ghzhushou.com".equals(url.getHost())
|| "download.ghzhushou.com".equals(url.getHost())) {
if (mSSLSocketFactory == null || mHostnameVerifier == null) {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, TRUST_MANAGERS, null);
mSSLSocketFactory = sslContext.getSocketFactory();
mHostnameVerifier = HOSTNAME_VERIFIER;
}
httpsURLConnection.setSSLSocketFactory(mSSLSocketFactory);
httpsURLConnection.setHostnameVerifier(mHostnameVerifier);
} else {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, TRUST_MANAGERS, null);
httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
httpsURLConnection.setHostnameVerifier(HOSTNAME_VERIFIER);
}
return httpsURLConnection;
}
}

View File

@ -1,151 +1,105 @@
package com.gh.common.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.content.res.Resources;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.view.ViewGroup;
import com.gh.common.view.CircleImageView;
import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.gh.gamecenter.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ImageUtils {
private static ImageUtils singleton;
private static ImageLoader imageLoader;
private static DisplayImageOptions options;
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
private static ImageUtils singleton;
public static ImageUtils getInstance(Context context) {
public static ImageUtils getInstance() {
if (singleton == null) {
synchronized (ImageUtils.class) {
if (singleton == null) {
singleton = new ImageUtils(context.getApplicationContext(),
(int) Runtime.getRuntime().maxMemory() / 10);
singleton = new ImageUtils();
return singleton;
}
}
}
return singleton;
}
private ImageUtils(Context context, int size) {
// 自适应图片宽高
public void display(final SimpleDraweeView simpleDraweeView, String url, final int width) {
ControllerListener<ImageInfo> listener = new BaseControllerListener<ImageInfo>(){
@Override
public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
if (imageInfo == null){
return;
}
ViewGroup.LayoutParams layoutParams = simpleDraweeView.getLayoutParams();
float scale = (float) imageInfo.getHeight() / (float) imageInfo.getWidth();
layoutParams.height = (int)(width * scale);
simpleDraweeView.setLayoutParams(layoutParams);
}
};
simpleDraweeView.setController(Fresco.newDraweeControllerBuilder()
.setUri(url)
.setControllerListener(listener)
.build());
}
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
// .showImageOnLoading(R.drawable.ocupy)
// .showImageForEmptyUri(R.drawable.ocupy)
// .showImageOnFail(R.drawable.ocupy)
// 设置缩放类型,设置按压状态下的叠加图
public void display(Resources resources, SimpleDraweeView simpleDraweeView,
ScalingUtils.ScaleType scaleType, String url) {
simpleDraweeView.setHierarchy(new GenericDraweeHierarchyBuilder(resources)
.setFadeDuration(500)
.setPressedStateOverlay(new ColorDrawable(resources.getColor(R.color.pressed_bg)))
.setPlaceholderImage(R.drawable.ocupy2, ScalingUtils.ScaleType.CENTER)
.setBackground(new ColorDrawable(resources.getColor(R.color.placeholder_bg)))
.setActualImageScaleType(scaleType)
.build());
simpleDraweeView.setImageURI(url);
}
// 设置占位符
public void display(Resources resources, SimpleDraweeView simpleDraweeView, String url, int placeholderImage) {
simpleDraweeView.setHierarchy(new GenericDraweeHierarchyBuilder(resources)
.setFadeDuration(500)
.setPressedStateOverlay(new ColorDrawable(resources.getColor(R.color.pressed_bg)))
.setBackground(new ColorDrawable(resources.getColor(R.color.placeholder_bg)))
.setPlaceholderImage(placeholderImage)
.build());
simpleDraweeView.setImageURI(url);
}
// 图片下载监听和设置低高分辨率图片
public void display(SimpleDraweeView simpleDraweeView, String url, String lowUrl,
ControllerListener<? super ImageInfo> listener) {
simpleDraweeView.setController(Fresco.newDraweeControllerBuilder()
.setImageRequest(ImageRequest.fromUri(url))
.setControllerListener(listener)
.setLowResImageRequest(ImageRequest.fromUri(lowUrl)) // 低分辨率图片
.build());
}
// 获取bitmap
public void display(Context context, String url, BaseBitmapDataSubscriber dataSubscriber) {
ImageRequest imageRequest = ImageRequestBuilder
.newBuilderWithSource(Uri.parse(url))
.setProgressiveRenderingEnabled(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).writeDebugLogs().build();
ImageLoader.getInstance().init(config);
imageLoader = ImageLoader.getInstance();
}
public void displayFile(String url, ImageView imageView) {
imageLoader.displayImage(url, imageView, options,
new ImageLoadingListener() {
@Override
public void onLoadingCancelled(String arg0, View arg1) {
}
@Override
public void onLoadingComplete(String arg0, View view,
Bitmap arg2) {
AlphaAnimation animation = new AlphaAnimation(0f, 1f);
animation.setDuration(500);
view.startAnimation(animation);
}
@Override
public void onLoadingFailed(String arg0, View arg1,
FailReason arg2) {
}
@Override
public void onLoadingStarted(String arg0, View arg1) {
}
});
}
public void display(String url, ImageView imageView, int drawable) {
display(url, imageView, drawable, ScaleType.FIT_XY, null);
}
public void display(final String url, final ImageView imageView,
final int drawable, final ScaleType scaleType,
final OnLoadingCompleteListener listener) {
imageLoader.displayImage(url, imageView, options,
new ImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
if (imageView instanceof CircleImageView) {
imageView.setScaleType(ScaleType.CENTER_CROP);
} else {
imageView.setScaleType(scaleType);
}
if (listener != null) {
listener.onLoadingComplete();
}
}
@Override
public void onLoadingStarted(String imageUri, View view) {
imageView.setScaleType(ScaleType.CENTER);
imageView.setImageResource(drawable);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason reason) {
}
});
}
public void display(String url, ImageView imageView, ScaleType scaleType) {
display(url, imageView, R.drawable.ocupy, scaleType, null);
}
public void display(String url, ImageView imageView) {
display(url, imageView, R.drawable.ocupy, ScaleType.FIT_XY, null);
}
public void display(String url, ImageView imageView, ScaleType scaleType, OnLoadingCompleteListener listener) {
display(url, imageView, R.drawable.ocupy, scaleType, listener);
}
public void display(String url, ImageView imageView, OnLoadingCompleteListener listener) {
display(url, imageView, R.drawable.ocupy, ScaleType.FIT_XY, listener);
}
public interface OnLoadingCompleteListener {
void onLoadingComplete();
Fresco.getImagePipeline()
.fetchDecodedImage(imageRequest, context)
.subscribe(dataSubscriber, CallerThreadExecutor.getInstance());
}
}

View File

@ -9,9 +9,11 @@ import java.io.RandomAccessFile;
import java.util.UUID;
public class Installation {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
private static String sID = null;
public synchronized static String getUUID(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
@ -42,4 +44,5 @@ public class Installation {
out.write(id.getBytes());
out.close();
}
}

View File

@ -74,4 +74,5 @@ public class MD5Utils {
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
}

View File

@ -0,0 +1,63 @@
package com.gh.common.util;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by khy on 2016/8/22.
* RecyclerView 自适应高度
*/
public class MeasureHeightLayoutManager extends LinearLayoutManager {
public MeasureHeightLayoutManager(Context context) {
super(context);
}
private int[] mMeasuredDimension = new int[1];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
height = height + mMeasuredDimension[0];
}
if (height > heightSize){
super.onMeasure(recycler, state, widthSpec, heightSpec);
}else {
setMeasuredDimension(View.MeasureSpec.getSize(widthSpec), height);
}
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view.getVisibility() == View.GONE) {
measuredDimension[0] = 0;
return;
}
super.measureChildWithMargins(view, 0, 0);
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childHeightSpec = ViewGroup.getChildMeasureSpec(
heightSpec,
getPaddingTop() + getPaddingBottom() + getDecoratedTop(view) + getDecoratedBottom(view),
p.height);
view.measure(0, childHeightSpec);
measuredDimension[0] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}

View File

@ -0,0 +1,441 @@
package com.gh.common.util;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gh.gamecenter.R;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.platformtools.Util;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* Created by khy on 2016/11/8.
*/
public class MessageShareUtils {
private static MessageShareUtils instance;
private Bitmap shareBm; //分享截图
private String picName;
private boolean isPlugin = false;
private static IWXAPI api;
private static Tencent mTencent;
private Handler handler;
private int[] arrLogo = {R.drawable.share_wechat_logo, R.drawable.share_wechatmoments_logo, R.drawable.share_qq_logo
, R.drawable.share_qzone_logo, R.drawable.share_save};
private String[] arrLabel = {"微信好友", "朋友圈", "QQ好友", "QQ空间", "保存"};
private PopupWindow popupWindow;
private Context context;
private Activity activity; // 用来关闭分享页面
public static MessageShareUtils getInstance(Context context) {
if (instance == null) {
instance = new MessageShareUtils();
mTencent = Tencent.createInstance("1104659243", context); //初始化QQ分享
api = WXAPIFactory.createWXAPI(context, "wx3ffd0785fad18396"); //初始化微信分享
}
instance.context = context;
return instance;
}
public void showShareWindows(View view, Bitmap bitmap, String picName, boolean ispopupWindow){
this.shareBm = bitmap;
this.picName = picName;
this.activity= (Activity) context;
RelativeLayout contentView = new RelativeLayout(context);
contentView.setBackgroundColor(0x8c000000);
contentView.setFocusable(true);
contentView.setFocusableInTouchMode(true);
RecyclerView shareRecyclerView = new RecyclerView(context);
shareRecyclerView.setPadding(DisplayUtils.dip2px(context, 10), DisplayUtils.dip2px(context, 10), DisplayUtils.dip2px(context, 10), 0);
shareRecyclerView.setBackgroundColor(Color.WHITE);
//RecyclerView禁止滑动
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 5){
@Override
public boolean canScrollVertically() {
return false;
}
};
shareRecyclerView.setLayoutManager(gridLayoutManager);
shareRecyclerView.setAdapter(new ShareRecyclerViewAdapter());
if (!ispopupWindow) {
LinearLayout llBottom = (LinearLayout) view;
ViewGroup.LayoutParams layoutParams = llBottom.getLayoutParams();
layoutParams.height = DisplayUtils.dip2px(context, 100);
llBottom.addView(shareRecyclerView);
return;
}
RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
, DisplayUtils.dip2px(context, 106));
rlParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
contentView.addView(shareRecyclerView,rlParams);
popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT
, LinearLayout.LayoutParams.MATCH_PARENT, true);
popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
contentView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0 && popupWindow != null
&& popupWindow.isShowing()) {
popupWindow.dismiss();
}
return false;
}
});
}
public class ShareRecyclerViewAdapter extends RecyclerView.Adapter<ShareRecyclerViewAdapter.ViewHolder>{
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DisplayUtils.dip2px(context, 90)));
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
linearLayout.setBackgroundResource(R.drawable.cardview_item_style);
ImageView shareLogo = new ImageView(context);
LinearLayout.LayoutParams logoParams = new LinearLayout.LayoutParams(DisplayUtils.dip2px(context, 43), DisplayUtils.dip2px(context, 43));
logoParams.setMargins(0, DisplayUtils.dip2px(context, 10), 0, 0);
shareLogo.setLayoutParams(logoParams);
TextView shareLabel = new TextView(context);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, DisplayUtils.dip2px(context,10), 0, 0);
shareLabel.setLayoutParams(layoutParams);
shareLabel.setGravity(Gravity.CENTER);
shareLabel.setTextColor(Color.parseColor("#3a3a3a"));
shareLabel.setTextSize(13);
linearLayout.addView(shareLogo);
linearLayout.addView(shareLabel);
return new ViewHolder(linearLayout);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.shareLogo.setImageResource(arrLogo[position]);
holder.shareLabel.setText(arrLabel[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (holder.getPosition()){
case 0:
wechatSahre();
activity.finish();
break;
case 1:
wechatMomentsSahre();
activity.finish();
break;
case 2:
qqSahre();
break;
case 3:
qZoneSahre();
break;
case 4:
String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/ghzhushou/";
writeBitmap(savePath, "gh-" + new Date().getTime() + ".jpg", shareBm, true);
if (popupWindow == null) return;
popupWindow.dismiss();
activity.finish();
break;
}
}
});
}
@Override
public int getItemCount() {
return arrLogo.length;
}
public class ViewHolder extends RecyclerView.ViewHolder{
LinearLayout linearLayout;
TextView shareLabel;
ImageView shareLogo;
public ViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView;
shareLogo = (ImageView) linearLayout.getChildAt(0);
shareLabel = (TextView) linearLayout.getChildAt(1);
}
}
}
//QQ分享
private void qqSahre(){
Utils.toast(context,"分享跳转中...");
Bundle params = new Bundle();
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
QQShare.SHARE_TO_QQ_TYPE_IMAGE);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, context.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "光环助手");
params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,
QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
mTencent.shareToQQ(
(Activity) context, params,QqShareListener);
if (popupWindow == null) return;
popupWindow.dismiss();
}
//QQ空间分享
private void qZoneSahre(){
Utils.toast(context,"分享跳转中...");
Bundle params = new Bundle();
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
QQShare.SHARE_TO_QQ_TYPE_IMAGE);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, context.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "光环助手");
params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,
QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
mTencent.shareToQQ(
(Activity) context, params,QqShareListener);
if (popupWindow == null) return;
popupWindow.dismiss();
}
//微信好友分享
private void wechatSahre(){
Utils.toast(context,"分享跳转中...");
//官方分享
// WXImageObject imgObj = new WXImageObject();
// imgObj.setImagePath(context.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
// WXMediaMessage msg = new WXMediaMessage();
// msg.mediaObject = imgObj;
//
// SendMessageToWX.Req req = new SendMessageToWX.Req();
// req.transaction = buildTransaction("img");
// req.message = msg;
// req.scene = SendMessageToWX.Req.WXSceneSession;
//
// Bitmap compressBp = compressBitmap(shareBm);
// msg.thumbData = Util.bmpToByteArray(compressBp, true);
// api.sendReq(req);
//调用手机系统分享
try {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + context.getExternalCacheDir().getPath() + "/ShareImg/" + picName));
intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI"));
context.startActivity(intent);
} catch (Exception e) {
Utils.toast(context,"分享失败!请检查是否已安装微信");
e.printStackTrace();
}
if (popupWindow == null) return;
popupWindow.dismiss();
}
//微信朋友圈分享
private void wechatMomentsSahre(){
Utils.toast(context,"分享跳转中...");
WXImageObject imgObj = new WXImageObject();
imgObj.setImagePath(context.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = imgObj;
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("img");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneTimeline;
Bitmap compressBp = compressBitmap(shareBm);
msg.thumbData = Util.bmpToByteArray(compressBp, true);
api.sendReq(req);
if (popupWindow == null) return;
popupWindow.dismiss();
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
//压缩图片
private Bitmap compressBitmap(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);
float zoom = (float) Math.sqrt(10 * 1024 / (float) bos.toByteArray().length);
Matrix matrix = new Matrix();
matrix.setScale(zoom, zoom);
Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bos.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, bos);
while(bos.toByteArray().length > 10 * 1024){
System.out.println(bos.toByteArray().length);
matrix.setScale(0.9f, 0.9f);
result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
bos.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, bos);
}
return result;
}
//QQ或者QQ空间分享回调处理
public IUiListener QqShareListener = new IUiListener() {
@Override
public void onComplete(Object o) {
activity.finish();
activity.overridePendingTransition(0, 0);//禁止退出Activity 动画
Utils.toast(context, "分享成功");
}
@Override
public void onError(UiError uiError) {
Utils.toast(context, "分享失败");
}
@Override
public void onCancel() {
activity.finish();
activity.overridePendingTransition(0, 0);//禁止退出Activity 动画
Utils.toast(context, "分享已取消");
}
};
//检查是否安装手机QQ
public static boolean isQQClientAvailable(Context context){
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
if (pinfo != null) {
for (int i = 0; i < pinfo.size(); i++) {
String pn = pinfo.get(i).packageName; if (pn.equals("com.tencent.mobileqq")) {
return true;
}
}
}
return false;
}
//写到存储卡中
public void writeBitmap(String path, String name, Bitmap bitmap, boolean isToast) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
File _file = new File(path , name);
if (_file.exists()) {
_file.delete();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(_file);
if (name != null && !"".equals(name)) {
int index = name.lastIndexOf(".");
if (index != -1 && (index + 1) < name.length()) {
String extension = name.substring(index + 1).toLowerCase();
if ("png".equals(extension)) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} else if ("jpg".equals(extension)
|| "jpeg".equals(extension)) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
}
if (isToast) {
Utils.toast(context,"成功保存到相册");
//刷新手机图片库
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(_file);
intent.setData(uri);
context.sendBroadcast(intent);
Utils.log("保存分享图片路径:" + _file.getAbsolutePath());
}
}
}
} catch (FileNotFoundException e) {
Utils.log("消息分享异常" + e.toString());
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

View File

@ -9,8 +9,7 @@ public class NetworkUtils {
/**
* 判断是否有网络连接
*
* @param context
* 上下文
* @param context 上下文
* @return true 有网络连接 false 无网络连接
*/
public static boolean isNetworkConnected(Context context) {
@ -29,8 +28,7 @@ public class NetworkUtils {
/**
* 判断WIFI网络是否可用
*
* @param context
* 上下文
* @param context 上下文
* @return true wifi可用 false wifi不可用
*/
public static boolean isWifiConnected(Context context) {
@ -49,8 +47,7 @@ public class NetworkUtils {
/**
* 判断MOBILE网络是否可用
*
* @param context
* 上下文
* @param context 上下文
* @return true mobile可用 false mobile不可用
*/
public static boolean isMobileConnected(Context context) {
@ -106,4 +103,5 @@ public class NetworkUtils {
}
return "NONE";
}
}

View File

@ -2,19 +2,29 @@ package com.gh.common.util;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.widget.TextView;
import com.gh.gamecenter.NewsActivity;
import com.android.volley.Request;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.gamecenter.MessageDetailActivity;
import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.NewsDetailsEntity;
import com.gh.gamecenter.entity.ConcernEntity;
import com.gh.gamecenter.entity.NewsEntity;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class NewsUtils {
/**
* 根据新闻类型获取标签背景资源
*
* @param type
* @return
*/
public static int getDrawableIdByType(String type) {
if ("活动".equals(type) || "高阶".equals(type)) {
@ -30,24 +40,105 @@ public class NewsUtils {
/**
* 启动新闻详情页面
*
* @param context
* @param newsEntity
* @param entrance
* @return
*/
public static void startNewsActivity(Context context,
NewsEntity newsEntity, String entrance) {
Intent intent = new Intent(context, NewsActivity.class);
NewsDetailsEntity entity = new NewsDetailsEntity();
entity.setId(newsEntity.getId());
entity.setTitle(newsEntity.getTitle());
entity.setType(newsEntity.getType());
entity.setTime(newsEntity.getPublishOn());
intent.putExtra("entity", entity);
public static void startNewsActivity(Context context, NewsEntity newsEntity, String entrance) {
Intent intent = new Intent(context, NewsDetailActivity.class);
intent.putExtra("id", newsEntity.getId());
intent.putExtra("title", newsEntity.getTitle());
intent.putExtra("type", newsEntity.getType());
intent.putExtra("entrance", entrance);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 启动消息详情页面
*/
public static void startMessageActivity(Context context, ConcernEntity concernEntity, String entrance) {
AppController.put("ConcernEntity", concernEntity);
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra("entrance", entrance);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 统计阅读量
*/
public static void statNewsViews(String news_id) {
String url = Config.DATA_HOST + "news/stat?news_id=" + news_id;
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Request.Method.POST, url, null, null);
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
/**
* 去除与重复sourceList相同的数据
*/
public static List<NewsEntity> removeDuplicateData(List<NewsEntity> sourceList, List<NewsEntity> rawList) {
if (sourceList == null || sourceList.isEmpty()
|| rawList == null || rawList.isEmpty()) {
return rawList;
}
String id;
for (int i = 0; i < rawList.size(); i++) {
id = rawList.get(i).getId();
for (NewsEntity newsEntity : sourceList) {
if (id.equals(newsEntity.getId())) {
rawList.remove(i);
i--;
break;
}
}
}
return rawList;
}
/**
* 设置新闻类型
*/
public static void setNewsType(TextView textView, String type) {
textView.setText(type);
textView.setTextColor(Color.WHITE);
if ("活动".equals(type)) {
textView.setBackgroundResource(R.drawable.textview_orange_style);
} else if ("公告".equals(type)) {
textView.setBackgroundResource(R.drawable.textview_red_style);
} else if ("评测".equals(type)) {
textView.setBackgroundResource(R.drawable.textview_red_style);
} else if ("杂谈".equals(type)) {
textView.setBackgroundResource(R.drawable.textview_orange_style);
} else if ("专题".equals(type)) {
textView.setBackgroundResource(R.drawable.textview_blue_style);
} else {
textView.setBackgroundResource(R.drawable.textview_blue_style);
}
}
/**
* 设置新闻发布时间
*/
public static void setNewsPublishOn(TextView textView, long time) {
time = time * 1000;
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
try {
long today = format.parse(format.format(new Date())).getTime();
if (time >= today && time < today + 86400 * 1000) {
format.applyPattern("HH:mm");
textView.setText(String.format("今天 %s", format.format(time)));
} else if (time >= today - 86400 * 1000 && time < today) {
format.applyPattern("HH:mm");
textView.setText(String.format("昨天 %s", format.format(time)));
} else {
format.applyPattern("yyyy年MM月dd日 HH:mm");
textView.setText(format.format(time));
}
} catch (ParseException e) {
e.printStackTrace();
format.applyPattern("yyyy年MM月dd日 HH:mm");
textView.setText(format.format(time));
}
}
}

View File

@ -0,0 +1,85 @@
package com.gh.common.util;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.R;
/**
* Created by LGT on 2016/10/10.
*/
public class NotificationUtils {
public static void showDownloadDoneNotification(Context context, DownloadEntity downloadEntity, int flag) {
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent();
intent.putExtra("path", downloadEntity.getPath());
intent.setAction("com.gh.gamecenter.INSTALL");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, flag,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
String text;
String title;
if (downloadEntity.isPluggable()) {
text = "下载完成,点击继续插件化";
title = downloadEntity.getName() + "-"
+ PlatformUtils.getInstance(context).getPlatformName(downloadEntity.getPlatform());
} else {
if (downloadEntity.isPlugin()) {
text = downloadEntity.getName() + "-"
+ PlatformUtils.getInstance(context).getPlatformName(downloadEntity.getPlatform()) + " 下载完成";
} else {
text = downloadEntity.getName() + " 下载完成";
}
title = "点击立即安装";
}
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setTicker(text)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(pendingIntent).build();
// notification.defaults = Notification.DEFAULT_SOUND;// 添加系统默认声音
notification.flags |= Notification.FLAG_AUTO_CANCEL; // // FLAG_AUTO_CANCEL表明当通知被用户点击时通知将被清除。
nManager.notify(flag, notification);
}
public static void showDownloadingNotification(Context context) {
int downloadingSize = 0;
for (DownloadEntity entity : DownloadManager.getInstance(context).getAll()) {
if (entity.getStatus().equals(DownloadStatus.downloading)
|| entity.getStatus().equals(DownloadStatus.waiting)
|| entity.getStatus().equals(DownloadStatus.pause)
|| entity.getStatus().equals(DownloadStatus.timeout)
|| entity.getStatus().equals(DownloadStatus.neterror)) {
downloadingSize++;
}
}
if (downloadingSize == 0) {
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.cancel(0x123);
} else {
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent();
intent.setAction("com.gh.gamecenter.DOWNLOAD");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0x123,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setTicker("你有" + downloadingSize + "个游戏正在下载中")
.setContentTitle("点击查看详情")
.setContentText("你有" + downloadingSize + "个游戏正在下载中")
.setContentIntent(pendingIntent).build();
// notification.defaults = Notification.DEFAULT_SOUND;// 添加系统默认声音
notification.flags |= Notification.FLAG_NO_CLEAR; // 通知无法手动清除
nManager.notify(0x123, notification);
}
}
}

View File

@ -9,18 +9,14 @@ import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.Toast;
import com.gh.gamecenter.entity.GameUpdateEntity;
import com.gh.gamecenter.manager.FilterManager;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
@ -31,65 +27,6 @@ public class PackageUtils {
public static final String publicKey = "OpenSSLRSAPublicKey{modulus=a8c4bb5748fec8d5c35db1a7a182d41ba4721a91131a417330af79ef4ddb43f9fa0ff4907b0a613bfe152de0ed8fc1b2e6f94a908aa98a5f7adc1ce814ba7ec919d75d9910bdfd8649b4789da6a90ffb61f0d23ac4f828a78fcd0d6f6120c1c43c1f87f7498a89eb40ca8e32dfc2f9d5c10d612b95192870223674e241e53305abf320d7eed76ded398778576e4db7b17b3bc6a792f13de5e43a6a5fae4276c73e6990ce97f68dff0ec16fc9594f175c8d49cd0d7877340d9de60942ca0efc737e50b6c295dfe0713e4532b4e810e1ea11b702b4a27753e41559cbceb247e7f044ec4e3ab2e8bccd8b9fd71286e63307550bcde86deee95adb8133076269135b,publicExponent=10001}";
/*
* 根据apk路径获取apk的签名信息,耗时
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String getApkSignatureByPath(Context context, String path) {
String PATH_PackageParser = "android.content.pm.PackageParser";
try {
// apk包的文件路径
// 这是一个Package 解释器, 是隐藏的
// 构造函数的参数只有一个, apk文件的路径
// PackageParser packageParser = new PackageParser(apkPath);
Class pkgParserCls = Class.forName(PATH_PackageParser);
Class[] typeArgs = new Class[1];
typeArgs[0] = String.class;
Constructor pkgParserCt = pkgParserCls.getConstructor(typeArgs);
Object[] valueArgs = new Object[1];
valueArgs[0] = path;
Object pkgParser = pkgParserCt.newInstance(valueArgs);
// 这个是与显示有关的, 里面涉及到一些像素显示等等, 我们使用默认的情况
DisplayMetrics metrics = new DisplayMetrics();
metrics.setToDefaults();
// PackageParser.Package mPkgInfo = packageParser.parsePackage(new
// File(apkPath), apkPath,
// metrics, 0);
typeArgs = new Class[4];
typeArgs[0] = File.class;
typeArgs[1] = String.class;
typeArgs[2] = DisplayMetrics.class;
typeArgs[3] = Integer.TYPE;
Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod(
"parsePackage", typeArgs);
valueArgs = new Object[4];
valueArgs[0] = new File(path);
valueArgs[1] = path;
valueArgs[2] = metrics;
valueArgs[3] = PackageManager.GET_SIGNATURES;
Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser,
valueArgs);
typeArgs = new Class[2];
typeArgs[0] = pkgParserPkg.getClass();
typeArgs[1] = Integer.TYPE;
Method pkgParser_collectCertificatesMtd = pkgParserCls
.getDeclaredMethod("collectCertificates", typeArgs);
valueArgs = new Object[2];
valueArgs[0] = pkgParserPkg;
valueArgs[1] = PackageManager.GET_SIGNATURES;
pkgParser_collectCertificatesMtd.invoke(pkgParser, valueArgs);
// 应用程序信息包, 这个公开的, 不过有些函数, 变量没公开
Field packageInfoFld = pkgParserPkg.getClass().getDeclaredField(
"mSignatures");
Signature[] info = (Signature[]) packageInfoFld.get(pkgParserPkg);
return parseSignature(info[0].toByteArray())[0];
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*
* 根据路径获取apk的包名
*/
@ -104,6 +41,9 @@ public class PackageUtils {
return null;
}
/*
* 获取meta-data
*/
public static Object getMetaData(Context context, String packageName, String name) {
try {
Bundle metaDate = context.getPackageManager().getApplicationInfo(
@ -120,8 +60,7 @@ public class PackageUtils {
/*
* 根据包名获取apk的签名信息
*/
public static String getApkSignatureByPackageName(Context context,
String packageName) {
public static String getApkSignatureByPackageName(Context context, String packageName) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
@ -133,6 +72,83 @@ public class PackageUtils {
return null;
}
/*
* 判断是否可以更新只判断gh_version的大小
*/
public static boolean isCanUpdate(Context context, GameUpdateEntity gameUpdateEntity) {
// 判断是否gh_version是否存在
String gh_version = (String) PackageUtils.getMetaData(
context, gameUpdateEntity.getPackageName(), "gh_version");
if (gh_version != null) {
gh_version = gh_version.substring(2);
// 判断gh_version的大小
return Long.parseLong(gh_version) < Long.parseLong(gameUpdateEntity.getGhVersion());
} else {
return false;
}
}
/*
* 判断是否是插件包
*/
public static boolean isSignature(Context context, String packageName) {
String signature = getApkSignatureByPackageName(context, packageName);
return publicKey.equals(signature);
}
/*
* 根据apk路径获取apk包名、签名 根据包名 判断 是否已安装游戏 根据签名 判断 是否一致
*/
public static boolean isCanLaunchSetup(Context context, String path) {
String packageName = getPackageNameByPath(context, path);
if (TextUtils.isEmpty(packageName)) {
return true;
}
boolean isContain = com.gh.gamecenter.manager.PackageManager.isInstalled(packageName);
if (!isContain) {
return true;
}
boolean isInstalled = isInstalled(context, packageName);
if (!isInstalled) {
return true;
}
String signature = getApkSignatureByPackageName(context, packageName);
return publicKey.equals(signature);
}
/*
* 启动安装应用程序
*/
public static void launchSetup(final Context context, final String path) {
if (isCanLaunchSetup(context, path)) {
context.startActivity(PackageUtils.getInstallIntent(path));
} else {
DialogUtils.showPluginDialog(context, new DialogUtils.ConfiremListener() {
@Override
public void onConfirem() {
context.startActivity(PackageUtils.getUninstallIntent(context, path));
}
});
}
}
/*
* 获取应用第一次安装的时间
*/
public static long getInstalledTime(Context context, String packageName) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, 0);
return packageInfo.firstInstallTime;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return 0;
}
/*
* 解析签名
*/
@ -165,6 +181,9 @@ public class PackageUtils {
return null;
}
/*
* 获取apk的版本
*/
public static String getVersionByPackage(Context context, String packageName) {
try {
return context.getPackageManager().getPackageInfo(packageName,
@ -175,11 +194,13 @@ public class PackageUtils {
return null;
}
/*
* 获取所有已安装的软件的包名、版本(非系统应用)
*/
public static ArrayList<String> getAllPackageName(Context context) {
FilterManager filterManager = new FilterManager(context);
ArrayList<String> list = new ArrayList<String>();
List<PackageInfo> packageInfos = context.getPackageManager()
.getInstalledPackages(0);
ArrayList<String> list = new ArrayList<>();
List<PackageInfo> packageInfos = context.getPackageManager().getInstalledPackages(0);
for (int i = 0, size = packageInfos.size(); i < size; i++) {
PackageInfo packageInfo = packageInfos.get(i);
if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
@ -193,6 +214,9 @@ public class PackageUtils {
return list;
}
/*
* 启动应用
*/
public static void launchApplicationByPackageName(Context context,
String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(
@ -224,33 +248,8 @@ public class PackageUtils {
* 根据包名,判断是否已安装该游戏
*/
public static boolean isInstalled(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(
packageName);
if (intent == null) {
return false;
}
return true;
}
private static ArrayMap<String, Boolean> map;
public static boolean isContain(Context context, String packageName) {
if (TextUtils.isEmpty(packageName)) {
return false;
}
if (map == null) {
map = new ArrayMap<String, Boolean>();
List<PackageInfo> infos = context.getPackageManager()
.getInstalledPackages(0);
for (PackageInfo info : infos) {
map.put(info.packageName, true);
}
}
Boolean b = map.get(packageName);
if (b != null) {
return true;
}
return false;
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
return intent != null;
}
/*
@ -277,13 +276,4 @@ public class PackageUtils {
return installIntent;
}
public static String getInstalledApkPath(Context context, String packageName) {
try {
return context.getPackageManager().getApplicationInfo(packageName,
0).sourceDir;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -11,19 +11,17 @@ import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.gamecenter.R;
import com.gh.gamecenter.SplashScreenActivity;
import com.gh.gamecenter.eventbus.EBPlatformChanged;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Properties;
@ -33,15 +31,15 @@ import de.greenrobot.event.EventBus;
public class PlatformUtils {
private static PlatformUtils mInstance;
private Context context;
private ArrayMap<String, String> platformMap;
private ArrayMap<String, Integer> platformPicMap;
private ArrayMap<String, String> platformPicUrlMap;
private ArrayMap<String, String> platformColorMap;
private static PlatformUtils mInstance;
private Context context;
private PlatformUtils(Context con) {
this.context = con.getApplicationContext();
initMap();
@ -55,7 +53,7 @@ public class PlatformUtils {
}
private void initMap() {
ArrayMap<String, Integer> platformPicMap = new ArrayMap<String, Integer>();
ArrayMap<String, Integer> platformPicMap = new ArrayMap<>();
platformPicMap.put("360", R.drawable.platform_360);
platformPicMap.put("37wan", R.drawable.platform_37);
platformPicMap.put("91", R.drawable.platform_91);
@ -74,7 +72,7 @@ public class PlatformUtils {
platformPicMap.put("vivo", R.drawable.platform_vivo);
platformPicMap.put("wdj", R.drawable.platform_wdj);
ArrayMap<String, String> platformColorMap = new ArrayMap<String, String>();
ArrayMap<String, String> platformColorMap = new ArrayMap<>();
platformColorMap.put("360", "#218FA4");
platformColorMap.put("37wan", "#F5BD20");
platformColorMap.put("91", "#6A63CB");
@ -93,8 +91,8 @@ public class PlatformUtils {
platformColorMap.put("vivo", "#3FA5E3");
platformColorMap.put("wdj", "#5ABA3F");
ArrayMap<String, String> platformMap = new ArrayMap<String, String>();
ArrayMap<String, String> platformPicUrlMap = new ArrayMap<String, String>();
ArrayMap<String, String> platformMap = new ArrayMap<>();
ArrayMap<String, String> platformPicUrlMap = new ArrayMap<>();
SharedPreferences sharedPreferences = context.getSharedPreferences(
"gh_platform", Context.MODE_PRIVATE);
@ -104,7 +102,7 @@ public class PlatformUtils {
try {
properties
.load(context.getAssets().open("platform.properties"));
Set<String> pset = new HashSet<String>();
Set<String> pset = new HashSet<>();
for (Object object : properties.keySet()) {
platformMap.put(object.toString(),
(String) properties.get(object));
@ -118,7 +116,7 @@ public class PlatformUtils {
e.printStackTrace();
}
} else {
ArrayList<String> urls = new ArrayList<String>();
ArrayList<String> urls = new ArrayList<>();
for (String str : set) {
String[] platform = str.split("=");
platformMap.put(platform[0], platform[1]);
@ -177,7 +175,7 @@ public class PlatformUtils {
+ url.substring(url.lastIndexOf("/") + 1);
try {
int code = FileUtils.downloadFile(url, savePath);
if (code == HttpStatus.SC_OK) {
if (code == HttpURLConnection.HTTP_OK) {
success++;
}
} catch (IOException e) {
@ -189,7 +187,7 @@ public class PlatformUtils {
handler.post(new Runnable() {
@Override
public void run() {
EventBus.getDefault().post(new EBPlatformChanged());
EventBus.getDefault().post(new EBReuse("PlatformChanged"));
}
});
}
@ -201,30 +199,24 @@ public class PlatformUtils {
}
}
public ArrayMap<String, String> getPlatformMap() {
return platformMap;
}
public String getPlatformColor(String platform) {
if ("".equals(platform) || "官方版".equals(platform)
|| "local_plugin".equals(platform)) {
if ("".equals(platform) || "官方版".equals(platform)) {
return "#BB3D42";
}
String color = platformColorMap.get(platform);
if (color != null) {
return color;
}
return "#1BA4FC";
return "#00B7FA";
}
public int getPlatformPic(String platform) {
if ("".equals(platform) || "官方版".equals(platform)
|| "local_plugin".equals(platform)) {
if ("".equals(platform) || "官方版".equals(platform)) {
return R.drawable.platform_gf;
}
Integer id = platformPicMap.get(platform);
if (id != null) {
return id.intValue();
return id;
}
return 0;
}
@ -244,7 +236,7 @@ public class PlatformUtils {
}
}
if (path == null && !isCheck) {
ArrayList<String> urls = new ArrayList<String>();
ArrayList<String> urls = new ArrayList<>();
for (String value : platformPicUrlMap.values()) {
urls.add(value);
}
@ -255,11 +247,14 @@ public class PlatformUtils {
}
public String getPlatformName(String platform) {
if ("".equals(platform) || "官方版".equals(platform)
|| "local_plugin".equals(platform)) {
if ("".equals(platform) || "官方版".equals(platform)) {
return "官方版";
}
return platformMap.get(platform);
String platformName = platformMap.get(platform);
if (TextUtils.isEmpty(platformName)) {
getPlatform();
}
return platformName;
}
boolean isUpdate = false;
@ -270,32 +265,25 @@ public class PlatformUtils {
}
isUpdate = true;
JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
TimestampUtils.addTimestamp(Config.HOST
+ "v1d45/support/setting/platform",
Constants.PLATFORM_CD),
Config.HOST + "support/setting/platform",
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
Set<String> pset = new HashSet<String>();
Set<String> platformSet = new HashSet<>();
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response
.getJSONObject(i);
JSONObject jsonObject = response.getJSONObject(i);
String code = jsonObject.getString("code");
String name = jsonObject.getString("name");
String pic = jsonObject.getString("pic");
String color = jsonObject.getString("color");
pset.add(code + "=" + name + "=" + pic + "="
+ color);
platformSet.add(code + "=" + name + "=" + pic + "=" + color);
}
SharedPreferences sharedPreferences = context
.getSharedPreferences("gh_platform",
Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putStringSet("platform", pset);
editor.apply();
SharedPreferences sp = context.getSharedPreferences(
"gh_platform", Context.MODE_PRIVATE);
sp.edit().putStringSet("platform", platformSet).apply();
initMap();
EventBus.getDefault().post(new EBPlatformChanged());
EventBus.getDefault().post(new EBReuse("PlatformChanged"));
} catch (JSONException e) {
e.printStackTrace();
}
@ -307,6 +295,7 @@ public class PlatformUtils {
isUpdate = false;
}
});
AppController.addToRequestQueue(request, SplashScreenActivity.class);
AppController.addToRequestQueue(request);
}
}

View File

@ -0,0 +1,97 @@
package com.gh.common.util;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.gh.gamecenter.volley.extended.StringExtendedRequest;
import org.json.JSONObject;
/**
* Created by khy on 2016/11/9.
*
*/
public class PostCommentUtils {
public static void addCommentData(Context context, String url, String content, PostCommentListener listener) {
addCommentData(context, url, content, true, listener);
}
public static void addCommentData(final Context context, final String url, final String content,
final boolean isCheck, final PostCommentListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Request.Method.POST, url, content,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (listener != null){
listener.postSucced(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null && error.networkResponse.statusCode == 401) {
addCommentData(context, url, content, false, listener);
return;
}
if (listener != null){
listener.postFailed(error);
}
}
});
request.setShouldCache(false);
request.addHeader("TOKEN", TokenUtils.getToken(context, isCheck));
AppController.addToRequestQueue(request);
}
}).start();
}
public static void addCommentVoto(final Context context, final String newsId, final PostCommentListener listener) {
addCommentVoto(context, newsId, true, listener);
}
public static void addCommentVoto(final Context context, final String newsId, final boolean isCheck
, final PostCommentListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.POST, Config.COMMENT_HOST + "comment/" + newsId + "/vote",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
listener.postSucced(null);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null && error.networkResponse.statusCode == 401) {
addCommentVoto(context, newsId, false,listener);
} else {
listener.postFailed(error);
}
}
});
request.setShouldCache(false);
request.addHeader("TOKEN", TokenUtils.getToken(context, isCheck));
AppController.addToRequestQueue(request);
}
}).start();
}
public interface PostCommentListener {
void postSucced(JSONObject response);
void postFailed(VolleyError error);
}
}

View File

@ -43,7 +43,6 @@ public class RSEUtils {
* 使用公钥加密
*
* @param content
* @param key
* @return
*/
public static String encryptByPublic(String content) {
@ -68,10 +67,7 @@ public class RSEUtils {
/**
* 使用公钥解密
*
* @param content
* 密文
* @param key
* 商户私钥
* @param content 密文
* @return 解密后的字符串
*/
public static String decryptByPublic(String content) {

View File

@ -17,7 +17,7 @@ public class RandomUtils {
if (i == 0) {
index[i] = random.nextInt(size);
} else {
random(random, index, i, size);
index[i] = random(random, index, i, size);
}
}
return index;

View File

@ -13,7 +13,7 @@ public class RunningUtils {
/**
* 判断当前应用程序处于前台还是后台
*/
public static boolean isApplicationBroughtToBackground(final Context context) {
public static boolean isApplicationBroughtToBackground(Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
@ -85,8 +85,8 @@ public class RunningUtils {
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> infos = activityManager.getRunningTasks(100);
for (RunningTaskInfo info : infos) {
if (info.topActivity.getPackageName().equals(
context.getPackageName())) {
if (info.topActivity.getPackageName().equals(context.getPackageName())
&& info.baseActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}

View File

@ -0,0 +1,494 @@
package com.gh.common.util;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.gh.gamecenter.R;
import com.gh.gamecenter.WeiBoShareActivity;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.mm.sdk.platformtools.Util;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by khy on 2016/9/4.
*/
public class ShareUtils {
private static ShareUtils instance;
private String shareUrl;
private String shareGameName;
private String shareIcon;
private String shareNewsTitle; // shareNewsTitle不为空就是新闻分享否则是游戏分享
private boolean isPlugin = false;
private static IWXAPI api;
private static Tencent mTencent;
private Handler handler;
private int[] arrLogo = {R.drawable.share_wechat_logo, R.drawable.share_wechatmoments_logo, R.drawable.share_qq_logo
, R.drawable.share_qzone_logo, R.drawable.share_sinaweibo_logo, R.drawable.share_shortmessage_logo
, R.drawable.share_copyfont_logo, R.drawable.share_cancel_logo};
private String[] arrLabel = {"微信好友", "朋友圈", "QQ好友", "QQ空间", "新浪微博", "短信", "复制链接", "取消"};
private PopupWindow popupWindow;
private Context context;
public static ShareUtils getInstance(Context context) {
if (instance == null) {
instance = new ShareUtils();
mTencent = Tencent.createInstance("1104659243", context); //初始化QQ分享
api = WXAPIFactory.createWXAPI(context, "wx3ffd0785fad18396"); //初始化微信分享
}
instance.context = context;
return instance;
}
public void showShareWindows(View view, String url, String gameName, String icon ,String newsTitle, boolean isPlugin){
this.shareIcon = icon;
this.shareGameName = gameName;
this.shareUrl = url;
this.shareNewsTitle = newsTitle;
this.isPlugin = isPlugin;
RelativeLayout contentView = new RelativeLayout(context);
contentView.setBackgroundColor(0x8c000000);
contentView.setFocusable(true);
contentView.setFocusableInTouchMode(true);
RecyclerView shareRecyclerView = new RecyclerView(context);
shareRecyclerView.setPadding(DisplayUtils.dip2px(context, 20), DisplayUtils.dip2px(context, 10), DisplayUtils.dip2px(context, 20), 0);
shareRecyclerView.setBackgroundColor(Color.WHITE);
//RecyclerView禁止滑动
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 4){
@Override
public boolean canScrollVertically() {
return false;
}
};
shareRecyclerView.setLayoutManager(gridLayoutManager);
shareRecyclerView.setAdapter(new ShareRecyclerViewAdapter());
RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
, DisplayUtils.dip2px(context, 200));
rlParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
contentView.addView(shareRecyclerView,rlParams);
popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT
, LinearLayout.LayoutParams.MATCH_PARENT, true);
popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
contentView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0 && popupWindow != null
&& popupWindow.isShowing()) {
popupWindow.dismiss();
}
return false;
}
});
}
private class ShareRecyclerViewAdapter extends RecyclerView.Adapter<ShareRecyclerViewAdapter.ViewHolder>{
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DisplayUtils.dip2px(context, 90)));
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
linearLayout.setBackgroundResource(R.drawable.cardview_item_style);
ImageView shareLogo = new ImageView(context);
LinearLayout.LayoutParams logoParams = new LinearLayout.LayoutParams(DisplayUtils.dip2px(context, 45), DisplayUtils.dip2px(context, 45));
logoParams.setMargins(0, DisplayUtils.dip2px(context, 10), 0, 0);
shareLogo.setLayoutParams(logoParams);
TextView shareLabel = new TextView(context);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, DisplayUtils.dip2px(context,10), 0, 0);
shareLabel.setLayoutParams(layoutParams);
shareLabel.setGravity(Gravity.CENTER);
shareLabel.setTextColor(Color.parseColor("#3a3a3a"));
shareLabel.setTextSize(13);
linearLayout.addView(shareLogo);
linearLayout.addView(shareLabel);
return new ViewHolder(linearLayout);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.shareLogo.setImageResource(arrLogo[position]);
holder.shareLabel.setText(arrLabel[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (holder.getPosition()){
case 0:
wechatSahre();
break;
case 1:
wechatMomentsSahre();
break;
case 2:
qqSahre();
break;
case 3:
qZoneSahre();
break;
case 4:
sinaWeiboSahre();
break;
case 5:
shortMessageSahre();
break;
case 6:
copyLink(shareUrl);
break;
case 7:
popupWindow.dismiss();
break;
}
}
});
}
@Override
public int getItemCount() {
return 8;
}
public class ViewHolder extends RecyclerView.ViewHolder{
LinearLayout linearLayout;
TextView shareLabel;
ImageView shareLogo;
public ViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView;
shareLogo = (ImageView) linearLayout.getChildAt(0);
shareLabel = (TextView) linearLayout.getChildAt(1);
}
}
}
//QQ分享
private void qqSahre(){
Utils.toast(context,"分享跳转中...");
Bundle params = new Bundle();
if (shareNewsTitle != null){
params.putString(QQShare.SHARE_TO_QQ_TITLE, shareNewsTitle);
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "来自光环助手(最强卡牌神器)");
}else {
params.putString(QQShare.SHARE_TO_QQ_TITLE, "向你推荐:");
if (isPlugin){
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareGameName + "(光环加速版)");
}else {
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareGameName);
}
}
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, shareIcon);
params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "光环助手");
mTencent.shareToQQ(
(Activity) context, params,QqShareListener);
popupWindow.dismiss();
}
//微信好友分享
private void wechatSahre(){
Utils.toast(context,"分享跳转中...");
WXWebpageObject webpage = new WXWebpageObject();
WXMediaMessage msg = new WXMediaMessage(webpage);
webpage.webpageUrl = shareUrl;
if (shareNewsTitle != null){
msg.title = shareNewsTitle;
msg.description = "来自光环助手(最强卡牌神器)";
}else {
if (isPlugin){
msg.title = "向你推荐";
msg.description = shareGameName + "(光环加速版)";
}else {
msg.title = "向你推荐";
msg.description = shareGameName;
}
}
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneSession;
loadBitMap(shareIcon, msg, req);
popupWindow.dismiss();
}
//QQ空间分享
private void qZoneSahre(){
Utils.toast(context,"分享跳转中...");
Bundle params = new Bundle();
if (shareNewsTitle != null){
params.putString(QzoneShare.SHARE_TO_QQ_TITLE, shareNewsTitle);
}else {
params.putString(QzoneShare.SHARE_TO_QQ_TITLE, "向你推荐:");
if (isPlugin){
params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareGameName + "(光环加速版)");
}else {
params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareGameName);
}
}
ArrayList<String> imageUrls = new ArrayList<String>();
imageUrls.add(shareIcon);
params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_NO_TYPE);
params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, "光环助手");
mTencent.shareToQzone(
(Activity) context, params,QqShareListener);
popupWindow.dismiss();
}
//微信朋友圈分享
private void wechatMomentsSahre(){
Utils.toast(context,"分享跳转中...");
WXWebpageObject webpage = new WXWebpageObject();
WXMediaMessage msg = new WXMediaMessage(webpage);
webpage.webpageUrl = shareUrl;
if (shareNewsTitle != null){
msg.title = shareNewsTitle;
}else {
if (isPlugin){
msg.title = "向你推荐:" + shareGameName + "(光环加速版)";
}else {
msg.title = "向你推荐:" + shareGameName;
}
}
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneTimeline;
loadBitMap(shareIcon, msg, req);
popupWindow.dismiss();
}
//新浪微博分享
private void sinaWeiboSahre(){
Intent intent = new Intent(context, WeiBoShareActivity.class);
Bundle bundle = new Bundle();
bundle.putString("shareNewsTitle", shareNewsTitle);
bundle.putString("shareIcon", shareIcon);
bundle.putString("shareGameName", shareGameName);
bundle.putString("shareUrl", shareUrl);
bundle.putBoolean("isPlugin",isPlugin);
intent.putExtras(bundle);
context.startActivity(intent);
popupWindow.dismiss();
}
//短信分享
private void shortMessageSahre(){
String smsBody;
if (shareNewsTitle != null){
smsBody = shareNewsTitle + shareUrl;
}else {
if (isPlugin){
smsBody = "向你推荐:" + shareGameName + "(光环加速版)" + shareUrl;
}else {
smsBody = "向你推荐:" + shareGameName + shareUrl;
}
}
Intent sendIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( "smsto:" ));
sendIntent.putExtra( "sms_body", smsBody);
sendIntent.setType( "vnd.android-dir/mms-sms" );
try {
context.startActivity(sendIntent);
} catch (Exception e) {
Utils.toast(context, "系统异常,分享失败");
e.printStackTrace();
}
popupWindow.dismiss();
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
//复制文字链接
private void copyLink(String copyContent) {
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setText(copyContent);
popupWindow.dismiss();
Utils.toast(context,"复制成功");
}
private void loadBitMap(final String iconUrl, final WXMediaMessage msg, final SendMessageToWX.Req req){
ImageUtils.getInstance().display(context, iconUrl, new BaseBitmapDataSubscriber() {
@Override
protected void onNewResultImpl(Bitmap bitmap) {
Bitmap compressBp = compressBitmap(bitmap);
Bitmap resultBp = addBackGround(compressBp);
msg.thumbData = Util.bmpToByteArray(resultBp, true);
api.sendReq(req);
}
@Override
protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
Utils.log("分享获取bitmap失败");
}
});
}
//添加背景防止图片格式为PNG的图片分享出现黑框问题
public Bitmap addBackGround(Bitmap result) {
Bitmap bgBitmap;
int[] colors = new int[result.getWidth()*result.getHeight()];
for (int i = 0; i < colors.length; i++) {
colors[i] = Color.WHITE;
}
bgBitmap = Bitmap.createBitmap(colors, result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);
Bitmap newmap = Bitmap
.createBitmap(result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newmap);
canvas.drawBitmap(bgBitmap, 0, 0, null);
canvas.drawBitmap(result, (result.getHeight() - result.getWidth()) / 2,
(result.getHeight() - result.getWidth()) / 2, null);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return newmap;
}
//压缩图片
private Bitmap compressBitmap(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);
float zoom = (float) Math.sqrt(10 * 1024 / (float) bos.toByteArray().length);
Matrix matrix = new Matrix();
matrix.setScale(zoom, zoom);
Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bos.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, bos);
while(bos.toByteArray().length > 10 * 1024){
System.out.println(bos.toByteArray().length);
matrix.setScale(0.9f, 0.9f);
result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
bos.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, bos);
}
return result;
}
//QQ或者QQ空间分享回调处理
public IUiListener QqShareListener = new IUiListener() {
@Override
public void onComplete(Object o) {
Utils.toast(context, "分享成功");
}
@Override
public void onError(UiError uiError) {
Utils.toast(context, "分享失败");
}
@Override
public void onCancel() {
Utils.toast(context, "分享已取消");
}
};
//检查是否安装手机QQ
public static boolean isQQClientAvailable(Context context){
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
if (pinfo != null) {
for (int i = 0; i < pinfo.size(); i++) {
String pn = pinfo.get(i).packageName; if (pn.equals("com.tencent.mobileqq")) {
return true;
}
}
}
return false;
}
}

View File

@ -5,7 +5,7 @@ public class SpeedUtils {
public static String getSpeed(long kSpeed) {
if (kSpeed >= 1000) {
float mSpeed = kSpeed / 1024f;
String str = mSpeed + "";
String str = String.valueOf(mSpeed);
if (str.length() > 4) {
str = str.substring(0, 4);
}
@ -14,10 +14,9 @@ public class SpeedUtils {
return kSpeed + "K/s";
}
public static String getRemainTime(long totalSize, long currentSize,
long speed) {
public static String getRemainTime(long totalSize, long currentSize, long speed) {
long remainSize = totalSize - currentSize;
long remainTime = 0;
long remainTime;
if (speed != 0) {
remainTime = remainSize / speed;
} else {
@ -35,4 +34,5 @@ public class SpeedUtils {
return second + "";
}
}
}

View File

@ -1,8 +1,10 @@
package com.gh.common.util;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import java.util.regex.Pattern;
@ -11,43 +13,113 @@ public class TimestampUtils {
// 基准时间
private static final long BASE = 1426608000000L;
private static ArrayMap<String, Integer> map;
private static ArrayMap<String, Integer> intervalMap; // 间隔
private static ArrayMap<String, Integer> cdMap; // cd
public static void initMap() {
initIntervalMap();
initCDMap();
}
private static void initIntervalMap() {
intervalMap = new ArrayMap<>();
intervalMap.put("^" + Config.HOST + "index/slides" + "$", 5);
intervalMap.put("^" + Config.HOST + "game/chajian" + "$", 10);
intervalMap.put("^" + Config.HOST + "game/tuijian" + "$", 15);
intervalMap.put("^" + Config.HOST + "game/.+/detail" + "$", 20);
intervalMap.put("^" + Config.HOST + "game/.+/digest" + "$", 25);
intervalMap.put("^" + Config.HOST + "game/remenkapai" + "$", 30);
intervalMap.put("^" + Config.HOST + "game/.+/news_digest" + "$", 35);
intervalMap.put("^" + Config.HOST + "game/column/.+\\?page=.+" + "$", 40);
intervalMap.put("^" + Config.HOST + "support/package/.+/game/digest" + "$", 45);
intervalMap.put("^" + Config.HOST + "game/danjiyouxi\\?limit=20\\&offset=.+" + "$", 50);
intervalMap.put("^" + Config.HOST + "news/.+/digest" + "$", 55);
intervalMap.put("^" + Config.HOST + "news/.+/detail" + "$", 60);
intervalMap.put("^" + Config.HOST + "news/.+/suggestion" + "$", 65);
intervalMap.put("^" + Config.HOST + "game/.+/news\\?limit=3" + "$", 70);
intervalMap.put("^" + Config.HOST + "zixun/zixun\\?limit=20\\&offset=.+" + "$", 75);
intervalMap.put("^" + Config.HOST + "game/.+/news\\?limit=20\\&offset=.+" + "$", 80);
intervalMap.put("^" + Config.HOST + "zixun/yuanchuang\\?limit=20\\&offset=.+" + "$", 85);
intervalMap.put("^" + Config.HOST + "news\\?type_group=.+\\&offset=.+\\&limit=20" + "$", 90);
intervalMap.put("^" + Config.HOST + "zixun/guanzhu\\?key=.+\\&limit=20\\&offset=.+" + "$", 95);
intervalMap.put("^" + Config.HOST + "game/.+/news\\?limit=20\\&offset=.+\\&type=.+" + "$", 100);
intervalMap.put("^" + Config.HOST + "zixun/guanzhu\\?game_id=.+\\&limit=20\\&offset=.+" + "$", 105);
intervalMap.put("^" + Config.HOST + "search/news\\?game_id=.+\\&keyword=.+\\&page=.+\\&limit=20" + "$", 110);
intervalMap.put("^" + Config.HOST + "search/game\\?keyword=.+" + "$", 115);
intervalMap.put("^" + Config.HOST + "support/setting/platform" + "$", 120);
intervalMap.put("^" + Config.HOST + "update/package/.+" + "$", 125);
intervalMap.put("^" + Config.HOST + "update/game/.+/package/.+" + "$", 130);
intervalMap.put("^" + Config.COMMENT_HOST + "article/.+/comment\\?limit=10\\&offset=.+" + "$", 135);
intervalMap.put("^" + Config.COMMENT_HOST + "article/.+/comment\\?order=hot\\&limit=10\\&offset=.+" + "$", 140);
}
private static void initCDMap() {
cdMap = new ArrayMap<>();
cdMap.put("^" + Config.HOST + "index/slides" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/chajian" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/tuijian" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/.+/detail" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/.+/digest" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/remenkapai" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/.+/news_digest" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/column/.+\\?page=.+" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "support/package/.+/game/digest" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/danjiyouxi\\?limit=20\\&offset=.+" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "news/.+/digest" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "news/.+/detail" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "news/.+/suggestion" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "game/.+/news\\?limit=3" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "zixun/zixun\\?limit=20\\&offset=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "game/.+/news\\?limit=20\\&offset=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "zixun/yuanchuang\\?limit=10\\&offset=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "news\\?type_group=.+\\&offset=.+\\&limit=20" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "zixun/guanzhu\\?key=.+\\&limit=20\\&offset=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "game/.+/news\\?limit=20\\&offset=.+\\&type=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "zixun/guanzhu\\?game_id=.+\\&limit=20\\&offset=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "search/news\\?game_id=.+\\&keyword=.+\\&page=.+\\&limit=20" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "search/game\\?keyword=.+" + "$", Constants.SEARCH_CD);
cdMap.put("^" + Config.HOST + "support/setting/platform" + "$", Constants.PLATFORM_CD);
cdMap.put("^" + Config.HOST + "update/package/.+" + "$", Constants.UPDATE_CD);
cdMap.put("^" + Config.HOST + "update/game/.+/package/.+" + "$", Constants.UPDATE_CD);
cdMap.put("^" + Config.COMMENT_HOST + "article/.+/comment\\?limit=10\\&offset=.+" + "$", Constants.COMMENT_CD);
cdMap.put("^" + Config.COMMENT_HOST + "article/.+/comment\\?order=hot\\&limit=10\\&offset=.+" + "$", Constants.COMMENT_CD);
cdMap.put("^" + Config.HOST + "device/.+/concern" + "$", 0);
cdMap.put("^" + Config.HOST + "device/.+/concern/.+" + "$", 0);
cdMap.put("^" + Config.HOST + "stat/download" + "$", 0);
cdMap.put("^" + Config.HOST + "disclaimer" + "$", 0);
cdMap.put("^" + Config.HOST + "search/game/default" + "$", 0);
cdMap.put("^" + Config.HOST + "support/upgrade\\?version=.+\\&channel=.+" + "$", 0);
cdMap.put("^" + Config.HOST + "support/time/current" + "$", 0);
cdMap.put("^" + Config.HOST + "support/setting/ui" + "$", 0);
cdMap.put("^" + Config.HOST + "support/download_status\\?version=.+\\&channel=.+" + "$", 0);
cdMap.put("^" + Config.HOST + "support/suggestion" + "$", 0);
cdMap.put("^" + Config.HOST + "game/.+/serverInfo" + "$", 0);
cdMap.put("^" + Config.HOST + "support/package/unused\\?skip=.+" + "$", 0);
}
private static ArrayMap<String, Integer> getIntervalMap() {
if (intervalMap == null) {
intervalMap = new ArrayMap<>();
}
return intervalMap;
}
private static ArrayMap<String, Integer> getCdMap() {
if (cdMap == null) {
cdMap = new ArrayMap<>();
}
return cdMap;
}
/*
* 根据CD获取时间戳
*/
public static long getTimestamp(String url, int cd) {
if (map == null){
map = new ArrayMap<String, Integer>();
map.put("^" + Config.HOST + "v1d45/index/kapaitoutiao" + "$", 5);
map.put("^" + Config.HOST + "v1d45/index/remenkapai" + "$", 10);
map.put("^" + Config.HOST + "v1d45/index/xincekapai" + "$", 15);
map.put("^" + Config.HOST + "v1d45/index/yuedujingxuan" + "$", 20);
map.put("^" + Config.HOST + "v1d45/index/zuixinchajian" + "$", 25);
map.put("^" + Config.HOST + "v1d45/search/game\\?keyword=.+" + "$", 30);
map.put("^" + Config.HOST + "v1d45/plugin/slide" + "$", 40);
map.put("^" + Config.HOST + "v1d45/plugin/jingpin\\?limit=20\\&offset=.+" + "$", 35);
map.put("^" + Config.HOST + "v1d45/plugin/zuixin\\?limit=20\\&offset=.+" + "$", 45);
map.put("^" + Config.HOST + "v1d45/plugin/danji\\?limit=20\\&offset=.+" + "$", 50);
map.put("^" + Config.HOST + "v1d45/game/remenkapai" + "$", 60);
map.put("^" + Config.HOST + "v1d45/game/youxituijian" + "$", 85);
map.put("^" + Config.HOST + "v1d45/game/xincekapai\\?limit=10\\&offset=.+" + "$", 90);
map.put("^" + Config.HOST + "v1d45/game/.+/digest" + "$", 55);
map.put("^" + Config.HOST + "v1d45/game/.+/digest" + "$", 65);
map.put("^" + Config.HOST + "v1d45/game/.+/news_digest" + "$", 70);
map.put("^" + Config.HOST + "v1d45/game/.+/news\\?limit=3\\&offset=0\\&type_group=.+" + "$", 75);
map.put("^" + Config.HOST + "v1d45/game/.+/news\\?limit=5\\&offset=0\\&type_group=.+" + "$", 80);
map.put("^" + Config.HOST + "v1d45/news/.+/suggestion" + "$", 95);
map.put("^" + Config.HOST + "v1d45/news\\?type_group=.+\\&offset=.+\\&limit=20" + "$", 100);
map.put("^" + Config.HOST + "v1d45/support/setting/platform" + "$", 105);
map.put("^" + Config.HOST + "v1d45/support/package/.+/game/digest" + "$", 110);
map.put("^" + Config.HOST + "v1d45/support/package/update\\?package=.+" + "$", 115);
}
long base = BASE;
for (String key : map.keySet()){
for (String key : getIntervalMap().keySet()){
if (Pattern.matches(key, url)) {
Utils.log("url add base = " + url);
base += map.get(key);
base += getIntervalMap().get(key);
break;
}
}
@ -59,7 +131,20 @@ public class TimestampUtils {
/*
* 为url添加timestamp
*/
public static String addTimestamp(String url, int cd) {
public static String addTimestamp(String url) {
if (TextUtils.isEmpty(url)) {
return url;
}
int cd = 0;
for (String key : getCdMap().keySet()){
if (Pattern.matches(key, url)) {
cd = getCdMap().get(key);
break;
}
}
if (cd == 0) {
return url;
}
if (url.contains("?")) {
String u = url + "&timestamp=" + getTimestamp(url, cd);
Utils.log("url = " + u);
@ -70,7 +155,7 @@ public class TimestampUtils {
return u;
}
}
/*
* 去除url中的timestamp
*/

View File

@ -3,13 +3,27 @@ package com.gh.common.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.Response;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.gamecenter.volley.extended.StringExtendedRequest;
import com.tencent.stat.StatConfig;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
@ -20,57 +34,112 @@ import java.util.Map;
public class TokenUtils {
// 获取用户token
public static synchronized String getToken(Context context) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE,
Context.MODE_PRIVATE);
String token = sp.getString("token", null);
if (token != null) {
long expire = sp.getLong("token_expire", 0) * 1000 - 10 * 1000;
long time = System.currentTimeMillis();
// 判断token是否过期
if (time < expire) {
return token;
}
// 注册设备
public static synchronized String register(final Context context) {
HashMap<String, String> params = new HashMap<>();
String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
if (!TextUtils.isEmpty(android_id)) {
params.put("ANDROID_ID", android_id);
}
// Map<String, String> params = DeviceUtils.getDeviceParams(context);
Map<String, String> params = new HashMap<String, String>();
String url = Config.HOST + "v1d45/token/visit";
//判断是否已登录
if (sp.getBoolean("isLogin", false)) {
// 已登录,获取用户名和密码自动登录
String username = sp.getString("username", null);
String password = sp.getString("password", null);
if (username == null || password == null) {
url = Config.HOST + "v2/token/user?time=" + System.currentTimeMillis();
params.put("username", username);
try {
String s = RSEUtils.encryptByPublic(password + username + System.currentTimeMillis() / 1000);
Utils.log("加密 = " + s);
params.put("password", s);
} catch (Exception e) {
e.printStackTrace();
}
} else {
url = Config.HOST + "v2/token/mobile?time=" + System.currentTimeMillis();
String mobile = sp.getString("mobile", null);
params.put("mobile_number", mobile);
}
String imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
if (!TextUtils.isEmpty(imei)) {
params.put("IMEI", imei);
}
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String mac = wm.getConnectionInfo().getMacAddress();
if (!TextUtils.isEmpty(mac) || !":::::".equals(mac)) {
params.put("MAC", mac);
} else {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
sp.edit().putBoolean("isUploadMac", false).apply();
}
String mid = StatConfig.getMid(context);
if (!TextUtils.isEmpty(mid) || !"0".equals(mid)) {
params.put("MTA_ID", mid);
} else {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
sp.edit().putBoolean("isUploadMid", false).apply();
}
String url = Config.USER_HOST + "device/register";
try {
JSONObject body = new JSONObject(params);
HttpURLConnection connection = (HttpURLConnection) new URL(url)
.openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.connect();
OutputStreamWriter outputStream = new OutputStreamWriter(
connection.getOutputStream(), "utf-8");
outputStream.write(body.toString());
outputStream.flush();
outputStream.close();
if (connection.getResponseCode() == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
try {
JSONObject response = new JSONObject(builder.toString());
String device_id = response.getString("device_id");
// 保存device_id
saveDeviceId(context, device_id);
Utils.log("device_id = " + device_id);
return device_id;
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static synchronized String getToken(Context context) {
return getToken(context, true);
}
// 获取用户token
public static synchronized String getToken(Context context, boolean isCheck) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
String token = sp.getString("token", null);
if (isCheck) {
if (token != null) {
long expire = sp.getLong("token_expire", 0) * 1000 - 10 * 1000;
long time = Utils.getTime(context);
// 判断token是否过期
if (time < expire) {
// token未过期
return token;
}
}
}
// 重新获取token
String url = Config.USER_HOST + "login";
Map<String, String> params = new HashMap<>();
params.put("device_id", getDeviceId(context));
try {
JSONObject body = new JSONObject(params);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.addRequestProperty("Device", DeviceUtils.getDeviceHeader(context));
connection.connect();
@ -90,12 +159,19 @@ public class TokenUtils {
}
reader.close();
try {
JSONObject jsonObject = new JSONObject(builder.toString());
Editor editor = sp.edit();
editor.putString("token", jsonObject.getString("token"));
JSONObject jsonObject = new JSONObject(builder.toString());
editor.putString("user_name", jsonObject.getString("name"));
editor.putString("user_icon", jsonObject.getString("icon"));
jsonObject = jsonObject.getJSONObject("token");
editor.putString("token", jsonObject.getString("value"));
editor.putLong("token_expire", jsonObject.getLong("expire"));
editor.apply();
return jsonObject.getString("token");
if (token != null && token.equals(jsonObject.getString("value"))) {
// 服务器返回的token和本地已存的token相同更新本地时间
getTime(context);
}
return jsonObject.getString("value");
} catch (JSONException e) {
e.printStackTrace();
}
@ -103,7 +179,189 @@ public class TokenUtils {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 获取服务器时间
public static synchronized void getTime(Context context) {
final SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.GET, Config.HOST + "support/time/current",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.matches("^[0-9]{10}$")) {
try {
Editor editor = sp.edit();
editor.putLong("server_time", Long.parseLong(response));
editor.putLong("client_time", System.currentTimeMillis() / 1000);
editor.apply();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
}, null);
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
public static synchronized void saveDeviceId(Context context, String device_id){
saveSharedPreferences(context, device_id);
saveDataFile(context, device_id);
svaeSDCard(device_id, "/gh-uuid");// SDCard根目录
svaeSDCard(device_id, "/system"); // SDCard system目录
svaeSDCard(device_id, "/data"); // SDCard data目录
}
//将uuid存到sp
private static void saveSharedPreferences(Context context, String device_id) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("uuid", device_id);
edit.apply();
Utils.log("saveDeviceId", "保存成功SP");
}
//将uuid存到data/data/PackageName/files文件夹下
private static void saveDataFile(Context context, String device_id) {
FileOutputStream fops;
try {
fops = context.openFileOutput("uuid", Context.MODE_PRIVATE);
fops.write(device_id.getBytes());
fops.close();
Utils.log("saveDeviceId", "保存成功DataFile");
} catch (Exception e) {
Utils.log("保存uuid到data/data/PackageName/files文件异常" + e.toString());
e.printStackTrace();
}
}
//将uuid存到SD卡
private static void svaeSDCard(String device_id, String saveDir) {
File sdCardDir = Environment.getExternalStorageDirectory();
String path = sdCardDir.getPath() + saveDir;
File file = new File(path);
if (!file.exists()){
file.mkdirs();
}
// 判断文件是否存在,存在则删除
File uuidFile = new File(path +"/uuid");
if (uuidFile.isFile() && uuidFile.exists()){
Utils.log(saveDir + "文件夹里的文件存在,执行删除操作");
uuidFile.delete();
}
File writeFile = new File(file, "uuid");
FileOutputStream fos;
try {
fos = new FileOutputStream(writeFile);
fos.write(device_id.getBytes());
fos.close();
Utils.log("saveDeviceId", "保存成功SDCard"+"目录为:"+saveDir);
} catch (Exception e) {
Utils.log("保存uuid到SDCard异常" + saveDir + e.toString());
e.printStackTrace();
}
}
// 启动助手时检查uuid
public static void checkDeviceID(Context context) {
String uuid = loadSharedPreferences(context, false);
if (uuid == null) {
// 重新获取uuid保存
return;
}
// 检查
if (loadSharedPreferences(context, true) == null){
saveSharedPreferences(context, uuid);
}
if (loadDataFile(context ,true) == null){
saveDataFile(context, uuid);
}
String[] dirName = {"/gh-uuid", "/system", "/data"};
for (int i = 0; i< 3; i++) {
String s = loadSDCard(dirName[i]);
if (s == null) {
svaeSDCard(uuid, dirName[i]);
}
}
}
public static synchronized String getDeviceId(Context context) {
return loadSharedPreferences(context, false);
}
//读取SharedPreferences的uuid
private static String loadSharedPreferences(Context context, boolean isCheck) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
String uuid = sp.getString("uuid", null);
if (isCheck){
return uuid;
}
if (uuid == null){
return loadDataFile(context, false);
}
Utils.log("getDeviceId", "获取成功SP" + uuid);
return uuid;
}
//读取data/data/PackageName/files的uuid
private static String loadDataFile(Context context, boolean isCheck) {
File file = new File(context.getFilesDir(), "uuid");
if (file.exists()){
try {
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int count = -1;
String uuid = null;
while ((count = fis.read(b)) != -1) {
uuid = new String(b, 0, count, "UTF-8");
}
Utils.log("getDeviceId", "获取成功DataFile"+ uuid);
return uuid;
} catch (Exception e) {
e.printStackTrace();
}
}else if (!isCheck){
String[] dirName = {"/gh-uuid", "/system", "/data"};
for (int i = 0; i< 3; i++) {
String s = loadSDCard(dirName[i]);
if (s != null) {
return s;
}
}
}
return null;
}
//读取SD卡的uuid
private static String loadSDCard(String saveDir){
File sdCardDir = Environment.getExternalStorageDirectory();
String path = sdCardDir.getPath() + saveDir;
File file = new File(path, "uuid");
if (file.exists()){
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] array = new byte[1024];
int len = -1;
while( (len = fis.read(array)) != -1){
bos.write(array,0,len);
}
bos.close();
fis.close();
Utils.log("getDeviceId", "获取成功SDCard"+"目录为:"+saveDir+"::"+bos.toString());
return bos.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

View File

@ -1,64 +0,0 @@
package com.gh.common.util;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author 温冠超
* @email 294299195@qq.com
* @date 2015-8-19
* @update 2015-8-19
* @des 控制debug调试信息
*/
public class Trace {
private final String TAG = "gh_debug";
private Map<String, Boolean> maps;//(tag, boolean), boolean = true,表示debug信息可以显示,否则不能显示
private static Trace mInstance;
private Trace(){
maps = new HashMap<String ,Boolean>();
}
public static Trace getInstance(){
synchronized (Trace.class) {
if(mInstance == null)
mInstance = new Trace();
return mInstance;
}
}
public void debug(String tag, String msg){
if(maps.get(tag) == null){
maps.put(tag, false);
}
if(maps.get(tag) == true){
Log.d(TAG, tag + "==>" + msg);
}
}
/**
*
* @param tag debug的tag
* @param flag true则输出该tag的debug信息否则不输出该tag的debug信息
*/
public void setClassDebug(String tag, boolean flag){
maps.put(tag, flag);
}
/**
*
* @param flag true--所有tag的debug消息都可以输出否则全部都不输出
*/
public void setDebug(boolean flag){
for ( String tag : maps.keySet()) {
maps.put(tag, flag);
}
}
}

View File

@ -26,14 +26,12 @@ public class TrafficUtils {
synchronized (TrafficUtils.class) {
if (instance == null) {
instance = new TrafficUtils(context);
if (update)
instance.update();
return instance;
}
}
}
if (update)
if (update) {
instance.update();
}
return instance;
}
@ -47,9 +45,7 @@ public class TrafficUtils {
// 获取所有的安装在手机上的应用软件的信息,并且获取这些软件里面的权限信息
PackageManager pm = context.getPackageManager();// 获取系统应用包管理
// 获取每个包内的androidmanifest.xml信息它的权限等等
List<PackageInfo> pinfos = pm
.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES
| PackageManager.GET_PERMISSIONS);
List<PackageInfo> pinfos = pm.getInstalledPackages(PackageManager.GET_PERMISSIONS);
// 遍历每个应用包信息
for (PackageInfo info : pinfos) {
// 请求每个程序包对应的androidManifest.xml里面的权限
@ -64,9 +60,7 @@ public class TrafficUtils {
long rx = TrafficStats.getUidRxBytes(uId);
// 如果返回-1代表不支持使用该方法注意必须是2.2以上的
long tx = TrafficStats.getUidTxBytes(uId);
if (rx < 0 || tx < 0) {
continue;
} else {
if (rx >= 0 && tx >= 0) {
db.update(info.packageName, rx + tx);
}
}

View File

@ -1,29 +1,48 @@
package com.gh.common.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.gh.common.constant.Config;
import com.gh.gamecenter.R;
import java.lang.reflect.Field;
public class Utils {
private static final boolean DEBUG = false;
private static final boolean DEBUG = true;
private final static String TAG = "result";
public static void log(String msg) {
log(TAG, msg);
}
public static void log(Object obj) {
log(TAG, obj.getClass().getSimpleName() + ":" + obj.toString());
}
public static void log(String tag, String msg) {
log(Log.ERROR, tag, msg);
}
public static void log(String tag, Object obj) {
log(Log.ERROR, tag, obj.getClass().getSimpleName() + ":" + obj.toString());
}
private static void log(int priority, String tag, String msg) {
if (DEBUG) {
Log.e("result", msg);
Log.println(priority, tag, msg);
}
}
public static void log(Object obj) {
private static void log(int priority, String tag, Object obj) {
if (DEBUG) {
Log.e("result", obj.getClass().getSimpleName() + " = " + obj.toString());
Log.println(priority, tag, obj.getClass().getSimpleName() + ":" + obj.toString());
}
}
@ -31,6 +50,20 @@ public class Utils {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
/*
* 获取服务器时间
*/
public static long getTime(Context context) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
long serverTime = sp.getLong("server_time", 0);
long clientTime = sp.getLong("client_time", 0);
if (serverTime == 0 || clientTime == 0) {
return System.currentTimeMillis() / 1000;
} else {
return serverTime + (System.currentTimeMillis() / 1000 - clientTime);
}
}
public static void hideSoftInput(Context context, EditText editText) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);

View File

@ -0,0 +1,249 @@
package com.gh.common.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import com.gh.gamecenter.R;
/**
* Created by LGT on 2016/8/31.
*/
public class CardLinearLayout extends LinearLayout {
private Drawable mLeftDrawable, mTopDrawable, mRightDrawable, mBottomDrawable, mCenterDrawable;
private Drawable mLeftTopDrawable, mRightTopDrawable, mLeftBottomDrawable, mRightBottomDrawable;
private int mLeft, mTop, mRight, mBottom;
private boolean isBottom;
public CardLinearLayout(Context context) {
this(context, null);
}
public CardLinearLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CardLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
setWillNotDraw(false);
isBottom = true;
mLeftDrawable = getContext().getResources().getDrawable(R.drawable.frame_left);
mTopDrawable = getContext().getResources().getDrawable(R.drawable.frame_top);
mRightDrawable = getContext().getResources().getDrawable(R.drawable.frame_right);
mBottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_bottom);
mCenterDrawable = getContext().getResources().getDrawable(R.drawable.frame_center);
mLeftTopDrawable = getContext().getResources().getDrawable(R.drawable.frame_left_top_square);
mRightTopDrawable = getContext().getResources().getDrawable(R.drawable.frame_right_top_square);
mLeftBottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_left_bottom_square);
mRightBottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_right_bottom_square);
if (attrs != null) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CardLayout);
mLeft = ta.getDimensionPixelSize(R.styleable.CardLayout_left, 0);
mTop = ta.getDimensionPixelSize(R.styleable.CardLayout_top, 0);
mRight = ta.getDimensionPixelSize(R.styleable.CardLayout_right, 0);
mBottom = ta.getDimensionPixelSize(R.styleable.CardLayout_bottom, 0);
ta.recycle();
}
setPadding(getPaddingLeft() + mLeft, getPaddingTop() + mTop, getPaddingRight() + mRight, getPaddingBottom() + mBottom);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mLeft != 0 && mTop != 0 && mRight != 0 && mBottom != 0) {
// 左、上、右、下
if (mLeftTopDrawable != null) {
mLeftTopDrawable.setBounds(0, 0, mLeft, mTop);
mLeftTopDrawable.draw(canvas);
}
if (mTopDrawable != null) {
mTopDrawable.setBounds(mLeft, 0, getWidth() - mRight, mTop);
mTopDrawable.draw(canvas);
}
if (mRightTopDrawable != null) {
mRightTopDrawable.setBounds(getWidth() - mRight, 0, getWidth(), mTop);
mRightTopDrawable.draw(canvas);
}
if (mLeftDrawable != null) {
mLeftDrawable.setBounds(0, mTop, mLeft, getHeight() - mBottom);
mLeftDrawable.draw(canvas);
}
if (mRightDrawable != null) {
mRightDrawable.setBounds(getWidth() - mRight, mTop, getWidth(), getHeight() - mBottom);
mRightDrawable.draw(canvas);
}
if (mLeftBottomDrawable != null) {
mLeftBottomDrawable.setBounds(0, getHeight() - mBottom, mLeft, getHeight());
mLeftBottomDrawable.draw(canvas);
}
if (isBottom) {
if (mBottomDrawable != null) {
mBottomDrawable.setBounds(mLeft, getHeight() - mBottom, getWidth() - mRight, getHeight());
mBottomDrawable.draw(canvas);
}
} else {
if (mCenterDrawable != null) {
mCenterDrawable.setBounds(mLeft, getHeight() - mBottom, getWidth() - mRight, getHeight());
mCenterDrawable.draw(canvas);
}
}
if (mRightBottomDrawable != null) {
mRightBottomDrawable.setBounds(getWidth() - mRight, getHeight() - mBottom, getWidth(), getHeight());
mRightBottomDrawable.draw(canvas);
}
} else if (mLeft != 0 && mTop != 0 && mRight != 0) {
// 左、上、右
if (mLeftTopDrawable != null) {
mLeftTopDrawable.setBounds(0, 0, mLeft, mTop);
mLeftTopDrawable.draw(canvas);
}
if (mTopDrawable != null) {
mTopDrawable.setBounds(mLeft, 0, getWidth() - mRight, mTop);
mTopDrawable.draw(canvas);
}
if (mRightTopDrawable != null) {
mRightTopDrawable.setBounds(getWidth() - mRight, 0, getWidth(), mTop);
mRightTopDrawable.draw(canvas);
}
if (mLeftDrawable != null) {
mLeftDrawable.setBounds(0, mTop, mLeft, getHeight());
mLeftDrawable.draw(canvas);
}
if (mRightDrawable != null) {
mRightDrawable.setBounds(getWidth() - mRight, mTop, getWidth(), getHeight());
mRightDrawable.draw(canvas);
}
} else if (mLeft != 0 && mBottom != 0 && mRight != 0) {
// 左、下、右
if (mLeftDrawable != null) {
mLeftDrawable.setBounds(0, 0, mLeft, getHeight() - mBottom);
mLeftDrawable.draw(canvas);
}
if (mRightDrawable != null) {
mRightDrawable.setBounds(getWidth() - mRight, 0, getWidth(), getHeight() - mBottom);
mRightDrawable.draw(canvas);
}
if (mLeftBottomDrawable != null) {
mLeftBottomDrawable.setBounds(0, getHeight() - mBottom, mLeft, getHeight());
mLeftBottomDrawable.draw(canvas);
}
if (isBottom) {
if (mBottomDrawable != null) {
mBottomDrawable.setBounds(mLeft, getHeight() - mBottom, getWidth() - mRight, getHeight());
mBottomDrawable.draw(canvas);
}
} else {
if (mCenterDrawable != null) {
mCenterDrawable.setBounds(mLeft, getHeight() - mBottom, getWidth() - mRight, getHeight());
mCenterDrawable.draw(canvas);
}
}
if (mRightBottomDrawable != null) {
mRightBottomDrawable.setBounds(getWidth() - mRight, getHeight() - mBottom, getWidth(), getHeight());
mRightBottomDrawable.draw(canvas);
}
} else if (mLeft != 0 && mRight != 0) {
// 左、右
if (mLeftDrawable != null) {
mLeftDrawable.setBounds(0, 0, mLeft, getHeight());
mLeftDrawable.draw(canvas);
}
if (mRightDrawable != null) {
mRightDrawable.setBounds(getWidth() - mRight, 0, getWidth(), getHeight());
mRightDrawable.draw(canvas);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int newHeight = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) + mTop + mBottom,
MeasureSpec.getMode(heightMeasureSpec));
super.onMeasure(widthMeasureSpec, newHeight);
}
public void setBottom(boolean bottom) {
isBottom = bottom;
}
public void setShadow(int left, int top, int right, int bottom) {
setPadding(getPaddingLeft() - mLeft + left,
getPaddingTop() - mTop + top,
getPaddingRight() - mRight + right,
getPaddingBottom() - mBottom + bottom);
this.mLeft = left;
this.mTop = top;
this.mRight = right;
this.mBottom = bottom;
}
public void setmLeft(int left) {
setPadding(getPaddingLeft() - mLeft + left, getPaddingTop(), getPaddingRight(), getPaddingBottom());
this.mLeft = left;
}
public void setmTop(int top) {
setPadding(getPaddingLeft(), getPaddingTop() - mTop + top, getPaddingRight(), getPaddingBottom());
this.mTop = top;
}
public void setmRight(int right) {
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight() - mRight + right, getPaddingBottom());
this.mRight = right;
}
public void setmBottom(int bottom) {
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), getPaddingBottom() - mBottom + bottom);
this.mBottom = bottom;
}
public int getmLeft() {
return mLeft;
}
public int getmTop() {
return mTop;
}
public int getmRight() {
return mRight;
}
public int getmBottom() {
return mBottom;
}
}

View File

@ -0,0 +1,99 @@
package com.gh.common.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import com.gh.gamecenter.R;
/**
* Created by LGT on 2016/9/9.
*/
public class CardRelativeLayout extends RelativeLayout {
private Drawable topDrawable, bottomDrawable;
private Drawable leftTopDrawable, rightTopDrawable, leftBottomDrawable, rightBottomDrawable;
private int mLeft, mTop, mRight, mBottom;
public CardRelativeLayout(Context context) {
this(context, null);
}
public CardRelativeLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CardRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
setWillNotDraw(false);
topDrawable = getContext().getResources().getDrawable(R.drawable.frame_top);
bottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_bottom);
leftTopDrawable = getContext().getResources().getDrawable(R.drawable.frame_left_top_square);
rightTopDrawable = getContext().getResources().getDrawable(R.drawable.frame_right_top_square);
leftBottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_left_bottom_square);
rightBottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_right_bottom_square);
if (attrs != null) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CardLayout);
mLeft = ta.getDimensionPixelSize(R.styleable.CardLayout_left, 0);
mTop = ta.getDimensionPixelSize(R.styleable.CardLayout_top, 0);
mRight = ta.getDimensionPixelSize(R.styleable.CardLayout_right, 0);
mBottom = ta.getDimensionPixelSize(R.styleable.CardLayout_bottom, 0);
ta.recycle();
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mTop != 0) {
if (leftBottomDrawable != null) {
leftBottomDrawable.setBounds(0, 0, mLeft, mTop);
leftBottomDrawable.draw(canvas);
}
if (bottomDrawable != null) {
bottomDrawable.setBounds(mLeft, 0, getWidth() - mRight, mTop);
bottomDrawable.draw(canvas);
}
if (rightBottomDrawable != null) {
rightBottomDrawable.setBounds(getWidth() - mRight, 0, getWidth(), mTop);
rightBottomDrawable.draw(canvas);
}
}
if (mBottom != 0) {
if (leftTopDrawable != null) {
leftTopDrawable.setBounds(0, getHeight() - mBottom, mLeft, getHeight());
leftTopDrawable.draw(canvas);
}
if (topDrawable != null) {
topDrawable.setBounds(mLeft, getHeight() - mBottom, getWidth() - mRight, getHeight());
topDrawable.draw(canvas);
}
if (rightTopDrawable != null) {
rightTopDrawable.setBounds(getWidth() - mRight, getHeight() - mBottom, getWidth(), getHeight());
rightTopDrawable.draw(canvas);
}
}
}
public void setmBottom(int mBottom) {
this.mBottom = mBottom;
}
public void setmTop(int mTop) {
this.mTop = mTop;
}
}

View File

@ -32,7 +32,7 @@ public class Concern_LinearLayout extends LinearLayout {
if (concern_rv_recommend.getHeight() < height) {
postDelayed(show, 10);
} else {
concern_iv_delete.setImageResource(R.drawable.concern_delete);
concern_iv_delete.setImageResource(R.drawable.concern_down);
}
}
};
@ -52,7 +52,7 @@ public class Concern_LinearLayout extends LinearLayout {
postDelayed(hide, 10);
} else {
concern_rv_recommend.setVisibility(View.GONE);
concern_iv_delete.setImageResource(R.drawable.concern_arrow);
concern_iv_delete.setImageResource(R.drawable.concern_up);
}
}
};

View File

@ -58,19 +58,25 @@ public class CropImageCustom extends RelativeLayout {
return mZoomImageView.clip();
}
public void savePicture(String path) {
public boolean savePicture(String path) {
Bitmap bitmap = mZoomImageView.clip();
File file = new File(path);
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
} catch (IOException e) {
file.delete();
e.printStackTrace();
}
int quality = 80;
do {
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
bos.flush();
bos.close();
} catch (IOException e) {
file.delete();
e.printStackTrace();
return false;
}
quality -= 10;
} while (file.length() > 81920);
return true;
}
public ImageView getCropImageZoomView() {

File diff suppressed because it is too large Load Diff

View File

@ -1,105 +0,0 @@
package com.gh.common.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import com.gh.common.util.DisplayUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBShowDone;
import de.greenrobot.event.EventBus;
public class Gh_LinearLayout extends LinearLayout {
private LinearLayout dm_item, dm_item_ll_delete;
private int height;
private int total;
private int distance;
private boolean isSliding;
public boolean isSliding() {
return isSliding;
}
private int position;
Runnable show = new Runnable() {
@Override
public void run() {
LayoutParams lparams = new LayoutParams(
LayoutParams.MATCH_PARENT, height);
lparams.height = dm_item.getHeight() + distance;
if (lparams.height > total) {
lparams.height = total;
}
dm_item.setLayoutParams(lparams);
invalidate();
if (dm_item.getHeight() < total) {
postDelayed(show, 10);
} else {
isSliding = false;
EventBus.getDefault().post(new EBShowDone("下载管理", position));
}
}
};
Runnable hide = new Runnable() {
@Override
public void run() {
LayoutParams lparams = new LayoutParams(
LayoutParams.MATCH_PARENT, height);
lparams.height = dm_item.getHeight() - distance;
if (lparams.height < height) {
lparams.height = height;
}
dm_item.setLayoutParams(lparams);
invalidate();
if (dm_item.getHeight() > height) {
postDelayed(hide, 10);
} else {
dm_item_ll_delete.setVisibility(View.GONE);
isSliding = false;
}
}
};
public Gh_LinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
height = DisplayUtils.dip2px(getContext(), 66);
total = DisplayUtils.dip2px(getContext(), 96);
distance = DisplayUtils.dip2px(getContext(), 3);
isSliding = false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
dm_item = (LinearLayout) findViewById(R.id.dm_item);
dm_item_ll_delete = (LinearLayout) findViewById(R.id.dm_item_ll_delete);
}
public void showDeleteView(int position) {
this.position = position;
isSliding = true;
dm_item_ll_delete.setVisibility(View.VISIBLE);
removeCallbacks(hide);
post(show);
getHandler();
}
public void hideDeleteView() {
isSliding = true;
removeCallbacks(show);
post(hide);
}
}

View File

@ -6,32 +6,31 @@ import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.RelativeLayout;
public class Gh_ImageLayout extends RelativeLayout {
public class Gh_RelativeLayout extends RelativeLayout {
private GestureDetector mGestureDetector;
private OnSingleTapListener listener;
public Gh_ImageLayout(Context context) {
public Gh_RelativeLayout(Context context) {
this(context, null);
}
public Gh_ImageLayout(Context context, AttributeSet attrs) {
public Gh_RelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (listener != null) {
listener.onSingleTap();
}
return super.onSingleTapUp(e);
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (listener != null) {
listener.onSingleTap();
}
return super.onSingleTapUp(e);
}
});
});
}
public void setOnSingleTapListener(OnSingleTapListener listener) {

View File

@ -5,25 +5,56 @@ import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.gh.gamecenter.eventbus.EBReuse;
import de.greenrobot.event.EventBus;
public class Gh_ViewPager extends ViewPager {
private boolean mChildIsBeingDragged=false;//当前子控件是否处理拖动状态
public Gh_ViewPager(Context context) {
this(context, null);
}
public Gh_ViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
EventBus.getDefault().register(this);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
for (int i = 0; i < getChildCount(); i++) {
getChildAt(i).dispatchTouchEvent(event);
}
// for (int i = 0; i < getChildCount(); i++) {
// getChildAt(i).dispatchTouchEvent(event);
// }
return super.dispatchTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if(mChildIsBeingDragged){
return false;
}
//指针索引超出范围异常
try {
return super.onInterceptTouchEvent(ev);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
}
}
public void onEvent(EBReuse reuse) {
if ("isStopMove".equals(reuse.getType())) {
mChildIsBeingDragged = false;
}
if ("isStartove".equals(reuse.getType())){
mChildIsBeingDragged = true;
}
}
public void onDestory (){
EventBus.getDefault().unregister(this);
}
}

View File

@ -1,6 +1,7 @@
package com.gh.common.view;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
@ -16,7 +17,7 @@ public class HorizontalItemDecoration extends RecyclerView.ItemDecoration {
public HorizontalItemDecoration(Context context, int interval, int size) {
paint = new Paint();
paint.setColor(0xffffffff);
paint.setColor(Color.WHITE);
mInterval = DisplayUtils.dip2px(context, interval);
mSize = size;
}

View File

@ -1,38 +0,0 @@
package com.gh.common.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
public class KeyboardLayout extends RelativeLayout {
private OnKeyboardChangedListener mListener;
public KeyboardLayout(Context context) {
super(context);
}
public KeyboardLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mListener != null) {
mListener.OnKeyboardChanged(w, h, oldw, oldh);
}
}
public interface OnKeyboardChangedListener {
void OnKeyboardChanged(int w, int h, int oldw, int oldh);
}
public void setOnKeyboardChangedListener(OnKeyboardChangedListener listener) {
this.mListener = listener;
}
}

View File

@ -1,91 +0,0 @@
package com.gh.common.view;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import com.gh.common.util.DisplayUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBShowDone;
import de.greenrobot.event.EventBus;
public class MyGame_LinearLayout extends LinearLayout {
private LinearLayout mygame_ll;
private RecyclerView mygame_rv_show;
private int height;
private int distance;
private int total;
private int position;
Runnable show = new Runnable() {
@Override
public void run() {
LayoutParams lparams = new LayoutParams(
LayoutParams.MATCH_PARENT, height);
lparams.height = mygame_ll.getHeight() + distance;
if (lparams.height > total) {
lparams.height = total;
}
mygame_ll.setLayoutParams(lparams);
invalidate();
if (lparams.height < total) {
postDelayed(show, 10);
} else {
EventBus.getDefault().post(new EBShowDone("我的游戏", position));
}
}
};
Runnable hide = new Runnable() {
@Override
public void run() {
LayoutParams lparams = new LayoutParams(
LayoutParams.MATCH_PARENT, height);
lparams.height = mygame_ll.getHeight() - distance;
if (lparams.height < height) {
lparams.height = height;
}
mygame_ll.setLayoutParams(lparams);
invalidate();
if (lparams.height > height) {
postDelayed(hide, 10);
} else {
mygame_rv_show.setVisibility(View.GONE);
}
}
};
public MyGame_LinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
height = DisplayUtils.dip2px(getContext(), 66);
distance = DisplayUtils.dip2px(getContext(), 5);
total = DisplayUtils.dip2px(getContext(), 136);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mygame_rv_show = (RecyclerView) findViewById(R.id.mygame_rv_show);
mygame_ll = (LinearLayout) findViewById(R.id.mygame_ll);
}
public void showRecyclerView(int position) {
this.position = position;
mygame_rv_show.setVisibility(View.VISIBLE);
removeCallbacks(hide);
post(show);
}
public void hideRecyclerView() {
removeCallbacks(show);
post(hide);
}
}

View File

@ -1,48 +0,0 @@
package com.gh.common.view;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
* 重写RecyclerView 解决触摸事件
*
* @author 黄壮华
*
*/
public class MyRecyclerView extends RecyclerView {
public static boolean isCanMove = false;
public MyRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private float xDis;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
xDis = ev.getX();
break;
case MotionEvent.ACTION_MOVE:
if (isCanMove) {
if (xDis - ev.getX() > 0) {
MyViewPager.isCanMove = true;
return false;
} else if (xDis - ev.getX() < 0) {
isCanMove = false;
}
}
xDis = ev.getX();
break;
default:
break;
}
return super.dispatchTouchEvent(ev);
}
}

View File

@ -1,60 +0,0 @@
package com.gh.common.view;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
* 重写ViewPager 解决触摸事件
*
* @author 黄壮华
*
*/
public class MyViewPager extends ViewPager {
public static boolean isCanMove = false;
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
if (isCanMove) {
return true;
}
break;
default:
break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
isCanMove = false;
break;
case MotionEvent.ACTION_MOVE:
if (isCanMove) {
return onTouchEvent(ev);
}
break;
case MotionEvent.ACTION_UP:
if (isCanMove) {
return onTouchEvent(ev);
}
break;
default:
break;
}
return super.dispatchTouchEvent(ev);
}
}

View File

@ -0,0 +1,44 @@
package com.gh.common.view;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by LGT on 2016/10/11.
*/
public class RecyclerViewExtended extends RecyclerView {
public RecyclerViewExtended(Context context) {
super(context);
}
public RecyclerViewExtended(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RecyclerViewExtended(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private OnDispatchTouchListener mListener;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mListener != null) {
mListener.onDispatch(this, ev);
}
return super.dispatchTouchEvent(ev);
}
public void setOnDispatchTouchListener(OnDispatchTouchListener listener) {
mListener = listener;
}
public interface OnDispatchTouchListener {
void onDispatch(View v, MotionEvent event);
}
}

View File

@ -17,7 +17,7 @@ public class VerticalItemDecoration extends RecyclerView.ItemDecoration {
public VerticalItemDecoration(Context context, int interval) {
paint = new Paint();
paint.setColor(context.getResources().getColor(R.color.bg_color));
paint.setColor(context.getResources().getColor(R.color.background));
mInterval = DisplayUtils.dip2px(context, interval);
}

View File

@ -0,0 +1,279 @@
package com.gh.common.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.gamecenter.eventbus.EBReuse;
import de.greenrobot.event.EventBus;
/**
* Created by khy on 2016/10/26.
*/
public class ZoomSimpleDraweeView extends SimpleDraweeView {
private ScaleGestureDetector mScaleDetector;
private GestureDetector mGestureDetector;
private float mCurrentScale = 1f;
private Matrix mCurrentMatrix;
private setOnSingleClickListener mClickListener;
private float imgagePro = -1; // 图片宽高比
public ZoomSimpleDraweeView(Context context) {
super(context);
init();
}
public ZoomSimpleDraweeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ZoomSimpleDraweeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mCurrentMatrix = new Matrix();
ScaleGestureDetector.OnScaleGestureListener scaleListener = new ScaleGestureDetector
.SimpleOnScaleGestureListener() {
@Override
public boolean onScale(ScaleGestureDetector detector) {
float scaleFactor = detector.getScaleFactor();
if (mCurrentScale < 4f || detector.getScaleFactor() < 1f){
mCurrentScale *= scaleFactor;
mCurrentMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
invalidate();
}
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
super.onScaleEnd(detector);
if (mCurrentScale < 1f) {
reset();
}
checkBorder();
}
};
mScaleDetector = new ScaleGestureDetector(getContext(), scaleListener);
GestureDetector.SimpleOnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (mClickListener != null) {
mClickListener.onClick();
}
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (mCurrentScale > 1f) {
mCurrentMatrix.postTranslate(-distanceX, -distanceY);
invalidate();
checkBorder();
}
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
final float x = e.getX();
final float y = e.getY();
float scaleSize ; //扩大或缩小的倍数
if (mCurrentScale > 1.5f){ //缩小时直接回到原画大小
scaleSize = 0.5f;
ZoomSimpleDraweeView.this.post(new AutoScaleRunnable(mCurrentScale * scaleSize, getWidth() / 2f, getHeight() / 2f, false));
} else {
scaleSize = 2.0f;
ZoomSimpleDraweeView.this.post(new AutoScaleRunnable(mCurrentScale * scaleSize, x, y, true));
}
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return super.onSingleTapUp(e);
}
};
mGestureDetector = new GestureDetector(getContext(), gestureListener);
}
/**
* 检查图片边界是否移到view以内
* 目的是让图片边缘不要移动到view里面
*/
private void checkBorder() {
RectF rectF = getDisplayRect(mCurrentMatrix);
boolean reset = false;
float dx = 0;
float dy = 0;
if (rectF.left > 0) {
dx = getLeft() - rectF.left;
reset = true;
}
if (rectF.top > 0) {
dy = getTop() - rectF.top;
reset = true;
}
if (rectF.right < getRight()) {
dx = getRight() - rectF.right;
reset = true;
}
if (rectF.bottom < getHeight()) {
dy = getHeight() - rectF.bottom;
reset = true;
}
if (reset) {
mCurrentMatrix.postTranslate(dx, dy);
invalidate();
}
if (dy == 0 && reset || mCurrentScale == 1f){
EventBus.getDefault().post(new EBReuse("isStopMove"));
} else{
EventBus.getDefault().post(new EBReuse("isStartove"));
}
}
/**
* Helper method that maps the supplied Matrix to the current Drawable
*
* @param matrix - Matrix to map Drawable against
* @return RectF - Displayed Rectangle
*/
private RectF getDisplayRect(Matrix matrix) {
// int bottom;
// if (imgagePro != -1){
// bottom = (int) (getRight()*imgagePro);
// } else {
// bottom = getBottom();
// }
RectF rectF = new RectF(getLeft(), getTop(), getRight(), getBottom());
matrix.mapRect(rectF);
return rectF;
}
@Override
public void setImageURI(Uri uri) {
reset();
super.setImageURI(uri);
}
@Override
protected void onDraw(Canvas canvas) {
int saveCount = canvas.save();
canvas.concat(mCurrentMatrix);
super.onDraw(canvas);
canvas.restoreToCount(saveCount);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
if (!mScaleDetector.isInProgress()) {
mGestureDetector.onTouchEvent(event);
}
return true;
}
/**
* 重置图片
*/
public void reset() {
mCurrentMatrix.reset();
mCurrentScale = 1f;
invalidate();
EventBus.getDefault().post(new EBReuse("isStopMove"));
}
private final float[] matrixValues = new float[9];
public final float getScale() {
mCurrentMatrix.getValues(matrixValues);
return matrixValues[Matrix.MSCALE_X];
}
/**
* 自动缩放的任务
*/
private class AutoScaleRunnable implements Runnable {
static final float BIGGER = 1.07f;
static final float SMALLER = 0.96f;
private float mTargetScale;
private boolean isExp;
/**
* 缩放的中心
*/
private float x;
private float y;
/**
* @param isExp :判断是否是放大
*/
public AutoScaleRunnable(float targetScale, float x, float y, boolean isExp) {
this.mTargetScale = targetScale;
this.x = x;
this.y = y;
this.isExp = isExp;
}
@Override
public void run() {
if (isExp){ //放大
mCurrentMatrix.postScale(BIGGER, BIGGER, x, y);
invalidate();
if (mCurrentScale < mTargetScale && mCurrentScale <= 4) {
ZoomSimpleDraweeView.this.postDelayed(this, 10);
mCurrentScale = mCurrentScale * BIGGER;
} else {
checkBorder();
mCurrentScale = getScale();
}
}else {//缩小
mCurrentMatrix.postScale(SMALLER, SMALLER, x, y);
invalidate();
checkBorder();
if (getScale() > 1.01) {
ZoomSimpleDraweeView.this.postDelayed(this, 1);
mCurrentScale = mCurrentScale * SMALLER;
} else {
reset();
}
}
}
}
//图片宽高比例
public void setImagePro (float imgPro){
this.imgagePro = imgPro;
}
public void setOnSingleClickListener(setOnSingleClickListener listener) {
mClickListener = listener;
}
public interface setOnSingleClickListener {
void onClick();
}
}

View File

@ -2,51 +2,48 @@ package com.gh.download;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.gh.common.util.Utils;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
public class DBHelper extends OrmLiteSqliteOpenHelper
{
public class DBHelper extends OrmLiteSqliteOpenHelper {
private static final String DB_NAME = "gh_download.db";
private static final int VERSION = 3;
/**
* downloadDao ,每张表对应一个
*/
private Dao<DownloadEntry, String> downloadDao;
private Dao<DownloadEntity, String> downloadDao;
private DBHelper(Context context)
{
private DBHelper(Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource)
{
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
Log.v("ormlite_test", "onCreate ====================");
TableUtils.createTable(connectionSource, DownloadEntry.class);
Utils.log("ormlite_test", "onCreate ====================");
TableUtils.createTable(connectionSource, DownloadEntity.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database,
ConnectionSource connectionSource, int oldVersion, int newVersion)
{
public void onUpgrade(SQLiteDatabase database,
ConnectionSource connectionSource,
int oldVersion,
int newVersion) {
try {
TableUtils.dropTable(connectionSource, DownloadEntry.class, true);
onCreate(database, connectionSource);
TableUtils.dropTable(connectionSource, DownloadEntity.class, true);
onCreate(database, connectionSource);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
}
private static DBHelper mInstance;
@ -57,25 +54,22 @@ public class DBHelper extends OrmLiteSqliteOpenHelper
* @param context
* @return
*/
public static synchronized DBHelper getInstance(Context context)
{
public static synchronized DBHelper getInstance(Context context) {
context = context.getApplicationContext();
if (mInstance == null)
{
synchronized (DBHelper.class)
{
if (mInstance == null)
mInstance = new DBHelper(context);
}
}
if (mInstance == null) {
synchronized (DBHelper.class) {
if (mInstance == null) {
mInstance = new DBHelper(context);
}
}
}
return mInstance;
}
public Dao<DownloadEntry, String> getDownloadDao(){
public Dao<DownloadEntity, String> getDownloadDao() {
try {
if(downloadDao == null){
downloadDao = getDao(DownloadEntry.class);
if (downloadDao == null) {
downloadDao = getDao(DownloadEntity.class);
}
} catch (java.sql.SQLException e) {
e.printStackTrace();
@ -87,10 +81,9 @@ public class DBHelper extends OrmLiteSqliteOpenHelper
* 释放资源
*/
@Override
public void close()
{
public void close() {
super.close();
downloadDao= null;
}
}
}

View File

@ -1,81 +1,57 @@
package com.gh.download;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
public class DataChanger extends Observable{
private HashMap<String, DownloadTask> mDownloadingTasks;//当前正在下载的任务队列
private HashMap<String, DownloadEntry> mDownloadEntries;//包含所有下载任务的任务队列
public class DataChanger extends Observable {
private static DataChanger mInstance;
private DataChanger() {
mDownloadingTasks = new HashMap<String, DownloadTask>();
mDownloadEntries = new HashMap<String, DownloadEntry>();
}
public static DataChanger getInstance(){
public static DataChanger getInstance() {
if(mInstance == null){
mInstance = new DataChanger();
}
return mInstance;
}
public HashMap<String, DownloadTask> getDownloadingTasks() {
return mDownloadingTasks;
private final Map<String, DownloadTask> mDownloadingTasks;//当前正在下载的任务队列
private final Map<String, DownloadEntity> mDownloadEntries;//包含所有下载任务的任务队列
private DataChanger() {
mDownloadingTasks = Collections.synchronizedMap(new HashMap<String, DownloadTask>());
mDownloadEntries = Collections.synchronizedMap(new HashMap<String, DownloadEntity>());
}
public HashMap<String, DownloadEntry> getDownloadEntries() {
return mDownloadEntries;
public Map<String, DownloadTask> getDownloadingTasks() {
synchronized (mDownloadingTasks) {
return mDownloadingTasks;
}
}
public void addToDownloadEntries(DownloadEntry entry) {
mDownloadEntries.put(entry.getUrl(), entry);
public Map<String, DownloadEntity> getDownloadEntries() {
synchronized (mDownloadEntries) {
return mDownloadEntries;
}
}
public int getDownloadingSize() {
return mDownloadingTasks.size();
}
public synchronized void notifyDataChanged(DownloadEntry entry) {
if(entry != null){
if(mDownloadEntries.get(entry.getUrl()) != null){
mDownloadEntries.put(entry.getUrl(), entry);
setChanged();
notifyObservers();
public synchronized void notifyDataChanged(DownloadEntity entry) {
if (entry != null) {
if (getDownloadEntries().get(entry.getUrl()) != null) {
getDownloadEntries().put(entry.getUrl(), entry);
}
setChanged();
notifyObservers(entry);
}
}
public void addToDownloadingTask(String url, DownloadTask task) {
mDownloadingTasks.put(url, task);
}
public void removeDownloadingTask(String url) {
getDownloadingTasks().remove(url);
}
public void removeDownloadEntry(String url) {
getDownloadEntries().remove(url);
}
public void pauseDownloadingTasks(String url) {
DownloadTask downloadTask = getDownloadingTasks().get(url);
if(downloadTask != null){
public synchronized void pauseDownloadingTasks(String url) {
DownloadTask downloadTask = getDownloadingTasks().remove(url);
if (downloadTask != null) {
downloadTask.pause();
removeDownloadingTask(url);
}
pauseDownloadEntries(url);
}
public void pauseDownloadEntries(String url) {
DownloadEntry entry = getDownloadEntries().get(url);
if(entry != null){
entry.setStatus(DownloadStatus.pause);
}
}
}

View File

@ -1,6 +1,5 @@
package com.gh.download;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
@ -9,10 +8,11 @@ public abstract class DataWatcher implements Observer{
@Override
public void update(Observable observable, Object data) {
onDataChanged(DataChanger.getInstance().getDownloadEntries());
if (data != null && data instanceof DownloadEntity) {
onDataChanged((DownloadEntity) data);
}
}
public abstract void onDataChanged(HashMap<String, DownloadEntry> downloadingEntries);
public abstract void onDataChanged(DownloadEntity downloadEntity);
}

View File

@ -8,7 +8,8 @@ import com.j256.ormlite.dao.Dao;
import java.util.List;
public class DownloadDao {
private static Dao<DownloadEntry, String> downloadDaoOpe;
private static Dao<DownloadEntity, String> downloadDaoOpe;
private static DBHelper helper;
private static DownloadDao mInstance;
@ -37,7 +38,7 @@ public class DownloadDao {
return mInstance;
}
public void newOrUpdate(DownloadEntry entry) {
public void newOrUpdate(DownloadEntity entry) {
try {
if (DownloadStatus.cancel.equals(entry.getStatus())) {
downloadDaoOpe.delete(entry);
@ -49,18 +50,17 @@ public class DownloadDao {
}
}
public DownloadEntry get(String url) {
public DownloadEntity get(String url) {
try {
return downloadDaoOpe.queryForId(url);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
return null;
}
public List<DownloadEntry> getAll() {
List<DownloadEntry> list = null;
public List<DownloadEntity> getAll() {
List<DownloadEntity> list = null;
try {
list = downloadDaoOpe.queryForAll();
} catch (java.sql.SQLException e) {
@ -75,6 +75,6 @@ public class DownloadDao {
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,351 @@
package com.gh.download;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.io.Serializable;
import java.util.HashMap;
@DatabaseTable(tableName = "download")
public class DownloadEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@DatabaseField(id = true, columnName="url")
private String url;
@DatabaseField(columnName="name")
private String name;
@DatabaseField(columnName="status")
private DownloadStatus status;
@DatabaseField(columnName="path")
private String path;
@DatabaseField(columnName="progress")
private long progress;
@DatabaseField(columnName="size")
private long size;
@DatabaseField(columnName="percent")
private double percent;
@DatabaseField(columnName="speed")
private long speed;
@DatabaseField(columnName="meta", dataType=DataType.SERIALIZABLE)
private HashMap<String, String> meta;//其他
public String getGameId() {
if (meta != null) {
return meta.get("gameId");
}
return null;
}
public void setGameId(String gameId) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("gameId", gameId);
}
public String getPackageName() {
if (meta != null) {
return meta.get("packageName");
}
return null;
}
public void setPackageName(String packageName) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("packageName", packageName);
}
public String getETag() {
if (meta != null) {
return meta.get("ETag");
}
return null;
}
public void setETag(String ETag) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("ETag", ETag);
}
public boolean isUpdate() {
if (meta != null) {
if ("true".equals(meta.get("isUpdate"))) {
return true;
}
}
return false;
}
public void setUpdate(boolean update) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("isUpdate", String.valueOf(update));
}
public boolean isPlugin() {
if (meta != null) {
if ("true".equals(meta.get("isPlugin"))) {
return true;
}
}
return false;
}
public void setPlugin(boolean plugin) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("isPlugin", String.valueOf(plugin));
}
public boolean isPluggable() {
if (meta != null) {
if ("true".equals(meta.get("isPluggable"))) {
return true;
}
}
return false;
}
public void setPluggable(boolean pluggable) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("isPluggable", String.valueOf(pluggable));
}
public boolean isReset() {
if (meta != null) {
if ("true".equals(meta.get("isReset"))) {
return true;
}
}
return false;
}
public void setReset(boolean reset) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("isReset", String.valueOf(reset));
}
public String getPlatform() {
if (meta != null) {
return meta.get("platform");
}
return null;
}
public void setPlatform(String platform) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("platform", platform);
}
public String getIcon() {
if (meta != null) {
return meta.get("icon");
}
return null;
}
public void setIcon(String icon) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("icon", icon);
}
public String getEntrance() {
if (meta != null) {
return meta.get("entrance");
}
return null;
}
public void setEntrance(String entrance) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("entrance", entrance);
}
public String getLocation() {
if (meta != null) {
return meta.get("location");
}
return null;
}
public void setLocation(String location) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("location", location);
}
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public String getError() {
if (meta != null) {
return meta.get("error");
}
return null;
}
public void setError(String error) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("error", error);
}
public long getStart() {
if (meta != null) {
String start = meta.get("start");
if (start == null) {
return 0;
}
return Long.valueOf(start);
}
return 0;
}
public void setStart(long start) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("start", String.valueOf(start));
}
public long getEnd() {
if (meta != null) {
String end = meta.get("end");
if (end == null) {
return 0;
}
return Long.valueOf(end);
}
return 0;
}
public void setEnd(long end) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("end", String.valueOf(end));
}
public long getInstalled() {
if (meta != null) {
String installed = meta.get("installed");
if (installed == null) {
return 0;
}
return Integer.valueOf(installed);
}
return 0;
}
public void setInstalled(int installed) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("installed", String.valueOf(installed));
}
public HashMap<String, String> getMeta() {
return meta;
}
public void setMeta(HashMap<String, String> meta) {
if (this.meta != null) {
this.meta.putAll(meta);
} else {
this.meta = meta;
}
}
public double getPercent() {
return percent;
}
public void setPercent(double percent) {
this.percent = percent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DownloadStatus getStatus() {
return status;
}
public void setStatus(DownloadStatus status) {
this.status = status;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public long getProgress() {
return progress;
}
public void setProgress(long progress) {
this.progress = progress;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}

View File

@ -1,144 +0,0 @@
package com.gh.download;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map.Entry;
@DatabaseTable(tableName = "download")
public class DownloadEntry implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@DatabaseField(id = true,columnName="url")
private String url;
// @DatabaseField(columnName="id")
// private String id;
@DatabaseField(columnName="name")
private String name;
@DatabaseField(columnName="status")
private DownloadStatus status;
@DatabaseField(columnName="path")
private String path;
@DatabaseField(columnName="progress")
private long progress;
@DatabaseField(columnName="size")
private long size;
@DatabaseField(columnName="percent")
private double percent;
@DatabaseField(columnName="speed")
private long speed;
@DatabaseField(columnName="meta", dataType=DataType.SERIALIZABLE)
private HashMap<String, String> meta;//其他
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public HashMap<String, String> getMeta() {
return meta;
}
public void setMeta(HashMap<String, String> meta) {
this.meta = meta;
}
public double getPercent() {
return percent;
}
public void setPercent(double percent) {
this.percent = percent;
}
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DownloadStatus getStatus() {
return status;
}
public void setStatus(DownloadStatus status) {
this.status = status;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public long getProgress() {
return progress;
}
public void setProgress(long progress) {
this.progress = progress;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
@Override
public String toString() {
StringBuilder metas = new StringBuilder();
metas.append("(");
int i = 1;
if(meta != null){
for (Entry<String, String> entry : meta.entrySet()) {
metas.append(entry.getKey());
metas.append(":");
metas.append(entry.getValue());
if(i != meta.size()){
metas.append(",");
}
}
}
metas.append(")");
return "["
+ name + "==="
+ url + "==="
+ path + "==="
+ status + "==="
+ progress + "==="
+ size + "==="
+ percent + "%==="
+ speed + "k/s==="
+ metas +
"]";
}
}

View File

@ -6,11 +6,12 @@ package com.gh.download;
* @version create timeSep 23, 2014 5:52:11 PM
*/
public interface DownloadListener {
/**
* 更新每一次下载的大小
* @param downloadedSize
*/
void onProgressChanged(int downloadedSize);
void onProgressChanged(long length, int downloadedSize);
/**
* 更新任务下载状态
@ -18,5 +19,10 @@ public interface DownloadListener {
*/
void onStatusChanged(DownloadStatus status);
/**
* 更新任务下载状态
* @param status
*/
void onStatusChanged(DownloadStatus status, String error);
}

Some files were not shown because too many files have changed in this diff Show More