├── .gitignore
├── README-cn.md
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── code19
│ │ └── androidcommon
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── code19
│ │ │ └── androidcommon
│ │ │ ├── HandlerActivity.java
│ │ │ ├── MainActivity.java
│ │ │ ├── model
│ │ │ ├── AppBean.java
│ │ │ ├── AppBiz.java
│ │ │ └── IAppBiz.java
│ │ │ ├── presenter
│ │ │ └── AppPresenter.java
│ │ │ ├── ui
│ │ │ ├── activity
│ │ │ │ ├── AppManagerActivity.java
│ │ │ │ ├── DeviceActivity.java
│ │ │ │ └── VerificationActivity.java
│ │ │ └── adapter
│ │ │ │ └── AppRecyAdapter.java
│ │ │ └── view
│ │ │ └── IAppView.java
│ └── res
│ │ ├── layout
│ │ ├── activity_app_manager.xml
│ │ ├── activity_device.xml
│ │ ├── activity_main.xml
│ │ ├── activity_virification.xml
│ │ └── app_recy.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── code19
│ └── androidcommon
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── code19
│ │ └── library
│ │ ├── AppUtils.java
│ │ ├── CipherUtils.java
│ │ ├── CoordinateTransformUtil.java
│ │ ├── DateUtils.java
│ │ ├── DensityUtil.java
│ │ ├── DeviceUtils.java
│ │ ├── FileUtils.java
│ │ ├── JsonUtils.java
│ │ ├── L.java
│ │ ├── NetUtils.java
│ │ ├── RadixUtils.java
│ │ ├── SPUtils.java
│ │ ├── StringUtils.java
│ │ ├── SystemUtils.java
│ │ └── VerificationUtils.java
│ └── res
│ ├── drawable
│ └── divider.xml
│ └── values
│ └── strings.xml
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | /build
7 | /captures
8 | /.idea
9 | /library/src/test
10 | /library/src/androidTest
11 | /*.properties
12 |
--------------------------------------------------------------------------------
/README-cn.md:
--------------------------------------------------------------------------------
1 | # gradle使用方式
2 | ```gradle
3 | compile 'com.code19.library:library:0.1.4'
4 | ```
5 | # 常用工具类
6 | - 常用代码片段收集 Issues
7 | - 如果你有更好的代码,请提交Pull request
8 |
9 | ```
10 | 使用示例:
11 | AppUtils.getAppName(MainActivity.this,com.code19.androidcommon);
12 | ```
13 |
14 | ## library Module中的类:
15 |
16 | - AppUtils.java 应用工具类
17 | * getAppName 获取应用名称
18 | * getAppIcon 获取应用图标
19 | * getAppFirstInstallTime 获取应用第一次安装日期
20 | * getAppLastUpdateTime 获取应用更新日期
21 | * getAppSize 获取应用大小
22 | * getAppApk 获取应用apk文件
23 | * getAppVersionName 获取应用版本名称
24 | * getAppVersionCode 获取应用版本号
25 | * getAppInstaller 获取应用的安装市场
26 | * getAppSign 获取应用签名
27 | * getAppTargetSdkVersion 获取应用兼容sdk
28 | * getAppUid 获取应用uid
29 | * getNumCores 获取Cpu内核数
30 | * getRootPermission 获得root权限
31 | * getAppPermissions 获取应用的所有权限
32 | * hasPermission 是否有权限
33 | * isInstalled 应用是否安装
34 | * ~~installApk 安装应用~~
35 | * ~~uninstallApk 卸载应用~~
36 | * isSystemApp 是否是系统应用
37 | * isServiceRunning 服务是否在运行
38 | * stopRunningService 停止服务
39 | * killProcesses 结束进程
40 | * runScript 运行脚本
41 | * runApp 启动应用
42 | * cleanCache 清除应用内部缓存
43 | * cleanDatabases 清除应用内部数据库
44 | * cleanSharedPreference 清除应用内部SP
45 |
46 | - CacheUtils.java 缓存工具类
47 | * setCache 设置缓存
48 | * getCache 获取缓存
49 |
50 | - CipherUtils.java 密码工具类
51 | * md5(String input) 字符串md5
52 | * md5L(String input) 字符串md5,返回小写密文
53 | * md5(InputStream in) 输入流md5
54 | * base64Encode Base64加密
55 | * base64Decode Base64解密
56 | * XorEncode 异或加密
57 | * XorDecode 异或解密
58 | * sha1 字符串sha1值
59 | * sha1 文件hash校验
60 |
61 | - CoordinateTransformUtil.java GPS坐标转换工具
62 | * 百度坐标(BD09)、国测局坐标(火星坐标,GCJ02)、和WGS84坐标系之间的转换的工具
63 | * bd09towgs84 百度坐标系(BD-09)转WGS坐标(百度坐标纬度,百度坐标经度),WGS84坐标数组
64 | * wgs84tobd09 WGS坐标转百度坐标系(BD-09)(WGS84坐标系的经度,WGS84坐标系的纬度),百度坐标数组
65 | * gcj02tobd09 火星坐标系(GCJ-02)转百度坐标系(BD-09)(火星坐标经度,火星坐标纬度),百度坐标数组
66 | * bd09togcj02 百度坐标系(BD-09)转火星坐标系(GCJ-02)(百度坐标纬度,百度坐标经度),火星坐标数组
67 | * wgs84togcj02 WGS84转GCJ02(火星坐标系)(WGS84坐标系的经度,WGS84坐标系的纬度),火星坐标数组
68 | * gcj02towgs84 GCJ02(火星坐标系)转GPS84(火星坐标系的经度,火星坐标系纬度),WGS84坐标数组
69 | * transformlat 纬度转换
70 | * transformlng 经度转换
71 | * out_of_china 判断是否在国内,不在国内不做偏移
72 |
73 | - DateUtil.java 日期工具类
74 | * formatDataTime 格式化日期时间
75 | * formatDate 格式化日期
76 | * formatTime 格式化时间
77 | * formatDateCustom 自定义格式的格式化日期时间
78 | * string2Date 将时间字符串转换成Date
79 | * getDate 获取系统日期
80 | * getTime 获取系统时间
81 | * getDateTime 获取系统日期时间
82 | * subtractDate 计算两个时间差
83 | * getDateAfter 得到几天后的时间
84 | * getWeekOfMonth 获取当前时间为本月的第几周
85 | * getDayOfWeek 获取当前时间为本周的第几天
86 |
87 | - DensityUtil.java 屏幕工具类
88 | * dip2px dp转像素
89 | * dip2sp dip转sp
90 | * px2dip 像素转dp
91 | * px2sp 像素转sp
92 | * sp2px sp转像素
93 | * sp2dip sp转dip
94 | * getScreenW 获取屏幕宽度
95 | * getScreenH 获取屏幕高度
96 | * getScreenRealSize 获取屏幕的真实高度
97 | * getStatusBarH 获取状态栏高度
98 | * getNavigationBarrH 获取导航栏高度
99 |
100 | - DeviceUtils.java 设备信息工具
101 | * getAndroidID 获取AndroidID
102 | * getIMEI 获取设备IMEI码
103 | * getIMSI 获取设备IMSI码
104 | * getWifiMacAddr 获取MAC地址
105 | * getIP 获取网络IP地址(优先获取wifi地址)
106 | * getWifiIP 获取WIFI连接下的ip地址
107 | * getGPRSIP 获取GPRS连接下的ip地址
108 | * getSerial 获取设备序列号
109 | * getSIMSerial 获取SIM序列号
110 | * getMNC 获取网络运营商 46000,46002,46007 中国移动,46001 中国联通,46003 中国电信
111 | * getCarrier 获取网络运营商:中国电信,中国移动,中国联通
112 | * getModel 获取硬件型号
113 | * getBuildBrand 获取编译厂商
114 | * getBuildHost 获取编译服务器主机
115 | * getBuildTags 获取描述Build的标签
116 | * getBuildTime 获取系统编译时间
117 | * getBuildUser 获取系统编译作者
118 | * getBuildVersionRelease 获取编译系统版本(5.1)
119 | * getBuildVersionCodename 获取开发代号
120 | * getBuildVersionIncremental 获取源码控制版本号
121 | * getBuildVersionSDK 获取编译的SDK
122 | * getBuildID 获取修订版本列表(LMY47D)
123 | * getSupportedABIS CPU指令集
124 | * getManufacturer 获取硬件制造厂商
125 | * getBootloader 获取系统启动程序版本号
126 | * getScreenDisplayID
127 | * getDisplayVersion 获取系统版本号
128 | * getLanguage 获取语言
129 | * getCountry 获取国家
130 | * getOSVersion 获取系统版本:5.1.1
131 | * getGSFID 获取GSF序列号
132 | * getBluetoothMAC 获取蓝牙地址
133 | * getPsuedoUniqueID Android设备物理唯一标识符
134 | * getFingerprint 构建标识,包括brand,name,device,version.release,id,version.incremental,type,tags这些信息
135 | * getHardware 获取硬件信息
136 | * getProduct 获取产品信息
137 | * getDevice 获取设备信息
138 | * getBoard 获取主板信息
139 | * getRadioVersion 获取基带版本(无线电固件版本 Api14以上)
140 | * getUA 获取的浏览器指纹(User-Agent)
141 | * getDensity 获取得屏幕密度
142 | * getGoogleAccounts 获取google账号
143 |
144 |
145 | - FileUtils.java 文件工具类
146 | * closeIO 关闭IO流
147 | * isFileExist 文件是否存在
148 | * writeFile 将字符串写入到文件
149 | * readFile 从文件中读取字符串
150 | * readFile 从文件中读取字符串(可设置编码)
151 | * copyFile 复制文件
152 | * copyFileFast 快速复制
153 | * shareFile 分享文件
154 | * zip zip压缩
155 | * unzip zip解压
156 | * formatFileSize 格式化文件大小
157 | * Stream2File 将输入流写入到文件
158 | * createFolder 创建文件夹
159 | * createFolder 创建文件夹(支持覆盖已存在的同名文件夹)
160 | * getFileName 获取文件名
161 | * getFileSize 获取文件大小
162 | * rename 重名名文件\文件夹
163 | * getFolderName 获取文件夹名称
164 | * getFilesArray 获取文件夹下所有文件
165 | * deleteFile 删除文件
166 | * deleteFileByDirectory 删除目录下的所有文件
167 | * openImage 打开图片
168 | * openVideo 打开视频
169 | * openURL 打开URL
170 | * downloadFile 下载文件
171 | * upgradeApp 通过APKURL升级应用
172 | * isSDCardAvailable 是否挂在SDCard
173 | * getAppExternalPath 获取应用在SDCard上的工作路径
174 | * getExtraPath 获取SDCard上目录的路径
175 |
176 | - JsonUtils.java Json工具类(需要依赖Gson 2.0以上)
177 | * toJson 对象转json
178 | * fromJson json转对象
179 | * mapToJson Map转为JSONObject
180 | * collection2Json 集合转换为JSONArray
181 | * object2Json Object对象转换为JSONArray
182 | * string2JSONObject json字符串生成JSONObject对象
183 |
184 | - L.java 日志工具
185 | * init 初始化日志开关和TAG(默认日志为开,TAG为"ghost")
186 | * v VERBOSE
187 | * d DEBUG
188 | * i INFO
189 | * w WARN
190 | * e ERROR
191 | * a ASSERT
192 | * json 输出json
193 | * xml 输出xml
194 |
195 | - NetUtils.java 网络工具
196 | * getNetworkType 获取网络类型
197 | * getNetworkTypeName 获取网络名称
198 | * isConnected 检查网络状态
199 | * isNetworkAvailable 网络可用性
200 | * isWiFi 是否wifi
201 | * openNetSetting 打开网络设置界面
202 | * setWifiEnabled 设置wifi状态
203 | * setDataEnabled 设置数据流量状态
204 | * getWifiScanResults 获取wifi列表
205 | * getScanResultsByBSSID 过滤扫描结果
206 | * getWifiConnectionInfo 获取wifi连接信息
207 |
208 | - RadixUtils 进制工具类
209 | *
210 | - SPUtils.java SharedPreferences工具
211 | * setSP 存储SharedPreferences值
212 | * getSp 获取SharedPreferences值
213 | * cleanAllSP 清除所有的SP值
214 |
215 | - StringUtils.java 字符串工具
216 | * getChsAscii 汉字转成ASCII码
217 | * convert 单字解析
218 | * getSelling 词组解析
219 | * parseEmpty 将null转化为""
220 | * isEmpty 是否是空字符串
221 | * chineseLength 中文长度
222 | * strLength 字符串长度
223 | * subStringLength 获取指定长度的字符所在位置
224 | * isChinese 是否是中文
225 | * isContainChinese 是否包含中文
226 | * strFormat2 不足2位前面补0
227 | * convert2Int 类型安全转换
228 | * decimalFormat 指定小数输出
229 |
230 | - SystemUtils.java 系统工具
231 | * sendSMS 调用系统发送短信
232 | * forwardToDial 跳转到拨号
233 | * sendMail 发邮件
234 | * openWeb 打开浏览器
235 | * openContacts 打开联系人
236 | * openSettings 打开系统设置
237 | ```
238 | /**
239 | * com.android.settings.AccessibilitySettings 辅助功能设置
240 | * com.android.settings.ActivityPicker 选择活动
241 | * com.android.settings.ApnSettings APN设置
242 | * com.android.settings.ApplicationSettings 应用程序设置
243 | * com.android.settings.BandMode 设置GSM/UMTS波段
244 | * com.android.settings.BatteryInfo 电池信息
245 | * com.android.settings.DateTimeSettings 日期和时间设置
246 | * com.android.settings.DateTimeSettingsSetupWizard 日期和时间设置
247 | * com.android.settings.DevelopmentSettings 应用程序设置=》开发设置
248 | * com.android.settings.DeviceAdminSettings 设备管理器
249 | * com.android.settings.DeviceInfoSettings 关于手机
250 | * com.android.settings.Display 显示——设置显示字体大小及预览
251 | * com.android.settings.DisplaySettings 显示设置
252 | * com.android.settings.DockSettings 底座设置
253 | * com.android.settings.IccLockSettings SIM卡锁定设置
254 | * com.android.settings.InstalledAppDetails 语言和键盘设置
255 | * com.android.settings.LanguageSettings 语言和键盘设置
256 | * com.android.settings.LocalePicker 选择手机语言
257 | * com.android.settings.LocalePickerInSetupWizard 选择手机语言
258 | * com.android.settings.ManageApplications 已下载(安装)软件列表
259 | * com.android.settings.MasterClear 恢复出厂设置
260 | * com.android.settings.MediaFormat 格式化手机闪存
261 | * com.android.settings.PhysicalKeyboardSettings 设置键盘
262 | * com.android.settings.PrivacySettings 隐私设置
263 | * com.android.settings.ProxySelector 代理设置
264 | * com.android.settings.RadioInfo 手机信息
265 | * com.android.settings.RunningServices 正在运行的程序(服务)
266 | * com.android.settings.SecuritySettings 位置和安全设置
267 | * com.android.settings.Settings 系统设置
268 | * com.android.settings.SettingsSafetyLegalActivity 安全信息
269 | * com.android.settings.SoundSettings 声音设置
270 | * com.android.settings.TestingSettings 测试——显示手机信息、电池信息、使用情况统计、Wifi
271 | * information、服务信息 com.android.settings.TetherSettings 绑定与便携式热点
272 | * com.android.settings.TextToSpeechSettings 文字转语音设置
273 | * com.android.settings.UsageStats 使用情况统计
274 | * com.android.settings.UserDictionarySettings 用户词典
275 | * com.android.settings.VoiceInputOutputSettings 语音输入与输出设置
276 | * com.android.settings.WirelessSettings 无线和网络设置
277 | */
278 | ```
279 |
280 | * hideKeyBoard 隐藏系统键盘
281 | * isBackground 判断当前应用程序是否后台运行
282 | * isSleeping 判断手机是否处理睡眠
283 | * installApk 安装apk
284 | * isRooted 是否root
285 | * isRunningOnEmulator 当前设备是否是模拟器
286 | * goHome 返回Home
287 | * hexdigest 32位签名
288 | * getDeviceUsableMemory 获取设备可用空间
289 | * gc 清理后台进程和服务
290 | * getProcessName 获取进程名字
291 | * createDeskShortCut 创建桌面快捷方式
292 | * createShortcut 创建快捷方式
293 | * shareText 分享文本
294 | * shareFile 分享文件(此方法是调用FileUtils.shareFile中的方式)
295 | * getShareTargets 获取可接受分享的应用
296 | * getCurrentLanguage 获取当前系统的语言
297 | * getLanguage 获取当前系统的语言
298 | * isGpsEnabled GPS是否打开
299 | * showSoftInputMethod 显示软键盘
300 | * closeSoftInputMethod 关闭软键盘
301 | * showSoftInput 显示软键盘
302 | * closeSoftInput 关闭软键盘
303 | * toWeChatScan 打开微信扫描
304 | * toAliPayScan 打开支付宝扫描
305 | * toAliPayPayCode 打开支付宝支付码
306 | * getRandomNumber 获取随机数
307 |
308 | - VerificationUtils.java 验证工具类
309 | * matcherRealName 判断姓名格式
310 | ```
311 | 真实姓名可以是汉字,也可以是字母,但是不能两者都有,也不能包含任何符号和数字
312 | 1.如果是英文名,可以允许英文名字中出现空格
313 | 2.英文名的空格可以是多个,但是不能连续出现多个
314 | 3.汉字不能出现空格
315 | ```
316 | * matcherPhoneNum 判断手机号格式 (匹配11数字,并且13-19开头)
317 | * matcherAccount 判断账号格式 (4-20位字符)
318 | * matcherPassword 判断密码格式 (6-12位字母或数字)
319 | * matcherPassword2 判断密码格式 (6-12位字母或数字,必须同时包含字母和数字)
320 | * matcherEmail 判断邮箱格式
321 | * matcherIP 判断IP地址
322 | * matcherUrl 判断URL (http,https,ftp)
323 | * matcherVehicleNumber 判断中国民用车辆号牌
324 | * matcherIdentityCard 判断身份证号码格式
325 | * isNumeric 是否数值型
326 | * testRegex 是否匹配正则
327 | * checkPostcode 匹配中国邮政编码
328 |
329 |
330 | ```shell
331 |
332 | /**
333 | * 身份证校验
334 | *
335 | * 根据〖中华人民共和国国家标准 GB 11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。
336 | * 排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。
337 | * 地址码表示编码对象常住户口所在县(市、旗、区)的行政区划代码。
338 | * 出生日期码表示编码对象出生的年、月、日,其中年份用四位数字表示,年、月、日之间不用分隔符。
339 | * 顺序码表示同一地址码所标识的区域范围内,对同年、月、日出生的人员编定的顺序号。顺序码的奇数分给男性,偶数分给女性。
340 | * 校验码是根据前面十七位数字码,按照ISO 7064:1983.MOD 11-2校验码计算出来的检验码。
341 | * 出生日期计算方法。
342 | * 15位的身份证编码首先把出生年扩展为4位,简单的就是增加一个19或18,这样就包含了所有1800-1999年出生的人;
343 | * 2000年后出生的肯定都是18位的了没有这个烦恼,至于1800年前出生的,那啥那时应该还没身份证号这个东东,⊙﹏⊙b汗...
344 | * 下面是正则表达式:
345 | * 出生日期1800-2099 /(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])/
346 | * 身份证正则表达式 /^[1-9]\d{5}((1[89]|20)\d{2})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dx]$/i
347 | * 15位校验规则 6位地址编码+6位出生日期+3位顺序号
348 | * 18位校验规则 6位地址编码+8位出生日期+3位顺序号+1位校验位
349 | * 校验位规则 公式:∑(ai×Wi)(mod 11)……………………………………(1)
350 | * 公式(1)中:
351 | * i----表示号码字符从由至左包括校验码在内的位置序号;
352 | * ai----表示第i位置上的号码字符值;
353 | * Wi----示第i位置上的加权因子,其数值依据公式Wi=2^(n-1)(mod 11)计算得出。
354 | * i 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
355 | * Wi 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 1
356 | *
357 | *
358 | * @author Yoojia.Chen (yoojia.chen@gmail.com)
359 | * @version version 2015-05-21
360 | * @since 2.0
361 | */
362 | ```
363 |
364 | # 这个库参考了众多网络的中的代码,在此对这些无私奉献的人致以最诚挚的感谢。
365 | License
366 | ----
367 |
368 | Copyright (C) 2016 android@19code.com
369 |
370 | Licensed under the Apache License, Version 2.0 (the "License");
371 | you may not use this file except in compliance with the License.
372 | You may obtain a copy of the License at
373 |
374 | http://www.apache.org/licenses/LICENSE-2.0
375 |
376 | Unless required by applicable law or agreed to in writing, software
377 | distributed under the License is distributed on an "AS IS" BASIS,
378 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
379 | See the License for the specific language governing permissions and
380 | limitations under the License.
381 |
382 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # How to use In Android Studio
2 | ```gradle
3 | compile 'com.code19.library:library:0.1.4'
4 | ```
5 |
6 | # notes
7 | [0.1.4 removed](https://github.com/h4de5ing/AndroidCommon/commit/f4cb414ce8a7732fb152c510833f782b0cf0fd6d "0.1.4 we removed") ``ToastUtils``,``ViewUtils.java``,``SpannableStringUtils.java``,if you used then,you can use 0.1.2.
8 |
9 | # Common Utils
10 | - Collection Chop [Issues](https://github.com/h4de5ing/AndroidCommon/issues)
11 | - Show Me The Best Code [Pull request](https://github.com/h4de5ing/AndroidCommon/pulls)
12 |
13 | ```
14 | Demo:
15 | AppUtils.getAppName(MainActivity.this,"com.code19.androidcommon");
16 | ```
17 | ## [中文文档](README-cn.md)
18 | ## library Module:
19 |
20 | - AppUtils.java (about Application tools)
21 | * getAppName
22 | * getAppIcon
23 | * getAppFirstInstallTime
24 | * getAppLastUpdateTime
25 | * getAppSize
26 | * getAppApk
27 | * getAppVersionName
28 | * getAppVersionCode
29 | * getAppInstaller
30 | * getAppSign
31 | * getAppTargetSdkVersion
32 | * getAppUid
33 | * getNumCores
34 | * getRootPermission
35 | * getAppPermissions
36 | * hasPermission
37 | * isInstalled
38 | * ~~installApk~~
39 | * ~~uninstallApk~~
40 | * isSystemApp
41 | * isServiceRunning
42 | * stopRunningService
43 | * killProcesses
44 | * runScript
45 | * runApp
46 | * cleanCache
47 | * cleanDatabases
48 | * cleanSharedPreference
49 |
50 | - CipherUtils.java
51 | * md5(String input)
52 | * md5L(String input)
53 | * md5(InputStream in)
54 | * base64Encode
55 | * base64Decode
56 | * XorEncode
57 | * XorDecode
58 | * sha1(String str)
59 | * sha1(File file)
60 |
61 | - DateUtil.java
62 | * formatDataTime
63 | * formatDate
64 | * formatTime
65 | * formatDateCustom
66 | * string2Date
67 | * getDate
68 | * getTime
69 | * getDateTime
70 | * subtractDate
71 | * getDateAfter
72 | * getWeekOfMonth
73 | * getDayOfWeek
74 |
75 | - DensityUtil.java
76 | * dip2px
77 | * dip2sp
78 | * px2dip
79 | * px2sp
80 | * sp2px
81 | * sp2dip
82 | * getScreenW
83 | * getScreenH
84 | * getScreenRealSize
85 | * getStatusBarH
86 | * getNavigationBarrH
87 |
88 | - DeviceUtils.java
89 | * getAndroidID
90 | * getIMEI
91 | * getIMSI
92 | * getWifiMacAddr
93 | * getIP
94 | * getWifiIP
95 | * getGPRSIP
96 | * getSerial
97 | * getSIMSerial
98 | * getMNC
99 | * getCarrier
100 | * getModel
101 | * getBuildBrand
102 | * getBuildHost
103 | * getBuildTags
104 | * getBuildTime
105 | * getBuildUser
106 | * getBuildVersionRelease
107 | * getBuildVersionCodename
108 | * getBuildVersionIncremental
109 | * getBuildVersionSDK
110 | * getBuildID
111 | * getSupportedABIS
112 | * getManufacturer
113 | * getBootloader
114 | * getScreenDisplayID
115 | * getDisplayVersion
116 | * getLanguage
117 | * getCountry
118 | * getOSVersion
119 | * getGSFID
120 | * getBluetoothMAC
121 | * getPsuedoUniqueID
122 | * getFingerprint
123 | * getHardware
124 | * getProduct
125 | * getDevice
126 | * getBoard
127 | * getRadioVersion
128 | * getUA
129 | * getDensity
130 | * getGoogleAccounts
131 |
132 |
133 | - FileUtils.java
134 | * closeIO
135 | * isFileExist
136 | * writeFile
137 | * readFile
138 | * readFile
139 | * copyFile
140 | * copyFileFast
141 | * shareFile
142 | * zip
143 | * unzip
144 | * formatFileSize
145 | * Stream2File
146 | * createFolder
147 | * createFolder
148 | * getFileName
149 | * getFileSize
150 | * rename
151 | * getFolderName
152 | * getFilesArray
153 | * deleteFile
154 | * deleteFileByDirectory
155 | * openImage
156 | * openVideo
157 | * openURL
158 | * downloadFile
159 | * upgradeApp
160 | * isSDCardAvailable
161 | * getAppExternalPath
162 | * getExtraPath
163 |
164 | - JsonUtils.java
165 | * toJson
166 | * fromJson
167 | * mapToJson
168 | * collection2Json
169 | * object2Json
170 | * string2JSONObject
171 |
172 | - L.java
173 | * init //Init the Log set Debug and Tag
174 | * v VERBOSE
175 | * d DEBUG
176 | * i INFO
177 | * w WARN
178 | * e ERROR
179 | * a ASSERT
180 | * json
181 | * xml
182 |
183 | - NetUtils.java
184 | * getNetworkType
185 | * getNetworkTypeName
186 | * isConnected
187 | * isNetworkAvailable
188 | * isWiFi
189 | * openNetSetting
190 | * setWifiEnabled
191 | * setDataEnabled
192 | * getWifiScanResults
193 | * getScanResultsByBSSID
194 | * getWifiConnectionInfo
195 |
196 | - SPUtils.java
197 | * setSP
198 | * getSp
199 | * cleanAllSP
200 |
201 | - StringUtils.java
202 | * getChsAscii
203 | * convert
204 | * getSelling
205 | * parseEmpty
206 | * isEmpty
207 | * chineseLength
208 | * strLength
209 | * subStringLength
210 | * isChinese
211 | * isContainChinese
212 | * strFormat2
213 | * convert2Int
214 | * decimalFormat
215 |
216 | - SystemUtils.java
217 | * sendSMS
218 | * forwardToDial
219 | * sendMail
220 | * openWeb
221 | * openContacts
222 | * openSettings
223 | * hideKeyBoard
224 | * isBackground
225 | * isSleeping
226 | * installApk
227 | * isRooted
228 | * isRunningOnEmulator
229 | * goHome
230 | * hexdigest
231 | * getDeviceUsableMemory
232 | * gc
233 | * getProcessName
234 | * createDeskShortCut
235 | * createShortcut
236 | * shareText
237 | * shareFile
238 | * getShareTargets
239 | * getCurrentLanguage
240 | * getLanguage
241 | * isGpsEnabled
242 | * showSoftInputMethod
243 | * closeSoftInputMethod
244 | * showSoftInput
245 | * closeSoftInput
246 | * toWeChatScan
247 | * toAliPayScan
248 | * toAliPayPayCode
249 | * getRandomNumber
250 |
251 | - VerificationUtils.java
252 | * matcherRealName
253 | * matcherPhoneNum //just matcher chinese phone number
254 | * matcherAccount
255 | * matcherPassword
256 | * matcherPassword2
257 | * matcherEmail
258 | * matcherIP
259 | * matcherUrl
260 | * isNumeric
261 | * testRegex
262 |
263 | # Thanks to all the open source programmers
264 | License
265 | ----
266 |
267 | Copyright (C) 2016 moxi1992@gmail.com
268 |
269 | Licensed under the Apache License, Version 2.0 (the "License");
270 | you may not use this file except in compliance with the License.
271 | You may obtain a copy of the License at
272 |
273 | http://www.apache.org/licenses/LICENSE-2.0
274 |
275 | Unless required by applicable law or agreed to in writing, software
276 | distributed under the License is distributed on an "AS IS" BASIS,
277 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
278 | See the License for the specific language governing permissions and
279 | limitations under the License.
280 |
281 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion '25.0.0'
6 |
7 | defaultConfig {
8 | applicationId "com.code19.androidcommon"
9 | minSdkVersion 15
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.3.0'
26 | compile project(':library')
27 | compile 'com.android.support:recyclerview-v7:23.3.0'
28 | compile 'com.android.support:cardview-v7:23.3.0'
29 | }
30 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in E:\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/code19/androidcommon/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon;
18 |
19 | import android.app.Application;
20 | import android.test.ApplicationTestCase;
21 |
22 | /**
23 | * Testing Fundamentals
24 | */
25 | public class ApplicationTest extends ApplicationTestCase {
26 | public ApplicationTest() {
27 | super(Application.class);
28 | }
29 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
48 |
49 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/HandlerActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon;
18 |
19 | import android.os.Bundle;
20 | import android.os.Handler;
21 | import android.os.Message;
22 | import android.os.PersistableBundle;
23 | import android.support.v7.app.AppCompatActivity;
24 |
25 | import java.lang.ref.WeakReference;
26 |
27 | /**
28 | * Create by h4de5ing 2016/5/10 010
29 | * 论Handler的正确使用方式, 参考自:https://yq.aliyun.com/articles/3009 Android 内存泄漏总结
30 | */
31 | public class HandlerActivity extends AppCompatActivity {
32 | private static class MyHandler extends Handler {
33 | private final WeakReference mMainActivityWeakReference;
34 |
35 | public MyHandler(HandlerActivity activity) {
36 | mMainActivityWeakReference = new WeakReference<>(activity);
37 | }
38 |
39 | @Override
40 | public void handleMessage(Message msg) {
41 | super.handleMessage(msg);
42 | HandlerActivity activity = mMainActivityWeakReference.get();
43 | if (activity != null) {
44 | // 处理msg
45 | switch (msg.what) {
46 | case 0:
47 | break;
48 | case 1:
49 | break;
50 | case 2:
51 | break;
52 | }
53 |
54 | }
55 | }
56 | }
57 |
58 |
59 | private final MyHandler mMyHandler = new MyHandler(this);
60 | private static final Runnable sRunnable = new Runnable() {
61 | @Override
62 | public void run() {
63 | // 执行的内容
64 | Message message = new Message();
65 | message.arg1 = 1;
66 | }
67 | };
68 |
69 | @Override
70 | public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
71 | super.onCreate(savedInstanceState, persistentState);
72 | mMyHandler.postDelayed(sRunnable, 1000 * 6);//6秒钟后执行
73 | finish();
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon;
18 |
19 | import android.content.Intent;
20 | import android.os.Bundle;
21 | import android.support.v7.app.AppCompatActivity;
22 | import android.view.View;
23 | import android.widget.Button;
24 | import android.widget.LinearLayout;
25 |
26 | import com.code19.androidcommon.ui.activity.AppManagerActivity;
27 | import com.code19.androidcommon.ui.activity.DeviceActivity;
28 | import com.code19.androidcommon.ui.activity.VerificationActivity;
29 | import com.code19.library.FileUtils;
30 |
31 | public class MainActivity extends AppCompatActivity implements View.OnClickListener {
32 | private LinearLayout mMain;
33 |
34 | @Override
35 | protected void onCreate(Bundle savedInstanceState) {
36 | super.onCreate(savedInstanceState);
37 | setContentView(R.layout.activity_main);
38 | mMain = (LinearLayout) findViewById(R.id.main);
39 | Button virification = (Button) findViewById(R.id.virification);
40 | Button deviceutils = (Button) findViewById(R.id.deviceutils);
41 | Button testutils = (Button) findViewById(R.id.testutils);
42 | Button fileutils = (Button) findViewById(R.id.fileutils);
43 | Button apputils = (Button) findViewById(R.id.apputils);
44 | testutils.setOnClickListener(this);
45 | fileutils.setOnClickListener(this);
46 | apputils.setOnClickListener(this);
47 | deviceutils.setOnClickListener(this);
48 | virification.setOnClickListener(this);
49 | }
50 |
51 | @Override
52 | public void onClick(View v) {
53 | switch (v.getId()) {
54 | case R.id.apputils:
55 | startActivity(new Intent(MainActivity.this, AppManagerActivity.class));
56 | break;
57 | case R.id.deviceutils:
58 | startActivity(new Intent(MainActivity.this, DeviceActivity.class));
59 | break;
60 | case R.id.fileutils:
61 | String url = "http://3lin9.19code.com/app.apk";
62 | FileUtils.upgradeApp(MainActivity.this, url);
63 | break;
64 | case R.id.testutils:
65 | //Bitmap bitmap = ViewUtils.createViewBitmap(mMain);
66 | //ImageUtils.bitmap2gallery(this, bitmap, "main.png");
67 | break;
68 | case R.id.virification:
69 | startActivity(new Intent(MainActivity.this, VerificationActivity.class));
70 | break;
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/model/AppBean.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon.model;
18 |
19 | import android.graphics.drawable.Drawable;
20 |
21 | /**
22 | * Create by h4de5ing 2016/5/24 024
23 | */
24 | public class AppBean {
25 | private String appName;
26 | private Drawable appIcon;
27 | private long appDate;
28 | private long appSize;
29 | private String appAPk;
30 | private String appVerName;
31 | private int appVerCode;
32 | private String appInstaller;
33 | private boolean isSystemApp;
34 | private String appPackage;
35 |
36 | public String getAppPackage() {
37 | return appPackage;
38 | }
39 |
40 | public void setAppPackage(String appPackage) {
41 | this.appPackage = appPackage;
42 | }
43 |
44 |
45 | public String getAppName() {
46 | return appName;
47 | }
48 |
49 | public void setAppName(String appName) {
50 | this.appName = appName;
51 | }
52 |
53 | public Drawable getAppIcon() {
54 | return appIcon;
55 | }
56 |
57 | public void setAppIcon(Drawable appIcon) {
58 | this.appIcon = appIcon;
59 | }
60 |
61 | public long getAppDate() {
62 | return appDate;
63 | }
64 |
65 | public void setAppDate(long appDate) {
66 | this.appDate = appDate;
67 | }
68 |
69 | public long getAppSize() {
70 | return appSize;
71 | }
72 |
73 | public void setAppSize(long appSize) {
74 | this.appSize = appSize;
75 | }
76 |
77 | public String getAppAPk() {
78 | return appAPk;
79 | }
80 |
81 | public void setAppAPk(String appAPk) {
82 | this.appAPk = appAPk;
83 | }
84 |
85 | public String getAppVerName() {
86 | return appVerName;
87 | }
88 |
89 | public void setAppVerName(String appVerName) {
90 | this.appVerName = appVerName;
91 | }
92 |
93 | public int getAppVerCode() {
94 | return appVerCode;
95 | }
96 |
97 | public void setAppVerCode(int appVerCode) {
98 | this.appVerCode = appVerCode;
99 | }
100 |
101 | public String getAppInstaller() {
102 | return appInstaller;
103 | }
104 |
105 | public void setAppInstaller(String appInstaller) {
106 | this.appInstaller = appInstaller;
107 | }
108 |
109 | public boolean isSystemApp() {
110 | return isSystemApp;
111 | }
112 |
113 | public void setSystemApp(boolean systemApp) {
114 | isSystemApp = systemApp;
115 | }
116 |
117 | @Override
118 | public String toString() {
119 | return "AppBean{" +
120 | "appName='" + appName + '\'' +
121 | ", appDate=" + appDate +
122 | ", appSize=" + appSize +
123 | ", appAPk='" + appAPk + '\'' +
124 | ", appVerName='" + appVerName + '\'' +
125 | ", appVerCode=" + appVerCode +
126 | ", appInstaller='" + appInstaller + '\'' +
127 | ", isSystemApp=" + isSystemApp +
128 | '}';
129 | }
130 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/model/AppBiz.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon.model;
18 |
19 | import android.content.Context;
20 | import android.content.pm.PackageInfo;
21 | import android.graphics.drawable.Drawable;
22 | import android.text.TextUtils;
23 |
24 | import com.code19.library.AppUtils;
25 |
26 | import java.util.ArrayList;
27 | import java.util.List;
28 |
29 | /**
30 | * Create by h4de5ing 2016/5/24 024
31 | */
32 | public class AppBiz implements IAppBiz {
33 |
34 | @Override
35 | public void getData(Context c, OnAppLoadListener onAppLoadListener) {
36 | List list = new ArrayList<>();
37 | List installedPackages = c.getPackageManager().getInstalledPackages(0);
38 | for (PackageInfo info : installedPackages) {
39 | String appName = AppUtils.getAppName(c, info.packageName);
40 | Drawable appIcon = AppUtils.getAppIcon(c, info.packageName);
41 | long appDate = AppUtils.getAppDate(c, info.packageName);
42 | long appSize = AppUtils.getAppSize(c, info.packageName);
43 | String appApk = AppUtils.getAppApk(c, info.packageName);
44 | String appVersionName = AppUtils.getAppVersionName(c, info.packageName);
45 | int appVersionCode = AppUtils.getAppVersionCode(c, info.packageName);
46 | String appInstaller = AppUtils.getAppInstaller(c, info.packageName);
47 | boolean systemApp = AppUtils.isSystemApp(c, info.packageName);
48 | if (!TextUtils.isEmpty(appName) &&
49 | !TextUtils.isEmpty(appApk) &&
50 | !TextUtils.isEmpty(appVersionName) &&
51 | !TextUtils.isEmpty(appInstaller) &&
52 | appIcon != null
53 | && appDate > 0
54 | && appSize > 0
55 | && appVersionCode > 0) {
56 | AppBean appBean = new AppBean();
57 | appBean.setAppName(appName);
58 | appBean.setAppIcon(appIcon);
59 | appBean.setAppDate(appDate);
60 | appBean.setAppSize(appSize);
61 | appBean.setAppAPk(appApk);
62 | appBean.setAppVerName(appVersionName);
63 | appBean.setAppVerCode(appVersionCode);
64 | appBean.setAppInstaller(appInstaller);
65 | appBean.setSystemApp(systemApp);
66 | appBean.setAppPackage(info.packageName);
67 | list.add(appBean);
68 | }
69 | }
70 | onAppLoadListener.loadSuccess(list);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/model/IAppBiz.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon.model;
18 |
19 | import android.content.Context;
20 |
21 | import java.util.List;
22 |
23 | /**
24 | * Create by h4de5ing 2016/5/24 024
25 | */
26 | public interface IAppBiz {
27 | void getData(Context context, OnAppLoadListener onAppLoadListener);
28 |
29 | interface OnAppLoadListener {
30 | void loading();
31 |
32 | void loadSuccess(List list);
33 |
34 | void loadFaile();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/presenter/AppPresenter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon.presenter;
18 |
19 | import android.content.Context;
20 | import android.os.Handler;
21 |
22 | import com.code19.androidcommon.model.AppBean;
23 | import com.code19.androidcommon.model.AppBiz;
24 | import com.code19.androidcommon.model.IAppBiz;
25 | import com.code19.androidcommon.view.IAppView;
26 |
27 | import java.util.List;
28 |
29 | /**
30 | * Create by h4de5ing 2016/5/24 024
31 | */
32 | public class AppPresenter {
33 | private IAppBiz mIAppBiz;
34 | private IAppView mIAppView;
35 | private Handler mHandler;
36 | private Context mContext;
37 |
38 | public AppPresenter(Context context, IAppView iAppView) {
39 | this.mContext = context;
40 | this.mHandler = new Handler();
41 | this.mIAppBiz = new AppBiz();
42 | this.mIAppView = iAppView;
43 | }
44 |
45 | public void getData() {
46 | new Thread(new Runnable() {
47 | @Override
48 | public void run() {
49 | mIAppBiz.getData(mContext, new IAppBiz.OnAppLoadListener() {
50 | @Override
51 | public void loading() {
52 | mIAppView.showLoading();
53 | }
54 |
55 | @Override
56 | public void loadSuccess(final List list) {
57 | mIAppView.hideLoading();
58 | mHandler.post(new Runnable() {
59 | @Override
60 | public void run() {
61 | mIAppView.referData(list);
62 | }
63 | });
64 | }
65 |
66 | @Override
67 | public void loadFaile() {
68 | mIAppView.hideLoading();
69 | }
70 | });
71 | }
72 | }).start();
73 |
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/ui/activity/AppManagerActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon.ui.activity;
18 |
19 | import android.app.ProgressDialog;
20 | import android.os.Bundle;
21 | import android.support.v7.app.AppCompatActivity;
22 | import android.support.v7.widget.GridLayoutManager;
23 | import android.support.v7.widget.RecyclerView;
24 |
25 | import com.code19.androidcommon.R;
26 | import com.code19.androidcommon.model.AppBean;
27 | import com.code19.androidcommon.presenter.AppPresenter;
28 | import com.code19.androidcommon.ui.adapter.AppRecyAdapter;
29 | import com.code19.androidcommon.view.IAppView;
30 | import com.code19.library.L;
31 |
32 | import java.util.List;
33 |
34 | public class AppManagerActivity extends AppCompatActivity implements IAppView {
35 | private static final String TAG = "ghost";
36 |
37 | private AppPresenter mPresenter;
38 | private ProgressDialog mDialog;
39 | private RecyclerView mRecyapp;
40 |
41 | @Override
42 | protected void onCreate(Bundle savedInstanceState) {
43 | super.onCreate(savedInstanceState);
44 | setContentView(R.layout.activity_app_manager);
45 | mRecyapp = (RecyclerView) findViewById(R.id.recy_app);
46 | mRecyapp.setLayoutManager(new GridLayoutManager(this, 4));
47 | mRecyapp.setHasFixedSize(true);
48 | initProgress();
49 | mPresenter = new AppPresenter(this, this);
50 | new Thread(new Runnable() {
51 | @Override
52 | public void run() {
53 | mPresenter.getData();
54 | }
55 | }).start();
56 | }
57 |
58 | private void initProgress() {
59 | mDialog = new ProgressDialog(this);
60 | mDialog.setMessage(getString(R.string.loading));
61 | mDialog.setCancelable(true);
62 | mDialog.setCanceledOnTouchOutside(false);
63 | mDialog.show();
64 | }
65 |
66 | @Override
67 | public void showLoading() {
68 | mDialog.show();
69 | }
70 |
71 | @Override
72 | public void hideLoading() {
73 | mDialog.cancel();
74 | }
75 |
76 | @Override
77 | public void referData(List list) {
78 | for (AppBean bean : list) {
79 | L.i(TAG, "app: " + bean.toString());
80 | }
81 | mRecyapp.setAdapter(new AppRecyAdapter(this, list));
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/ui/activity/DeviceActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon.ui.activity;
18 |
19 | import android.content.Context;
20 | import android.os.Bundle;
21 | import android.support.v7.app.AppCompatActivity;
22 | import android.util.Log;
23 | import android.widget.TextView;
24 |
25 | import com.code19.androidcommon.R;
26 | import com.code19.library.DensityUtil;
27 | import com.code19.library.DeviceUtils;
28 | import com.code19.library.SystemUtils;
29 |
30 | public class DeviceActivity extends AppCompatActivity {
31 | private Context c;
32 | private TextView mDeviceutilstextview;
33 |
34 | @Override
35 | protected void onCreate(Bundle savedInstanceState) {
36 | super.onCreate(savedInstanceState);
37 | setContentView(R.layout.activity_device);
38 | c = this;
39 | mDeviceutilstextview = (TextView) findViewById(R.id.deviceutils_textview);
40 | initDeviecesInfos();
41 | }
42 |
43 | private void initDeviecesInfos() {
44 | StringBuilder sb = new StringBuilder();
45 | sb.append("AndroidID--" + DeviceUtils.getAndroidID(c) + "\n");
46 | sb.append("getIMEI--" + DeviceUtils.getIMEI(c) + "\n");
47 | sb.append("getIMSI--" + DeviceUtils.getIMSI(c) + "\n");
48 | sb.append("getWifiMacAddr--" + DeviceUtils.getWifiMacAddr(c) + "\n");
49 | //sb.append("getIP--" + DeviceUtils.getIP(c) + "\n");
50 | sb.append("getSerial--" + DeviceUtils.getSerial() + "\n");
51 | sb.append("getSIMSerial--" + DeviceUtils.getSIMSerial(c) + "\n");
52 | sb.append("getMNC--" + DeviceUtils.getMNC(c) + "\n");
53 | sb.append("getBuildBrand--" + DeviceUtils.getBuildBrand() + "\n");
54 | sb.append("getBuildHost--" + DeviceUtils.getBuildHost() + "\n");
55 | sb.append("getBuildTags--" + DeviceUtils.getBuildTags() + "\n");
56 | sb.append("getBuildTime--" + DeviceUtils.getBuildTime() + "\n");
57 | sb.append("getBuildUser--" + DeviceUtils.getBuildUser() + "\n");
58 | sb.append("getBuildVersionRelease--" + DeviceUtils.getBuildVersionRelease() + "\n");
59 | sb.append("getBuildVersionCodename--" + DeviceUtils.getBuildVersionCodename() + "\n");
60 | sb.append("getBuildVersionIncremental--" + DeviceUtils.getBuildVersionIncremental() + "\n");
61 | sb.append("getBuildVersionSDK--" + DeviceUtils.getBuildVersionSDK() + "\n");
62 | sb.append("getSupportedABIS--" + DeviceUtils.getSupportedABIS()[0] + DeviceUtils.getSupportedABIS()[1] + "\n");
63 | sb.append("getManufacturer--" + DeviceUtils.getManufacturer() + "\n");
64 | sb.append("getBootloader--" + DeviceUtils.getBootloader() + "\n");
65 | sb.append("getScreenDisplayID--" + DeviceUtils.getScreenDisplayID(c) + "\n");
66 | sb.append("getDisplayVersion--" + DeviceUtils.getDisplayVersion() + "\n");
67 | sb.append("getLanguage--" + DeviceUtils.getLanguage() + "\n");
68 | sb.append("getCountry--" + DeviceUtils.getCountry(c) + "\n");
69 | sb.append("getOSVersion--" + DeviceUtils.getOSVersion() + "\n");
70 | //sb.append("getGSFID--" + DeviceUtils.getGSFID(c) + "\n");
71 | sb.append("getBluetoothMAC--" + DeviceUtils.getBluetoothMAC(c) + "\n");
72 | sb.append("getPsuedoUniqueID--" + DeviceUtils.getPsuedoUniqueID() + "\n");
73 | sb.append("getFingerprint--" + DeviceUtils.getFingerprint() + "\n");
74 | sb.append("getHardware--" + DeviceUtils.getHardware() + "\n");
75 | sb.append("getProduct--" + DeviceUtils.getProduct() + "\n");
76 | sb.append("getDevice--" + DeviceUtils.getDevice() + "\n");
77 | sb.append("getBoard--" + DeviceUtils.getBoard() + "\n");
78 | sb.append("getRadioVersion--" + DeviceUtils.getRadioVersion() + "\n");
79 | sb.append("getUA--" + DeviceUtils.getUA(c) + "\n");
80 | sb.append("getDensity--" + DeviceUtils.getDensity(c) + "\n");
81 | //sb.append("getAccounts--" + DeviceUtils.getGoogleAccounts(c)[0] + "\n");
82 | sb.append("isRunningOnEmulator--" + SystemUtils.isRunningOnEmulator() + "\n");
83 | sb.append("isRooted--" + SystemUtils.isRooted() + "\n");
84 | sb.append("ScreenWidth x ScreenHeight--" + DensityUtil.getScreenW(c) + "x" + (DensityUtil.getScreenRealH(c)) + "\n");
85 | Log.i("ghost", "StatusBar:" + DensityUtil.getStatusBarH(c) + ",Nav:" + DensityUtil.getNavigationBarrH(c));
86 | mDeviceutilstextview.setText(sb);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/ui/activity/VerificationActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon.ui.activity;
18 |
19 | import android.os.Bundle;
20 | import android.support.v7.app.AppCompatActivity;
21 | import android.view.View;
22 | import android.widget.Button;
23 | import android.widget.EditText;
24 |
25 | import com.code19.androidcommon.R;
26 | import com.code19.library.VerificationUtils;
27 |
28 | public class VerificationActivity extends AppCompatActivity {
29 |
30 | private EditText mVirisnumber;
31 | private EditText mVirname;
32 | private EditText mVirphonenumber;
33 | private EditText mViraccount;
34 | private EditText mVirpassword;
35 | private EditText mVirpassword2;
36 | private EditText mViremail;
37 | private EditText mVirip;
38 | private EditText mVirurl;
39 | private EditText mViridcard;
40 |
41 | @Override
42 | protected void onCreate(Bundle savedInstanceState) {
43 | super.onCreate(savedInstanceState);
44 | setContentView(R.layout.activity_virification);
45 | Button virsubmit = (Button) findViewById(R.id.vir_submit);
46 | mVirisnumber = (EditText) findViewById(R.id.vir_isnumber);
47 | mViridcard = (EditText) findViewById(R.id.vir_idcard);
48 | mVirurl = (EditText) findViewById(R.id.vir_url);
49 | mVirip = (EditText) findViewById(R.id.vir_ip);
50 | mViremail = (EditText) findViewById(R.id.vir_email);
51 | mVirpassword2 = (EditText) findViewById(R.id.vir_password2);
52 | mVirpassword = (EditText) findViewById(R.id.vir_password);
53 | mViraccount = (EditText) findViewById(R.id.vir_account);
54 | mVirphonenumber = (EditText) findViewById(R.id.vir_phonenumber);
55 | mVirname = (EditText) findViewById(R.id.vir_name);
56 | if (virsubmit != null) {
57 | virsubmit.setOnClickListener(
58 | new View.OnClickListener() {
59 | @Override
60 | public void onClick(View v) {
61 | if (!VerificationUtils.matcherRealName(mVirname.getText().toString())) {
62 | mVirname.setError("姓名不匹配");
63 | } else if (!VerificationUtils.matcherPhoneNum(mVirphonenumber.getText().toString())) {
64 | mVirphonenumber.setError("电话号码不匹配");
65 | } else if (!VerificationUtils.matcherAccount(mViraccount.getText().toString())) {
66 | mViraccount.setError("账号不匹配");
67 | } else if (!VerificationUtils.matcherPassword(mVirpassword.getText().toString())) {
68 | mVirpassword.setError("密码1不匹配");
69 | } else if (!VerificationUtils.matcherPassword2(mVirpassword2.getText().toString())) {
70 | mVirpassword2.setError("密码2不匹配");
71 | } else if (!VerificationUtils.matcherEmail(mViremail.getText().toString())) {
72 | mViremail.setError("邮箱不匹配");
73 | } else if (!VerificationUtils.matcherIP(mVirip.getText().toString())) {
74 | mVirip.setError("IP不匹配");
75 | } else if (!VerificationUtils.matcherUrl(mVirurl.getText().toString())) {
76 | mVirurl.setError("URL不匹配");
77 | } else if (!VerificationUtils.matcherIdentityCard(mViridcard.getText().toString())) {
78 | mViridcard.setError("身份证号码不匹配");
79 | } else if (!VerificationUtils.isNumeric(mVirisnumber.getText().toString())) {
80 | mVirisnumber.setError("不是数字");
81 | }
82 | }
83 | }
84 | );
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/ui/adapter/AppRecyAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon.ui.adapter;
18 |
19 | import android.content.Context;
20 | import android.support.v7.widget.RecyclerView;
21 | import android.view.LayoutInflater;
22 | import android.view.View;
23 | import android.view.ViewGroup;
24 | import android.widget.ImageView;
25 | import android.widget.TextView;
26 |
27 | import com.code19.androidcommon.R;
28 | import com.code19.androidcommon.model.AppBean;
29 | import com.code19.library.AppUtils;
30 | import com.code19.library.L;
31 |
32 | import java.util.List;
33 |
34 | /**
35 | * Create by h4de5ing 2016/5/24 024
36 | */
37 | public class AppRecyAdapter extends RecyclerView.Adapter {
38 | private Context mContext;
39 | private List mDatas;
40 | private LayoutInflater mLayoutInflater;
41 |
42 | public AppRecyAdapter(Context context, List list) {
43 | this.mContext = context;
44 | this.mDatas = list;
45 | this.mLayoutInflater = LayoutInflater.from(context);
46 | }
47 |
48 |
49 | @Override
50 | public AppViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
51 | return new AppViewHolder(mLayoutInflater.inflate(R.layout.app_recy, parent, false));
52 | }
53 |
54 | @Override
55 | public int getItemCount() {
56 | return mDatas.size() != 0 ? mDatas.size() : 0;
57 | }
58 |
59 | @Override
60 | public void onBindViewHolder(AppViewHolder holder, int position) {
61 | holder.tv_name.setText(mDatas.get(position).getAppName());
62 | holder.iv_icon.setImageDrawable(mDatas.get(position).getAppIcon());
63 | }
64 |
65 | class AppViewHolder extends RecyclerView.ViewHolder {
66 | TextView tv_name;
67 | ImageView iv_icon;
68 |
69 | public AppViewHolder(View itemView) {
70 | super(itemView);
71 | tv_name = (TextView) itemView.findViewById(R.id.recy_name);
72 | iv_icon = (ImageView) itemView.findViewById(R.id.recy_icon);
73 | itemView.setOnClickListener(new View.OnClickListener() {
74 | @Override
75 | public void onClick(View v) {
76 | L.i(mDatas.get(getAdapterPosition()).getAppPackage(), getAdapterPosition());
77 | //Toast.makeText(mContext, "点击了Item" + getAdapterPosition(), Toast.LENGTH_SHORT).show();
78 | AppUtils.runApp(mContext, mDatas.get(getAdapterPosition()).getAppPackage());
79 | }
80 | });
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/app/src/main/java/com/code19/androidcommon/view/IAppView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon.view;
18 |
19 | import com.code19.androidcommon.model.AppBean;
20 |
21 | import java.util.List;
22 |
23 | /**
24 | * Create by h4de5ing 2016/5/24 024
25 | */
26 | public interface IAppView {
27 | void showLoading();
28 |
29 | void hideLoading();
30 |
31 | void referData(List list);
32 | }
33 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_app_manager.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
15 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_device.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
16 |
17 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
27 |
28 |
29 |
35 |
36 |
42 |
43 |
44 |
50 |
51 |
52 |
58 |
59 |
65 |
97 |
98 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_virification.xml:
--------------------------------------------------------------------------------
1 |
2 |
14 |
15 |
20 |
21 |
25 |
26 |
27 |
32 |
33 |
38 |
39 |
44 |
45 |
50 |
51 |
56 |
57 |
62 |
63 |
68 |
69 |
74 |
75 |
80 |
81 |
86 |
87 |
93 |
94 |
95 |
96 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/app_recy.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/h4de5ing/AndroidCommon/abbc53dc3d6bae05589c2696e5c30838e481cb14/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/h4de5ing/AndroidCommon/abbc53dc3d6bae05589c2696e5c30838e481cb14/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/h4de5ing/AndroidCommon/abbc53dc3d6bae05589c2696e5c30838e481cb14/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/h4de5ing/AndroidCommon/abbc53dc3d6bae05589c2696e5c30838e481cb14/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/h4de5ing/AndroidCommon/abbc53dc3d6bae05589c2696e5c30838e481cb14/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
21 | 64dp
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | #3F51B5
20 | #303F9F
21 | #FF4081
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 | 16dp
20 | 16dp
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 | Android工具库
19 | 加载中...
20 | 应用工具
21 | 缓存工具
22 | Bitmap工具
23 | 加密工具
24 | 日期时间工具
25 | 日志工具
26 | 设备工具
27 | 文件工具(升级应用)
28 | Json工具
29 | 测试工具
30 | 属性工具
31 | 系统工具
32 | 验证工具
33 | View工具
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
20 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/test/java/com/code19/androidcommon/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.androidcommon;
18 |
19 | import org.junit.Test;
20 |
21 | import static org.junit.Assert.*;
22 |
23 | /**
24 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
25 | */
26 | public class ExampleUnitTest {
27 | @Test
28 | public void addition_isCorrect() throws Exception {
29 | assertEquals(4, 2 + 2);
30 | }
31 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.3.3'
9 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.0'
10 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
11 |
12 | // NOTE: Do not place your application dependencies here; they belong
13 | // in the individual module build.gradle files
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | jcenter()
20 | }
21 | }
22 |
23 | task clean(type: Delete) {
24 | delete rootProject.buildDir
25 | }
26 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | ## Project-wide Gradle settings.
2 | #
3 | # For more details on how to configure your build environment visit
4 | # http://www.gradle.org/docs/current/userguide/build_environment.html
5 | #
6 | # Specifies the JVM arguments used for the daemon process.
7 | # The setting is particularly useful for tweaking memory settings.
8 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
9 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
10 | #
11 | # When configured, Gradle will run in incubating parallel mode.
12 | # This option should only be used with decoupled projects. More details, visit
13 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
14 | # org.gradle.parallel=true
15 | #Mon May 23 10:02:15 CST 2016
16 | #systemProp.http.proxyHost=127.0.0.1
17 | #systemProp.http.proxyPort=1248
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/h4de5ing/AndroidCommon/abbc53dc3d6bae05589c2696e5c30838e481cb14/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | apply plugin: 'com.jfrog.bintray'
4 |
5 | version = "0.1.4" //版本号,更新代码后修改这个值
6 | android {
7 | compileSdkVersion 24
8 | buildToolsVersion '25.0.3'
9 |
10 | defaultConfig {
11 | minSdkVersion 15
12 | targetSdkVersion 25
13 | versionCode 2
14 | versionName "0.1.4"
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | }
23 |
24 | dependencies {
25 | //compile 'com.android.support:appcompat-v7:24.2.1'
26 | //compile fileTree(include: ['*.jar'], dir: 'libs')
27 | //testCompile 'junit:junit:4.12'
28 | //compile 'com.google.code.gson:gson:2+'
29 | compile 'com.google.code.gson:gson:2.2.4'
30 | }
31 | def siteUrl = 'https://github.com/h4de5ing/AndroidCommon'
32 | def gitUrl = 'https://github.com/h4de5ing/AndroidCommon.git'
33 | group = "com.code19.library"
34 | install {
35 | repositories.mavenInstaller {
36 | pom {
37 | project {
38 | packaging 'aar'
39 | name 'Android common library'
40 | url siteUrl
41 | licenses {
42 | license {
43 | name 'The Apache Software License, Version 2.0'
44 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
45 | }
46 | }
47 | developers {
48 | developer {
49 | id 'h4de5ing'
50 | name 'h4de5ing'
51 | email 'android@19code.com'
52 | }
53 | }
54 | scm {
55 | connection gitUrl
56 | developerConnection gitUrl
57 | url siteUrl
58 | }
59 | }
60 | }
61 | }
62 | }
63 | task sourcesJar(type: Jar) {
64 | from android.sourceSets.main.java.srcDirs
65 | classifier = 'sources'
66 | }
67 | task javadoc(type: Javadoc) {
68 | source = android.sourceSets.main.java.srcDirs
69 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
70 | }
71 | task javadocJar(type: Jar, dependsOn: javadoc) {
72 | classifier = 'javadoc'
73 | from javadoc.destinationDir
74 | }
75 | artifacts {
76 | archives javadocJar
77 | archives sourcesJar
78 | }
79 | Properties properties = new Properties()
80 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
81 | bintray { //用户名和上传key的位置
82 | user = properties.getProperty("bintray.user")
83 | key = properties.getProperty("bintray.apikey")
84 | configurations = ['archives']
85 | pkg {
86 | repo = "maven"
87 | name = "h4de5ing-common" //发布到JCenter上的项目名字
88 | websiteUrl = siteUrl
89 | vcsUrl = gitUrl
90 | licenses = ["Apache-2.0"]
91 | publish = true
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in E:\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
19 |
20 |
21 |
22 |
23 |
24 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/CipherUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import android.util.Base64;
20 |
21 | import java.io.File;
22 | import java.io.FileInputStream;
23 | import java.io.IOException;
24 | import java.io.InputStream;
25 | import java.security.DigestInputStream;
26 | import java.security.MessageDigest;
27 | import java.security.NoSuchAlgorithmException;
28 |
29 | /**
30 | * Create by h4de5ing 2016/5/7 007
31 | */
32 | public class CipherUtils {
33 |
34 | public static String md5(String input) {
35 | try {
36 | MessageDigest messageDigest = MessageDigest.getInstance("MD5");
37 | messageDigest.update(input.getBytes());
38 | byte[] resultByteArray = messageDigest.digest();
39 | char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
40 | char[] resultCharArray = new char[resultByteArray.length * 2];
41 | int index = 0;
42 | for (byte b : resultByteArray) {
43 | resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
44 | resultCharArray[index++] = hexDigits[b & 0xf];
45 | }
46 | return new String(resultCharArray);
47 | } catch (NoSuchAlgorithmException e) {
48 | return null;
49 | }
50 | }
51 |
52 | public static String md5L(String input) {
53 | try {
54 | MessageDigest mdInst = MessageDigest.getInstance("MD5");
55 | mdInst.update(input.getBytes());
56 | byte[] md = mdInst.digest();
57 | StringBuilder hexString = new StringBuilder();
58 | for (byte aMd : md) {
59 | String shaHex = Integer.toHexString(aMd & 0xFF);
60 | if (shaHex.length() < 2) {
61 | hexString.append(0);
62 | }
63 | hexString.append(shaHex);
64 | }
65 | return hexString.toString();
66 | } catch (NoSuchAlgorithmException e) {
67 | e.printStackTrace();
68 | }
69 | return "";
70 | }
71 |
72 | public static String md5(InputStream in) {
73 | int bufferSize = 256 * 1024;
74 | DigestInputStream digestInputStream = null;
75 | try {
76 | MessageDigest messageDigest = MessageDigest.getInstance("MD5");
77 | digestInputStream = new DigestInputStream(in, messageDigest);
78 | byte[] buffer = new byte[bufferSize];
79 | while (digestInputStream.read(buffer) > 0) ;
80 | messageDigest = digestInputStream.getMessageDigest();
81 | byte[] resultByteArray = messageDigest.digest();
82 | char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
83 | char[] resultCharArray = new char[resultByteArray.length * 2];
84 | int index = 0;
85 | for (byte b : resultByteArray) {
86 | resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
87 | resultCharArray[index++] = hexDigits[b & 0xf];
88 | }
89 | return new String(resultCharArray);
90 | } catch (NoSuchAlgorithmException e) {
91 | return null;
92 | } catch (IOException e) {
93 | e.printStackTrace();
94 | } finally {
95 | try {
96 | if (digestInputStream != null)
97 | digestInputStream.close();
98 | } catch (Exception e) {
99 | e.printStackTrace();
100 | }
101 | }
102 | return null;
103 | }
104 |
105 |
106 | public static String base64Encode(String str) {
107 | return Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
108 | }
109 |
110 |
111 | public static String base64Decode(String str) {
112 | return Base64.decode(str.getBytes(), Base64.DEFAULT).toString();
113 | }
114 |
115 |
116 | public static String XorEncode(String str, String privatekey) {
117 | int[] snNum = new int[str.length()];
118 | String result = "";
119 | String temp = "";
120 | for (int i = 0, j = 0; i < str.length(); i++, j++) {
121 | if (j == privatekey.length())
122 | j = 0;
123 | snNum[i] = str.charAt(i) ^ privatekey.charAt(j);
124 | }
125 | for (int k = 0; k < str.length(); k++) {
126 | if (snNum[k] < 10) {
127 | temp = "00" + snNum[k];
128 | } else {
129 | if (snNum[k] < 100) {
130 | temp = "0" + snNum[k];
131 | }
132 | }
133 | result += temp;
134 | }
135 | return result;
136 | }
137 |
138 | public static String XorDecode(String str, String privateKey) {
139 | char[] snNum = new char[str.length() / 3];
140 | String result = "";
141 |
142 | for (int i = 0, j = 0; i < str.length() / 3; i++, j++) {
143 | if (j == privateKey.length())
144 | j = 0;
145 | int n = Integer.parseInt(str.substring(i * 3, i * 3 + 3));
146 | snNum[i] = (char) ((char) n ^ privateKey.charAt(j));
147 | }
148 | for (int k = 0; k < str.length() / 3; k++) {
149 | result += snNum[k];
150 | }
151 | return result;
152 | }
153 |
154 | public static String sha1(String str) {
155 | try {
156 | MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
157 | digest.update(str.getBytes());
158 | byte messageDigest[] = digest.digest();
159 | StringBuilder hexString = new StringBuilder();
160 | for (byte aMessageDigest : messageDigest) {
161 | String shaHex = Integer.toHexString(aMessageDigest & 0xFF);
162 | if (shaHex.length() < 2) {
163 | hexString.append(0);
164 | }
165 | hexString.append(shaHex);
166 | }
167 | return hexString.toString();
168 |
169 | } catch (NoSuchAlgorithmException e) {
170 | e.printStackTrace();
171 | }
172 | return "";
173 | }
174 |
175 | public static String sha1(File file) {
176 | FileInputStream in = null;
177 | try {
178 | in = new FileInputStream(file);
179 | MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
180 | byte[] b = new byte[1024 * 1024 * 10];//10M memory
181 | int len;
182 | while ((len = in.read(b)) > 0) {
183 | messageDigest.update(b, 0, len);
184 | }
185 | return byte2Hex(messageDigest.digest());
186 | } catch (NoSuchAlgorithmException e) {
187 | e.printStackTrace();
188 | } catch (IOException e) {
189 | e.printStackTrace();
190 | } finally {
191 | FileUtils.closeIO(in);
192 | }
193 | return null;
194 | }
195 |
196 | private static String byte2Hex(byte[] b) {
197 | StringBuilder sb = new StringBuilder();
198 | for (byte aB : b) {
199 | String s = Integer.toHexString(aB & 0xFF);
200 | if (s.length() == 1) {
201 | sb.append("0");
202 | }
203 | //sb.append(s.toUpperCase());
204 | sb.append(s);
205 | }
206 | return sb.toString();
207 | }
208 | }
209 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/CoordinateTransformUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | /**
20 | * https://github.com/wandergis/coordtransform javaScript Version
21 | */
22 | public class CoordinateTransformUtil {
23 | static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
24 | static double pi = 3.1415926535897932384626;
25 | static double a = 6378245.0;
26 | static double ee = 0.00669342162296594323;
27 |
28 | public static double[] bd09towgs84(double lng, double lat) {
29 | double[] gcj = bd09togcj02(lng, lat);
30 | double[] wgs84 = gcj02towgs84(gcj[0], gcj[1]);
31 | return wgs84;
32 | }
33 |
34 | public static double[] wgs84tobd09(double lng, double lat) {
35 | double[] gcj = wgs84togcj02(lng, lat);
36 | double[] bd09 = gcj02tobd09(gcj[0], gcj[1]);
37 | return bd09;
38 | }
39 |
40 | public static double[] gcj02tobd09(double lng, double lat) {
41 | double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi);
42 | double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi);
43 | double bd_lng = z * Math.cos(theta) + 0.0065;
44 | double bd_lat = z * Math.sin(theta) + 0.006;
45 | return new double[]{bd_lng, bd_lat};
46 | }
47 |
48 | public static double[] bd09togcj02(double bd_lon, double bd_lat) {
49 | double x = bd_lon - 0.0065;
50 | double y = bd_lat - 0.006;
51 | double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
52 | double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
53 | double gg_lng = z * Math.cos(theta);
54 | double gg_lat = z * Math.sin(theta);
55 | return new double[]{gg_lng, gg_lat};
56 | }
57 |
58 | public static double[] wgs84togcj02(double lng, double lat) {
59 | if (out_of_china(lng, lat)) {
60 | return new double[]{lng, lat};
61 | }
62 | double dlat = transformlat(lng - 105.0, lat - 35.0);
63 | double dlng = transformlng(lng - 105.0, lat - 35.0);
64 | double radlat = lat / 180.0 * pi;
65 | double magic = Math.sin(radlat);
66 | magic = 1 - ee * magic * magic;
67 | double sqrtmagic = Math.sqrt(magic);
68 | dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
69 | dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi);
70 | double mglat = lat + dlat;
71 | double mglng = lng + dlng;
72 | return new double[]{mglng, mglat};
73 | }
74 |
75 | public static double[] gcj02towgs84(double lng, double lat) {
76 | if (out_of_china(lng, lat)) {
77 | return new double[]{lng, lat};
78 | }
79 | double dlat = transformlat(lng - 105.0, lat - 35.0);
80 | double dlng = transformlng(lng - 105.0, lat - 35.0);
81 | double radlat = lat / 180.0 * pi;
82 | double magic = Math.sin(radlat);
83 | magic = 1 - ee * magic * magic;
84 | double sqrtmagic = Math.sqrt(magic);
85 | dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
86 | dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi);
87 | double mglat = lat + dlat;
88 | double mglng = lng + dlng;
89 | return new double[]{lng * 2 - mglng, lat * 2 - mglat};
90 | }
91 |
92 | public static double transformlat(double lng, double lat) {
93 | double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
94 | ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0;
95 | ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
96 | ret += (160.0 * Math.sin(lat / 12.0 * pi) + 320 * Math.sin(lat * pi / 30.0)) * 2.0 / 3.0;
97 | return ret;
98 | }
99 |
100 | public static double transformlng(double lng, double lat) {
101 | double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
102 | ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0;
103 | ret += (20.0 * Math.sin(lng * pi) + 40.0 * Math.sin(lng / 3.0 * pi)) * 2.0 / 3.0;
104 | ret += (150.0 * Math.sin(lng / 12.0 * pi) + 300.0 * Math.sin(lng / 30.0 * pi)) * 2.0 / 3.0;
105 | return ret;
106 | }
107 |
108 | public static boolean out_of_china(double lng, double lat) {
109 | if (lng < 72.004 || lng > 137.8347) {
110 | return true;
111 | } else if (lat < 0.8293 || lat > 55.8271) {
112 | return true;
113 | }
114 | return false;
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/DateUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import java.text.ParseException;
20 | import java.text.SimpleDateFormat;
21 | import java.util.Calendar;
22 | import java.util.Date;
23 |
24 | /**
25 | * Create by h4de5ing 2016/5/7 007
26 | */
27 | public class DateUtils {
28 | private static final SimpleDateFormat DATE_FORMAT_DATETIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
29 | private static final SimpleDateFormat DATE_FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd");
30 | private static final SimpleDateFormat DATE_FORMAT_TIME = new SimpleDateFormat("HH:mm:ss");
31 |
32 | public static String formatDataTime(long date) {
33 | return DATE_FORMAT_DATETIME.format(new Date(date));
34 | }
35 |
36 | public static String formatDate(long date) {
37 | return DATE_FORMAT_DATE.format(new Date(date));
38 | }
39 |
40 | public static String formatTime(long date) {
41 | return DATE_FORMAT_TIME.format(new Date(date));
42 | }
43 |
44 | public static String formatDateCustom(String beginDate, String format) {
45 | return new SimpleDateFormat(format).format(new Date(Long.parseLong(beginDate)));
46 | }
47 |
48 | public static String formatDateCustom(Date beginDate, String format) {
49 | return new SimpleDateFormat(format).format(beginDate);
50 | }
51 |
52 | public static Date string2Date(String s, String style) {
53 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
54 | simpleDateFormat.applyPattern(style);
55 | Date date = null;
56 | if (s == null || s.length() < 6) {
57 | return null;
58 | }
59 | try {
60 | date = simpleDateFormat.parse(s);
61 | } catch (ParseException e) {
62 | e.printStackTrace();
63 | }
64 | return date;
65 | }
66 |
67 | public static String getTime() {
68 | Calendar cal = Calendar.getInstance();
69 | cal.setTimeInMillis(System.currentTimeMillis());
70 | return cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND);
71 | }
72 |
73 | public static String getDate() {
74 | return new SimpleDateFormat("yyyyMMdd").format(System.currentTimeMillis());
75 | }
76 | public static String getDateTime(){
77 | return DATE_FORMAT_DATETIME.format(System.currentTimeMillis());
78 | }
79 | public static String getDateTime(String format){
80 | return new SimpleDateFormat(format).format(System.currentTimeMillis());
81 | }
82 |
83 | public static long subtractDate(Date dateStart, Date dateEnd) {
84 | return dateEnd.getTime() - dateStart.getTime();
85 | }
86 |
87 | public static Date getDateAfter(Date d, int day) {
88 | Calendar now = Calendar.getInstance();
89 | now.setTime(d);
90 | now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
91 | return now.getTime();
92 | }
93 |
94 | public static int getWeekOfMonth() {
95 | Calendar calendar = Calendar.getInstance();
96 | int week = calendar.get(Calendar.WEEK_OF_MONTH);
97 | return week - 1;
98 | }
99 |
100 | public static int getDayOfWeek() {
101 | Calendar calendar = Calendar.getInstance();
102 | int day = calendar.get(Calendar.DAY_OF_WEEK);
103 | if (day == 1) {
104 | day = 7;
105 | } else {
106 | day = day - 1;
107 | }
108 | return day;
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/DensityUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import android.annotation.TargetApi;
20 | import android.content.Context;
21 | import android.content.res.Resources;
22 | import android.os.Build;
23 | import android.util.DisplayMetrics;
24 | import android.util.TypedValue;
25 | import android.view.Display;
26 | import android.view.WindowManager;
27 |
28 | import java.lang.reflect.Field;
29 | import java.lang.reflect.Method;
30 |
31 | /**
32 | * Create by h4de5ing 2016/5/7 007
33 | */
34 | public class DensityUtil {
35 |
36 | public static int dip2px(Context c, float dpValue) {
37 | final float scale = c.getResources().getDisplayMetrics().density;
38 | return (int) (dpValue * scale + 0.5f);
39 | }
40 |
41 | public static int dip2sp(Context c, float dpValue) {
42 | return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, c.getResources().getDisplayMetrics()));
43 | }
44 |
45 | public static int px2dip(Context c, float pxValue) {
46 | final float scale = c.getResources().getDisplayMetrics().density;
47 | return (int) (pxValue / scale + 0.5f);
48 | }
49 |
50 |
51 | public static int px2sp(Context c, float pxValue) {
52 | float fontScale = c.getResources().getDisplayMetrics().scaledDensity;
53 | return (int) (pxValue / fontScale + 0.5f);
54 | }
55 |
56 |
57 | public static int sp2px(Context c, float spValue) {
58 | float fontScale = c.getResources().getDisplayMetrics().scaledDensity;
59 | return (int) (spValue * fontScale + 0.5f);
60 | }
61 |
62 | public static int sp2dip(Context c, float spValue) {
63 | return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, c.getResources().getDisplayMetrics()));
64 | }
65 |
66 | public static int getScreenW(Context c) {
67 | return c.getResources().getDisplayMetrics().widthPixels;
68 | }
69 |
70 | public static int getScreenH(Context c) {
71 | return c.getResources().getDisplayMetrics().heightPixels;
72 | }
73 |
74 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
75 | public static int getScreenRealH(Context context) {
76 | int h;
77 | WindowManager winMgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
78 | Display display = winMgr.getDefaultDisplay();
79 | DisplayMetrics dm = new DisplayMetrics();
80 | if (Build.VERSION.SDK_INT >= 17) {
81 | display.getRealMetrics(dm);
82 | h = dm.heightPixels;
83 | } else {
84 | try {
85 | Method method = Class.forName("android.view.Display").getMethod("getRealMetrics", DisplayMetrics.class);
86 | method.invoke(display, dm);
87 | h = dm.heightPixels;
88 | } catch (Exception e) {
89 | display.getMetrics(dm);
90 | h = dm.heightPixels;
91 | }
92 | }
93 | return h;
94 | }
95 |
96 | public static int getStatusBarH(Context context) {
97 | Class> c;
98 | Object obj;
99 | Field field;
100 | int statusBarHeight = 0;
101 | try {
102 | c = Class.forName("com.android.internal.R$dimen");
103 | obj = c.newInstance();
104 | field = c.getField("status_bar_height");
105 | int x = Integer.parseInt(field.get(obj).toString());
106 | statusBarHeight = context.getResources().getDimensionPixelSize(x);
107 | } catch (Exception e1) {
108 | e1.printStackTrace();
109 | }
110 | return statusBarHeight;
111 | }
112 |
113 | public static int getNavigationBarrH(Context c) {
114 | Resources resources = c.getResources();
115 | int identifier = resources.getIdentifier("navigation_bar_height", "dimen", "android");
116 | return resources.getDimensionPixelOffset(identifier);
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/DeviceUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import android.Manifest;
20 | import android.accounts.Account;
21 | import android.accounts.AccountManager;
22 | import android.bluetooth.BluetoothAdapter;
23 | import android.content.Context;
24 | import android.content.pm.PackageManager;
25 | import android.database.Cursor;
26 | import android.net.Uri;
27 | import android.net.wifi.WifiInfo;
28 | import android.net.wifi.WifiManager;
29 | import android.os.Build;
30 | import android.provider.Settings;
31 | import android.telephony.TelephonyManager;
32 | import android.util.DisplayMetrics;
33 | import android.view.WindowManager;
34 | import android.webkit.WebView;
35 |
36 | import java.net.InetAddress;
37 | import java.net.NetworkInterface;
38 | import java.net.SocketException;
39 | import java.util.Enumeration;
40 | import java.util.Locale;
41 | import java.util.UUID;
42 |
43 | /**
44 | * https://github.com/nisrulz/easydeviceinfo
45 | */
46 | public class DeviceUtils {
47 |
48 |
49 | public static String getAndroidID(Context ctx) {
50 | return Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.ANDROID_ID);
51 | }
52 |
53 | public static String getIMEI(Context ctx) {
54 | return ((TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
55 | }
56 |
57 | public static String getIMSI(Context ctx) {
58 | TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
59 | return tm.getSubscriberId() != null ? tm.getSubscriberId() : null;
60 | }
61 |
62 | @SuppressWarnings("MissingPermission")
63 | public static String getWifiMacAddr(Context ctx) {
64 | String macAddr = "";
65 | try {
66 | WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
67 | macAddr = wifi.getConnectionInfo().getMacAddress();
68 | if (macAddr == null) {
69 | macAddr = "";
70 | }
71 | } catch (Exception e) {
72 | e.printStackTrace();
73 | }
74 | return macAddr;
75 | }
76 |
77 | public static String getIP(Context ctx) {
78 | WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
79 | return wifiManager.isWifiEnabled() ? getWifiIP(wifiManager) : getGPRSIP();
80 | }
81 |
82 | public static String getWifiIP(WifiManager wifiManager) {
83 | WifiInfo wifiInfo = wifiManager.getConnectionInfo();
84 | String ip = intToIp(wifiInfo.getIpAddress());
85 | return ip != null ? ip : "";
86 | }
87 |
88 | public static String getGPRSIP() {
89 | String ip = null;
90 | try {
91 | for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
92 | for (Enumeration enumIpAddr = en.nextElement().getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
93 | InetAddress inetAddress = enumIpAddr.nextElement();
94 | if (!inetAddress.isLoopbackAddress()) {
95 | ip = inetAddress.getHostAddress();
96 | }
97 | }
98 | }
99 | } catch (SocketException e) {
100 | e.printStackTrace();
101 | ip = null;
102 | }
103 | return ip;
104 | }
105 |
106 | private static String intToIp(int i) {
107 | return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
108 | }
109 |
110 |
111 | public static String getSerial() {
112 | return Build.SERIAL;
113 | }
114 |
115 | public static String getSIMSerial(Context ctx) {
116 | TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
117 | return tm.getSimSerialNumber();
118 | }
119 |
120 | public static String getMNC(Context ctx) {
121 | String providersName = "";
122 | TelephonyManager telephonyManager = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
123 | if (telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY) {
124 | providersName = telephonyManager.getSimOperator();
125 | providersName = providersName == null ? "" : providersName;
126 | }
127 | return providersName;
128 | }
129 |
130 | public static String getCarrier(Context ctx) {
131 | TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
132 | return tm.getNetworkOperatorName().toLowerCase(Locale.getDefault());
133 | }
134 |
135 |
136 | public static String getModel() {
137 | return Build.MODEL;
138 | }
139 |
140 | public static String getBuildBrand() {
141 | return Build.BRAND;
142 | }
143 |
144 | public static String getBuildHost() {
145 | return Build.HOST;
146 | }
147 |
148 | public static String getBuildTags() {
149 | return Build.TAGS;
150 | }
151 |
152 | public static long getBuildTime() {
153 | return Build.TIME;
154 | }
155 |
156 | public static String getBuildUser() {
157 | return Build.USER;
158 | }
159 |
160 | public static String getBuildVersionRelease() {
161 | return Build.VERSION.RELEASE;
162 | }
163 |
164 | public static String getBuildVersionCodename() {
165 | return Build.VERSION.CODENAME;
166 | }
167 |
168 | public static String getBuildVersionIncremental() {
169 | return Build.VERSION.INCREMENTAL;
170 | }
171 |
172 | public static int getBuildVersionSDK() {
173 | return Build.VERSION.SDK_INT;
174 | }
175 |
176 | public static String getBuildID() {
177 | return Build.ID;
178 | }
179 |
180 | public static String[] getSupportedABIS() {
181 | String[] result = new String[]{"-"};
182 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
183 | result = Build.SUPPORTED_ABIS;
184 | }
185 | if (result == null || result.length == 0) {
186 | result = new String[]{"-"};
187 | }
188 | return result;
189 | }
190 |
191 | public static String getManufacturer() {
192 | return Build.MANUFACTURER;
193 | }
194 |
195 |
196 | public static String getBootloader() {
197 | return Build.BOOTLOADER;
198 | }
199 |
200 |
201 | public static String getScreenDisplayID(Context ctx) {
202 | WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
203 | return String.valueOf(wm.getDefaultDisplay().getDisplayId());
204 | }
205 |
206 | public static String getDisplayVersion() {
207 | return Build.DISPLAY;
208 | }
209 |
210 |
211 | public static String getLanguage() {
212 | return Locale.getDefault().getLanguage();
213 | }
214 |
215 | public static String getCountry(Context ctx) {
216 | TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
217 | Locale locale = Locale.getDefault();
218 | return tm.getSimState() == TelephonyManager.SIM_STATE_READY ? tm.getSimCountryIso().toLowerCase(Locale.getDefault()) : locale.getCountry().toLowerCase(locale);
219 | }
220 |
221 | public static String getOSVersion() {
222 | return Build.VERSION.RELEASE;
223 | }
224 |
225 | //
226 | public static String getGSFID(Context context) {
227 | String result;
228 | final Uri URI = Uri.parse("content://com.google.android.gsf.gservices");
229 | final String ID_KEY = "android_id";
230 | String[] params = {ID_KEY};
231 | Cursor c = context.getContentResolver().query(URI, null, null, params, null);
232 | if (c == null || !c.moveToFirst() || c.getColumnCount() < 2) {
233 | return null;
234 | } else {
235 | result = Long.toHexString(Long.parseLong(c.getString(1)));
236 | }
237 | c.close();
238 | return result;
239 | }
240 |
241 | //
242 | @SuppressWarnings("MissingPermission")
243 | public static String getBluetoothMAC(Context context) {
244 | String result = null;
245 | try {
246 | if (context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH)
247 | == PackageManager.PERMISSION_GRANTED) {
248 | BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
249 | result = bta.getAddress();
250 | }
251 | } catch (Exception e) {
252 | e.printStackTrace();
253 | }
254 | return result;
255 | }
256 |
257 | public static String getPsuedoUniqueID() {
258 | String devIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10);
259 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
260 | devIDShort += (Build.SUPPORTED_ABIS[0].length() % 10);
261 | } else {
262 | devIDShort += (Build.CPU_ABI.length() % 10);
263 | }
264 | devIDShort += (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
265 | String serial;
266 | try {
267 | serial = Build.class.getField("SERIAL").get(null).toString();
268 | return new UUID(devIDShort.hashCode(), serial.hashCode()).toString();
269 | } catch (Exception e) {
270 | serial = "ESYDV000";
271 | }
272 | return new UUID(devIDShort.hashCode(), serial.hashCode()).toString();
273 | }
274 |
275 | public static String getFingerprint() {
276 | return Build.FINGERPRINT;
277 | }
278 |
279 | public static String getHardware() {
280 | return Build.HARDWARE;
281 | }
282 |
283 | public static String getProduct() {
284 | return Build.PRODUCT;
285 | }
286 |
287 | public static String getDevice() {
288 | return Build.DEVICE;
289 | }
290 |
291 | public static String getBoard() {
292 | return Build.BOARD;
293 | }
294 |
295 | public static String getRadioVersion() {
296 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ? Build.getRadioVersion() : "";
297 | }
298 |
299 | public static String getUA(Context ctx) {
300 | final String system_ua = System.getProperty("http.agent");
301 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
302 | return new WebView(ctx).getSettings().getDefaultUserAgent(ctx) + "__" + system_ua;
303 | } else {
304 | return new WebView(ctx).getSettings().getUserAgentString() + "__" + system_ua;
305 | }
306 | }
307 |
308 | public static String getDensity(Context ctx) {
309 | String densityStr = null;
310 | final int density = ctx.getResources().getDisplayMetrics().densityDpi;
311 | switch (density) {
312 | case DisplayMetrics.DENSITY_LOW:
313 | densityStr = "LDPI";
314 | break;
315 | case DisplayMetrics.DENSITY_MEDIUM:
316 | densityStr = "MDPI";
317 | break;
318 | case DisplayMetrics.DENSITY_TV:
319 | densityStr = "TVDPI";
320 | break;
321 | case DisplayMetrics.DENSITY_HIGH:
322 | densityStr = "HDPI";
323 | break;
324 | case DisplayMetrics.DENSITY_XHIGH:
325 | densityStr = "XHDPI";
326 | break;
327 | case DisplayMetrics.DENSITY_400:
328 | densityStr = "XMHDPI";
329 | break;
330 | case DisplayMetrics.DENSITY_XXHIGH:
331 | densityStr = "XXHDPI";
332 | break;
333 | case DisplayMetrics.DENSITY_XXXHIGH:
334 | densityStr = "XXXHDPI";
335 | break;
336 | }
337 | return densityStr;
338 | }
339 |
340 | //
341 | @SuppressWarnings("MissingPermission")
342 | public static String[] getGoogleAccounts(Context ctx) {
343 | if (ctx.checkCallingOrSelfPermission(Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) {
344 | Account[] accounts = AccountManager.get(ctx).getAccountsByType("com.google");
345 | String[] result = new String[accounts.length];
346 | for (int i = 0; i < accounts.length; i++) {
347 | result[i] = accounts[i].name;
348 | }
349 | return result;
350 | }
351 | return null;
352 | }
353 |
354 |
355 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/FileUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import android.app.DownloadManager;
20 | import android.content.Context;
21 | import android.content.Intent;
22 | import android.net.Uri;
23 | import android.os.Environment;
24 | import android.text.TextUtils;
25 | import android.text.format.Formatter;
26 |
27 | import java.io.BufferedReader;
28 | import java.io.BufferedWriter;
29 | import java.io.Closeable;
30 | import java.io.File;
31 | import java.io.FileInputStream;
32 | import java.io.FileNotFoundException;
33 | import java.io.FileOutputStream;
34 | import java.io.FileReader;
35 | import java.io.FileWriter;
36 | import java.io.IOException;
37 | import java.io.InputStream;
38 | import java.io.InputStreamReader;
39 | import java.io.OutputStream;
40 | import java.nio.channels.FileChannel;
41 | import java.util.ArrayList;
42 | import java.util.zip.GZIPInputStream;
43 | import java.util.zip.GZIPOutputStream;
44 |
45 | /**
46 | * Create by h4de5ing 2016/5/7 007
47 | */
48 | public class FileUtils {
49 |
50 | public static void closeIO(Closeable... closeables) {
51 | if (null == closeables || closeables.length <= 0) {
52 | return;
53 | }
54 | for (Closeable cb : closeables) {
55 | try {
56 | if (null == cb) {
57 | continue;
58 | }
59 | cb.close();
60 | } catch (IOException e) {
61 | e.printStackTrace();
62 | }
63 | }
64 | }
65 |
66 | public static boolean deleteFile(String filename) {
67 | return new File(filename).delete();
68 | }
69 |
70 | public static void deleteFileByDirectory(File directory) {
71 | if (directory.exists() && directory.isDirectory()) {
72 | for (File file : directory.listFiles()) {
73 | file.delete();
74 | }
75 | }
76 | }
77 |
78 | public static boolean isFileExist(String filePath) {
79 | return new File(filePath).exists();
80 | }
81 |
82 | public static boolean writeFile(String filename, String content, boolean append) {
83 | boolean isSuccess = false;
84 | BufferedWriter bufferedWriter = null;
85 | try {
86 | bufferedWriter = new BufferedWriter(new FileWriter(filename, append));
87 | bufferedWriter.write(content);
88 | isSuccess = true;
89 | } catch (IOException e) {
90 | e.printStackTrace();
91 | } finally {
92 | closeIO(bufferedWriter);
93 | }
94 | return isSuccess;
95 | }
96 |
97 | public static String readFile(String filename) {
98 | File file = new File(filename);
99 | BufferedReader bufferedReader = null;
100 | String str = null;
101 | try {
102 | if (file.exists()) {
103 | bufferedReader = new BufferedReader(new FileReader(filename));
104 | str = bufferedReader.readLine();
105 | }
106 | } catch (IOException e) {
107 | e.printStackTrace();
108 | } finally {
109 | closeIO(bufferedReader);
110 | }
111 | return str;
112 | }
113 |
114 | public static StringBuilder readFile(File file, String charsetName) {
115 | StringBuilder fileContent = new StringBuilder("");
116 | if (file == null || !file.isFile()) {
117 | return null;
118 | }
119 | BufferedReader reader = null;
120 | try {
121 | InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
122 | reader = new BufferedReader(is);
123 | String line = null;
124 | while ((line = reader.readLine()) != null) {
125 | if (!fileContent.toString().equals("")) {
126 | fileContent.append("\r\n");
127 | }
128 | fileContent.append(line);
129 | }
130 | return fileContent;
131 | } catch (IOException e) {
132 | throw new RuntimeException("IOException occurred. ", e);
133 | } finally {
134 | closeIO(reader);
135 | }
136 | }
137 |
138 | public static void copyFile(InputStream in, OutputStream out) {
139 | try {
140 | byte[] b = new byte[2 * 1024 * 1024]; //2M memory
141 | int len = -1;
142 | while ((len = in.read(b)) > 0) {
143 | out.write(b, 0, len);
144 | out.flush();
145 | }
146 | } catch (IOException e) {
147 | e.printStackTrace();
148 | } finally {
149 | closeIO(in, out);
150 | }
151 | }
152 |
153 | public static void copyFileFast(File in, File out) {
154 | FileChannel filein = null;
155 | FileChannel fileout = null;
156 | try {
157 | filein = new FileInputStream(in).getChannel();
158 | fileout = new FileOutputStream(out).getChannel();
159 | filein.transferTo(0, filein.size(), fileout);
160 | } catch (FileNotFoundException e) {
161 | e.printStackTrace();
162 | } catch (IOException e) {
163 | e.printStackTrace();
164 | } finally {
165 | closeIO(filein, fileout);
166 | }
167 | }
168 |
169 | public static void shareFile(Context context, String title, String filePath) {
170 | Intent intent = new Intent(Intent.ACTION_SEND);
171 | Uri uri = Uri.parse("file://" + filePath);
172 | intent.setType("*/*");
173 | intent.putExtra(Intent.EXTRA_STREAM, uri);
174 | context.startActivity(Intent.createChooser(intent, title));
175 | }
176 |
177 | public static void zip(InputStream is, OutputStream os) {
178 | GZIPOutputStream gzip = null;
179 | try {
180 | gzip = new GZIPOutputStream(os);
181 | byte[] buf = new byte[1024];
182 | int len;
183 | while ((len = is.read(buf)) != -1) {
184 | gzip.write(buf, 0, len);
185 | gzip.flush();
186 | }
187 | } catch (IOException e) {
188 | e.printStackTrace();
189 | } finally {
190 | closeIO(is, gzip);
191 | }
192 | }
193 |
194 | public static void unzip(InputStream is, OutputStream os) {
195 | GZIPInputStream gzip = null;
196 | try {
197 | gzip = new GZIPInputStream(is);
198 | byte[] buf = new byte[1024];
199 | int len;
200 | while ((len = gzip.read(buf)) != -1) {
201 | os.write(buf, 0, len);
202 | }
203 | } catch (IOException e) {
204 | e.printStackTrace();
205 | } finally {
206 | closeIO(gzip, os);
207 | }
208 | }
209 |
210 | public static String formatFileSize(Context context, long size) {
211 | return Formatter.formatFileSize(context, size);
212 | }
213 |
214 | public static void Stream2File(InputStream is, File file) {
215 | byte[] b = new byte[1024];
216 | int len;
217 | FileOutputStream os = null;
218 | try {
219 | os = new FileOutputStream(file);
220 | while ((len = is.read(b)) != -1) {
221 | os.write(b, 0, len);
222 | os.flush();
223 | }
224 | } catch (IOException e) {
225 | e.printStackTrace();
226 | } finally {
227 | closeIO(is, os);
228 | }
229 | }
230 |
231 | public static boolean createFolder(String filePath) {
232 | return createFolder(filePath, false);
233 | }
234 |
235 | public static boolean createFolder(String filePath, boolean recreate) {
236 | String folderName = getFolderName(filePath);
237 | if (folderName == null || folderName.length() == 0 || folderName.trim().length() == 0) {
238 | return false;
239 | }
240 | File folder = new File(folderName);
241 | if (folder.exists()) {
242 | if (recreate) {
243 | deleteFile(folderName);
244 | return folder.mkdirs();
245 | } else {
246 | return true;
247 | }
248 | } else {
249 | return folder.mkdirs();
250 | }
251 | }
252 |
253 | public static String getFileName(String filePath) {
254 | if (StringUtils.isEmpty(filePath)) {
255 | return filePath;
256 | }
257 |
258 | int filePosi = filePath.lastIndexOf(File.separator);
259 | return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
260 | }
261 |
262 | public static long getFileSize(String filepath) {
263 | if (TextUtils.isEmpty(filepath)) {
264 | return -1;
265 | }
266 | File file = new File(filepath);
267 | return (file.exists() && file.isFile() ? file.length() : -1);
268 | }
269 |
270 | public static boolean rename(String filepath, String newName) {
271 | File file = new File(filepath);
272 | return file.exists() && file.renameTo(new File(newName));
273 | }
274 |
275 | public static String getFolderName(String filePath) {
276 | if (filePath == null || filePath.length() == 0 || filePath.trim().length() == 0) {
277 | return filePath;
278 | }
279 | int filePos = filePath.lastIndexOf(File.separator);
280 | return (filePos == -1) ? "" : filePath.substring(0, filePos);
281 | }
282 |
283 | public static ArrayList getFilesArray(String path) {
284 | File file = new File(path);
285 | File files[] = file.listFiles();
286 | ArrayList listFile = new ArrayList();
287 | if (files != null) {
288 | for (int i = 0; i < files.length; i++) {
289 | if (files[i].isFile()) {
290 | listFile.add(files[i]);
291 | }
292 | if (files[i].isDirectory()) {
293 | listFile.addAll(getFilesArray(files[i].toString()));
294 | }
295 | }
296 | }
297 | return listFile;
298 | }
299 |
300 | public static boolean deleteFiles(String folder) {
301 | if (folder == null || folder.length() == 0 || folder.trim().length() == 0) {
302 | return true;
303 | }
304 | File file = new File(folder);
305 | if (!file.exists()) {
306 | return true;
307 | }
308 | if (file.isFile()) {
309 | return file.delete();
310 | }
311 | if (!file.isDirectory()) {
312 | return false;
313 | }
314 | for (File f : file.listFiles()) {
315 | if (f.isFile()) {
316 | f.delete();
317 | } else if (f.isDirectory()) {
318 | deleteFile(f.getAbsolutePath());
319 | }
320 | }
321 | return file.delete();
322 | }
323 |
324 | public static void openImage(Context mContext, String imagePath) {
325 | Intent intent = new Intent("android.intent.action.VIEW");
326 | intent.addCategory("android.intent.category.DEFAULT");
327 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
328 | Uri uri = Uri.fromFile(new File(imagePath));
329 | intent.setDataAndType(uri, "image/*");
330 | mContext.startActivity(intent);
331 | }
332 |
333 | public static void openVideo(Context mContext, String videoPath) {
334 | Intent intent = new Intent("android.intent.action.VIEW");
335 | intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
336 | intent.putExtra("oneshot", 0);
337 | intent.putExtra("configchange", 0);
338 | Uri uri = Uri.fromFile(new File(videoPath));
339 | intent.setDataAndType(uri, "video/*");
340 | mContext.startActivity(intent);
341 | }
342 |
343 | public static void openURL(Context mContext, String url) {
344 | Uri uri = Uri.parse(url);
345 | Intent intent = new Intent(Intent.ACTION_VIEW, uri);
346 | mContext.startActivity(intent);
347 | }
348 |
349 | public static void downloadFile(Context context, String fileurl) {
350 | DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileurl));
351 | request.setDestinationInExternalPublicDir("/Download/", fileurl.substring(fileurl.lastIndexOf("/") + 1));
352 | DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
353 | downloadManager.enqueue(request);
354 | }
355 |
356 |
357 | public static boolean isSDCardAvailable() {
358 | return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
359 | }
360 |
361 | public static String getAppExternalPath(Context context) {
362 | /* StringBuilder sb = new StringBuilder();
363 | sb.append(Environment.getExternalStorageDirectory().getAbsolutePath());
364 | sb.append(File.separator);
365 | sb.append("Android/data/");
366 | sb.append(packageName);
367 | return sb.toString();*/
368 | return context.getObbDir().getAbsolutePath();
369 | }
370 |
371 | @Deprecated
372 | public static String getExtraPath(String folder) {
373 | String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + folder;
374 | File file = new File(storagePath);
375 | if (!file.exists()) {
376 | file.mkdir();
377 | }
378 | return storagePath;
379 | }
380 | }
381 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/JsonUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import com.google.gson.Gson;
20 |
21 | import org.json.JSONArray;
22 | import org.json.JSONException;
23 | import org.json.JSONObject;
24 | import org.json.JSONTokener;
25 |
26 | import java.lang.reflect.Array;
27 | import java.util.Collection;
28 | import java.util.Map;
29 |
30 | /**
31 | * Create by h4de5ing 2016/5/7 007
32 | */
33 | public class JsonUtils {
34 | public static String toJson(Object obj) {
35 | Gson gson = new Gson();
36 | return gson.toJson(obj);
37 | }
38 |
39 | public static T fromJson(String str, Class type) {
40 | Gson gson = new Gson();
41 | return gson.fromJson(str, type);
42 | }
43 |
44 | public static JSONObject map2Json(Map, ?> data) {
45 | JSONObject object = new JSONObject();
46 |
47 | for (Map.Entry, ?> entry : data.entrySet()) {
48 | String key = (String) entry.getKey();
49 | if (key == null) {
50 | throw new NullPointerException("key == null");
51 | }
52 | try {
53 | object.put(key, wrap(entry.getValue()));
54 | } catch (JSONException e) {
55 | e.printStackTrace();
56 | }
57 | }
58 |
59 | return object;
60 | }
61 |
62 | public static JSONArray collection2Json(Collection> data) {
63 | JSONArray jsonArray = new JSONArray();
64 | if (data != null) {
65 | for (Object aData : data) {
66 | jsonArray.put(wrap(aData));
67 | }
68 | }
69 | return jsonArray;
70 | }
71 |
72 | public static JSONArray object2Json(Object data) throws JSONException {
73 | if (!data.getClass().isArray()) {
74 | throw new JSONException("Not a primitive data: " + data.getClass());
75 | }
76 | final int length = Array.getLength(data);
77 | JSONArray jsonArray = new JSONArray();
78 | for (int i = 0; i < length; ++i) {
79 | jsonArray.put(wrap(Array.get(data, i)));
80 | }
81 |
82 | return jsonArray;
83 | }
84 |
85 | private static Object wrap(Object o) {
86 | if (o == null) {
87 | return null;
88 | }
89 | if (o instanceof JSONArray || o instanceof JSONObject) {
90 | return o;
91 | }
92 | try {
93 | if (o instanceof Collection) {
94 | return collection2Json((Collection>) o);
95 | } else if (o.getClass().isArray()) {
96 | return object2Json(o);
97 | }
98 | if (o instanceof Map) {
99 | return map2Json((Map, ?>) o);
100 | }
101 |
102 | if (o instanceof Boolean || o instanceof Byte || o instanceof Character || o instanceof Double || o instanceof Float || o instanceof Integer || o instanceof Long
103 | || o instanceof Short || o instanceof String) {
104 | return o;
105 | }
106 | if (o.getClass().getPackage().getName().startsWith("java.")) {
107 | return o.toString();
108 | }
109 | } catch (Exception ignored) {
110 | }
111 | return null;
112 | }
113 |
114 | public static JSONObject string2JSONObject(String json) {
115 | JSONObject jsonObject = null;
116 | try {
117 | JSONTokener jsonParser = new JSONTokener(json);
118 | jsonObject = (JSONObject) jsonParser.nextValue();
119 | } catch (Exception e) {
120 | e.printStackTrace();
121 | }
122 | return jsonObject;
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/L.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import android.text.TextUtils;
20 | import android.util.Log;
21 |
22 | import org.json.JSONArray;
23 | import org.json.JSONException;
24 | import org.json.JSONObject;
25 |
26 | import java.io.StringReader;
27 | import java.io.StringWriter;
28 |
29 | import javax.xml.transform.OutputKeys;
30 | import javax.xml.transform.Source;
31 | import javax.xml.transform.Transformer;
32 | import javax.xml.transform.TransformerFactory;
33 | import javax.xml.transform.stream.StreamResult;
34 | import javax.xml.transform.stream.StreamSource;
35 |
36 |
37 | /**
38 | * Created by Gh0st on 2016/6/7 007.
39 | * https://github.com/ZhaoKaiQiang/KLog
40 | */
41 | public class L {
42 | private static String TAG = "ghost";
43 | private static boolean LOG_DEBUG = true;
44 | private static final String LINE_SEPARATOR = System.getProperty("line.separator");
45 | private static final int VERBOSE = 2;
46 | private static final int DEBUG = 3;
47 | private static final int INFO = 4;
48 | private static final int WARN = 5;
49 | private static final int ERROR = 6;
50 | private static final int ASSERT = 7;
51 | private static final int JSON = 8;
52 | private static final int XML = 9;
53 |
54 | private static final int JSON_INDENT = 4;
55 |
56 | public static void init(boolean isDebug, String tag) {
57 | TAG = tag;
58 | LOG_DEBUG = isDebug;
59 | }
60 |
61 | public static void v(String msg) {
62 | log(VERBOSE, null, msg);
63 | }
64 |
65 | public static void v(String tag, String msg) {
66 | log(VERBOSE, tag, msg);
67 | }
68 |
69 | public static void d(String msg) {
70 | log(DEBUG, null, msg);
71 | }
72 |
73 | public static void d(String tag, String msg) {
74 | log(DEBUG, tag, msg);
75 | }
76 |
77 | public static void i(Object... msg) {
78 | StringBuilder sb = new StringBuilder();
79 | for (Object obj : msg) {
80 | sb.append(obj);
81 | sb.append(",");
82 | }
83 | log(INFO, null, String.valueOf(sb));
84 | }
85 |
86 | public static void w(String msg) {
87 | log(WARN, null, msg);
88 | }
89 |
90 | public static void w(String tag, String msg) {
91 | log(WARN, tag, msg);
92 | }
93 |
94 | public static void e(String msg) {
95 | log(ERROR, null, msg);
96 | }
97 |
98 | public static void e(String tag, String msg, Throwable tr) {
99 | log(ERROR, tag, msg + '\n' + Log.getStackTraceString(tr));
100 | }
101 |
102 | public static void a(String msg) {
103 | log(ASSERT, null, msg);
104 | }
105 |
106 | public static void a(String tag, String msg) {
107 | log(ASSERT, tag, msg);
108 | }
109 |
110 | public static void json(String json) {
111 | log(JSON, null, json);
112 | }
113 |
114 | public static void json(String tag, String json) {
115 | log(JSON, tag, json);
116 | }
117 |
118 | public static void xml(String xml) {
119 | log(XML, null, xml);
120 | }
121 |
122 | public static void xml(String tag, String xml) {
123 | log(XML, tag, xml);
124 | }
125 |
126 | private static void log(int logType, String tagStr, Object objects) {
127 | String[] contents = wrapperContent(tagStr, objects);
128 | String tag = contents[0];
129 | String msg = contents[1];
130 | String headString = contents[2];
131 | if (LOG_DEBUG) {
132 | switch (logType) {
133 | case VERBOSE:
134 | case DEBUG:
135 | case INFO:
136 | case WARN:
137 | case ERROR:
138 | case ASSERT:
139 | printDefault(logType, tag, headString + msg);
140 | break;
141 | case JSON:
142 | printJson(tag, msg, headString);
143 | break;
144 | case XML:
145 | printXml(tag, msg, headString);
146 | break;
147 | default:
148 | break;
149 | }
150 | }
151 | }
152 |
153 | private static void printDefault(int type, String tag, String msg) {
154 | if (TextUtils.isEmpty(tag)) {
155 | tag = TAG;
156 | }
157 | printLine(tag, true);
158 | int maxLength = 4000;
159 | int countOfSub = msg.length();
160 | if (countOfSub > maxLength) {
161 | for (int i = 0; i < countOfSub; i += maxLength) {
162 | if (i + maxLength < countOfSub) {
163 | printSub(type, tag, msg.substring(i, i + maxLength));
164 | } else {
165 | printSub(type, tag, msg.substring(i, countOfSub));
166 | }
167 | }
168 | } else {
169 | printSub(type, tag, msg);
170 | }
171 | printLine(tag, false);
172 | }
173 |
174 | private static void printSub(int type, String tag, String msg) {
175 | switch (type) {
176 | case VERBOSE:
177 | Log.v(tag, msg);
178 | break;
179 | case DEBUG:
180 | Log.d(tag, msg);
181 | break;
182 | case INFO:
183 | Log.i(tag, msg);
184 | break;
185 | case WARN:
186 | Log.w(tag, msg);
187 | break;
188 | case ERROR:
189 | Log.e(tag, msg);
190 | break;
191 | case ASSERT:
192 | Log.wtf(tag, msg);
193 | break;
194 | }
195 | }
196 |
197 | private static void printJson(String tag, String json, String headString) {
198 | if (TextUtils.isEmpty(json)) {
199 | d("Empty/Null json content");
200 | return;
201 | }
202 | if (TextUtils.isEmpty(tag)) {
203 | tag = TAG;
204 | }
205 | String message;
206 |
207 | try {
208 | if (json.startsWith("{")) {
209 | JSONObject jsonObject = new JSONObject(json);
210 | message = jsonObject.toString(JSON_INDENT);
211 | } else if (json.startsWith("[")) {
212 | JSONArray jsonArray = new JSONArray(json);
213 | message = jsonArray.toString(JSON_INDENT);
214 | } else {
215 | message = json;
216 | }
217 | } catch (JSONException e) {
218 | message = json;
219 | }
220 |
221 | printLine(tag, true);
222 | message = headString + LINE_SEPARATOR + message;
223 | String[] lines = message.split(LINE_SEPARATOR);
224 | for (String line : lines) {
225 | printSub(DEBUG, tag, "|" + line);
226 | }
227 | printLine(tag, false);
228 | }
229 |
230 | private static void printXml(String tag, String xml, String headString) {
231 | if (TextUtils.isEmpty(tag)) {
232 | tag = TAG;
233 | }
234 | if (xml != null) {
235 | try {
236 | Source xmlInput = new StreamSource(new StringReader(xml));
237 | StreamResult xmlOutput = new StreamResult(new StringWriter());
238 | Transformer transformer = TransformerFactory.newInstance().newTransformer();
239 | transformer.setOutputProperty(OutputKeys.INDENT, "yes");
240 | transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
241 | transformer.transform(xmlInput, xmlOutput);
242 | xml = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
243 | } catch (Exception e) {
244 | e.printStackTrace();
245 | }
246 | xml = headString + "\n" + xml;
247 | } else {
248 | xml = headString + "Log with null object";
249 | }
250 |
251 | printLine(tag, true);
252 | String[] lines = xml.split(LINE_SEPARATOR);
253 | for (String line : lines) {
254 | if (!TextUtils.isEmpty(line)) {
255 | printSub(DEBUG, tag, "|" + line);
256 | }
257 | }
258 | printLine(tag, false);
259 | }
260 |
261 | private static String[] wrapperContent(String tag, Object... objects) {
262 | if (TextUtils.isEmpty(tag)) {
263 | tag = TAG;
264 | }
265 | StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
266 | StackTraceElement targetElement = stackTrace[5];
267 | String className = targetElement.getClassName();
268 | String[] classNameInfo = className.split("\\.");
269 | if (classNameInfo.length > 0) {
270 | className = classNameInfo[classNameInfo.length - 1] + ".java";
271 | }
272 | String methodName = targetElement.getMethodName();
273 | int lineNumber = targetElement.getLineNumber();
274 | if (lineNumber < 0) {
275 | lineNumber = 0;
276 | }
277 | String methodNameShort = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
278 | String msg = (objects == null) ? "Log with null object" : getObjectsString(objects);
279 | String headString = "[(" + className + ":" + lineNumber + ")#" + methodNameShort + " ] ";
280 | return new String[]{tag, msg, headString};
281 | }
282 |
283 | private static String getObjectsString(Object... objects) {
284 |
285 | if (objects.length > 1) {
286 | StringBuilder stringBuilder = new StringBuilder();
287 | stringBuilder.append("\n");
288 | for (int i = 0; i < objects.length; i++) {
289 | Object object = objects[i];
290 | if (object == null) {
291 | stringBuilder.append("param").append("[").append(i).append("]").append(" = ").append("null").append("\n");
292 | } else {
293 | stringBuilder.append("param").append("[").append(i).append("]").append(" = ").append(object.toString()).append("\n");
294 | }
295 | }
296 | return stringBuilder.toString();
297 | } else {
298 | Object object = objects[0];
299 | return object == null ? "null" : object.toString();
300 | }
301 | }
302 |
303 | private static void printLine(String tag, boolean isTop) {
304 | if (isTop) {
305 | Log.d(tag, "╔═══════════════════════════════════════════════════════════════════════════════════════");
306 | } else {
307 | Log.d(tag, "╚═══════════════════════════════════════════════════════════════════════════════════════");
308 | }
309 | }
310 |
311 | }
312 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/NetUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import android.app.Activity;
20 | import android.content.ComponentName;
21 | import android.content.Context;
22 | import android.content.Intent;
23 | import android.net.ConnectivityManager;
24 | import android.net.NetworkInfo;
25 | import android.net.wifi.ScanResult;
26 | import android.net.wifi.WifiInfo;
27 | import android.net.wifi.WifiManager;
28 | import android.telephony.TelephonyManager;
29 | import android.text.TextUtils;
30 |
31 | import java.lang.reflect.Field;
32 | import java.lang.reflect.Method;
33 | import java.util.List;
34 |
35 | /**
36 | * Blog : http://blog.csdn.net/u011240877
37 | */
38 | public class NetUtils {
39 |
40 | public static final String NETWORK_TYPE_WIFI = "wifi";
41 | public static final String NETWORK_TYPE_3G = "3g";
42 | public static final String NETWORK_TYPE_2G = "2g";
43 | public static final String NETWORK_TYPE_WAP = "wap";
44 | public static final String NETWORK_TYPE_UNKNOWN = "unknown";
45 | public static final String NETWORK_TYPE_DISCONNECT = "disconnect";
46 |
47 | public static int getNetworkType(Context context) {
48 | ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
49 | NetworkInfo networkInfo = connectivityManager == null ? null : connectivityManager.getActiveNetworkInfo();
50 | return networkInfo == null ? -1 : networkInfo.getType();
51 | }
52 |
53 | public static String getNetworkTypeName(Context context) {
54 | ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
55 | NetworkInfo networkInfo;
56 | String type = NETWORK_TYPE_DISCONNECT;
57 | if (manager == null || (networkInfo = manager.getActiveNetworkInfo()) == null) {
58 | return type;
59 | }
60 |
61 | if (networkInfo.isConnected()) {
62 | String typeName = networkInfo.getTypeName();
63 | if ("WIFI".equalsIgnoreCase(typeName)) {
64 | type = NETWORK_TYPE_WIFI;
65 | } else if ("MOBILE".equalsIgnoreCase(typeName)) {
66 | //String proxyHost = android.net.Proxy.getDefaultHost();//deprecated
67 | String proxyHost = System.getProperty("http.proxyHost");
68 | type = TextUtils.isEmpty(proxyHost) ? (isFastMobileNetwork(context) ? NETWORK_TYPE_3G : NETWORK_TYPE_2G) : NETWORK_TYPE_WAP;
69 | } else {
70 | type = NETWORK_TYPE_UNKNOWN;
71 | }
72 | }
73 | return type;
74 | }
75 |
76 | public static boolean isConnected(Context context) {
77 | ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
78 | NetworkInfo info = cm.getActiveNetworkInfo();
79 | if (info != null && info.isConnected()) {
80 | if (info.getState() == NetworkInfo.State.CONNECTED) {
81 | return true;
82 | }
83 | }
84 | return false;
85 | }
86 |
87 | public static boolean isNetworkAvailable(Context context) {
88 | if (context == null) {
89 | return false;
90 | }
91 | try {
92 | ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
93 | if (connectivity != null) {
94 | NetworkInfo info = connectivity.getActiveNetworkInfo();
95 | return info.isAvailable();
96 | }
97 | } catch (Exception e) {
98 | return false;
99 | }
100 | return false;
101 | }
102 |
103 | public static boolean isWiFi(Context cxt) {
104 | ConnectivityManager cm = (ConnectivityManager) cxt.getSystemService(Context.CONNECTIVITY_SERVICE);
105 | // wifi的状态:ConnectivityManager.TYPE_WIFI
106 | // 3G的状态:ConnectivityManager.TYPE_MOBILE
107 | return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
108 | }
109 |
110 | //unchecked
111 | public static void openNetSetting(Activity act) {
112 | Intent intent = new Intent();
113 | ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
114 | intent.setComponent(cm);
115 | intent.setAction("android.intent.action.VIEW");
116 | act.startActivityForResult(intent, 0);
117 | }
118 |
119 |
120 | /**
121 | * Whether is fast mobile network
122 | */
123 |
124 | private static boolean isFastMobileNetwork(Context context) {
125 | TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
126 | if (telephonyManager == null) {
127 | return false;
128 | }
129 |
130 | switch (telephonyManager.getNetworkType()) {
131 | case TelephonyManager.NETWORK_TYPE_1xRTT:
132 | return false;
133 | case TelephonyManager.NETWORK_TYPE_CDMA:
134 | return false;
135 | case TelephonyManager.NETWORK_TYPE_EDGE:
136 | return false;
137 | case TelephonyManager.NETWORK_TYPE_EVDO_0:
138 | return true;
139 | case TelephonyManager.NETWORK_TYPE_EVDO_A:
140 | return true;
141 | case TelephonyManager.NETWORK_TYPE_GPRS:
142 | return false;
143 | case TelephonyManager.NETWORK_TYPE_HSDPA:
144 | return true;
145 | case TelephonyManager.NETWORK_TYPE_HSPA:
146 | return true;
147 | case TelephonyManager.NETWORK_TYPE_HSUPA:
148 | return true;
149 | case TelephonyManager.NETWORK_TYPE_UMTS:
150 | return true;
151 | case TelephonyManager.NETWORK_TYPE_EHRPD:
152 | return true;
153 | case TelephonyManager.NETWORK_TYPE_EVDO_B:
154 | return true;
155 | case TelephonyManager.NETWORK_TYPE_HSPAP:
156 | return true;
157 | case TelephonyManager.NETWORK_TYPE_IDEN:
158 | return false;
159 | case TelephonyManager.NETWORK_TYPE_LTE:
160 | return true;
161 | case TelephonyManager.NETWORK_TYPE_UNKNOWN:
162 | return false;
163 | default:
164 | return false;
165 | }
166 | }
167 |
168 | public static void setWifiEnabled(Context context, boolean enabled) {
169 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
170 | wifiManager.setWifiEnabled(enabled);
171 | }
172 |
173 | public static void setDataEnabled(Context context, boolean enabled) {
174 | ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
175 | Class> conMgrClass = null;
176 | Field iConMgrField = null;
177 | Object iConMgr = null;
178 | Class> iConMgrClass = null;
179 | Method setMobileDataEnabledMethod = null;
180 | try {
181 | conMgrClass = Class.forName(conMgr.getClass().getName());
182 | iConMgrField = conMgrClass.getDeclaredField("mService");
183 | iConMgrField.setAccessible(true);
184 | iConMgr = iConMgrField.get(conMgr);
185 | iConMgrClass = Class.forName(iConMgr.getClass().getName());
186 | setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
187 | setMobileDataEnabledMethod.setAccessible(true);
188 | setMobileDataEnabledMethod.invoke(iConMgr, enabled);
189 | } catch (Exception e) {
190 | e.printStackTrace();
191 | }
192 | }
193 |
194 | public static List getWifiScanResults(Context context) {
195 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
196 | return wifiManager.startScan() ? wifiManager.getScanResults() : null;
197 | }
198 |
199 | public static ScanResult getScanResultsByBSSID(Context context, String bssid) {
200 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
201 | ScanResult scanResult = null;
202 | boolean f = wifiManager.startScan();
203 | if (!f) {
204 | getScanResultsByBSSID(context, bssid);
205 | }
206 | List list = wifiManager.getScanResults();
207 | if (list != null) {
208 | for (int i = 0; i < list.size(); i++) {
209 | scanResult = list.get(i);
210 | if (scanResult.BSSID.equals(bssid)) {
211 | break;
212 | }
213 | }
214 | }
215 | return scanResult;
216 | }
217 |
218 | public static WifiInfo getWifiConnectionInfo(Context context) {
219 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
220 | return wifiManager.getConnectionInfo();
221 | }
222 | }
223 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/RadixUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.code19.library;
17 |
18 | /**
19 | * Created by Gh0st on 2017/7/26.
20 | */
21 |
22 | public class RadixUtils {
23 | //16->2
24 | public static String hexString2binaryString(String hexString) {
25 | if (hexString.length() % 2 != 0) {
26 | hexString = "0" + hexString;
27 | }
28 | String bString = "", tmp;
29 | for (int i = 0; i < hexString.length(); i++) {
30 | tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
31 | bString += tmp.substring(tmp.length() - 4);
32 | }
33 | return bString;
34 | }
35 |
36 | //2->16
37 | public static String binaryString2hexString(String bString) {
38 | if (bString.length() % 8 != 0) {
39 | String sbuwei = "00000000";
40 | bString = sbuwei.substring(0, sbuwei.length() - bString.length() % 8) + bString;
41 | }
42 | StringBuilder tmp = new StringBuilder();
43 | int iTmp = 0;
44 | for (int i = 0; i < bString.length(); i += 4) {
45 | iTmp = 0;
46 | for (int j = 0; j < 4; j++) {
47 | iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
48 | }
49 | tmp.append(Integer.toHexString(iTmp));
50 | }
51 | return tmp.toString();
52 | }
53 |
54 | public static String addBinary(String a, String b) {
55 | int carry = 0;
56 | int sum = 0;
57 | int opa = 0;
58 | int opb = 0;
59 | StringBuilder result = new StringBuilder();
60 | while (a.length() != b.length()) {
61 | if (a.length() > b.length()) {
62 | b = "0" + b;
63 | } else {
64 | a = "0" + a;
65 | }
66 | }
67 | for (int i = a.length() - 1; i >= 0; i--) {
68 | opa = a.charAt(i) - '0';
69 | opb = b.charAt(i) - '0';
70 | sum = opa + opb + carry;
71 | if (sum >= 2) {
72 | result.append((char) (sum - 2 + '0'));
73 | carry = 1;
74 | } else {
75 | result.append((char) (sum + '0'));
76 | carry = 0;
77 | }
78 | }
79 | if (carry == 1) {
80 | result.append("1");
81 | }
82 | return result.reverse().toString();
83 | }
84 |
85 | public static String hexArray2String(byte[] data) {
86 | StringBuilder sb = new StringBuilder(data.length * 2);
87 | final char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
88 | 'A', 'B', 'C', 'D', 'E', 'F'};
89 | for (int i = 0; i < data.length; i++) {
90 | int value = data[i] & 0xff;
91 | sb.append(HEX[value / 16]).append(HEX[value % 16]).append(" ");
92 | }
93 | return sb.toString();
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/SPUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import android.content.Context;
20 | import android.content.SharedPreferences;
21 | import android.content.SharedPreferences.Editor;
22 |
23 | /**
24 | * Create by h4de5ing 2016/5/7 007
25 | */
26 | public class SPUtils {
27 |
28 | public static void setSP(Context context, String key, Object object) {
29 | String type = object.getClass().getSimpleName();
30 | String packageName = context.getPackageName();
31 | SharedPreferences sp = context.getSharedPreferences(packageName, Context.MODE_PRIVATE);
32 | Editor edit = sp.edit();
33 | if ("String".equals(type)) {
34 | edit.putString(key, (String) object);
35 | } else if ("Integer".equals(type)) {
36 | edit.putInt(key, (Integer) object);
37 | } else if ("Boolean".equals(type)) {
38 | edit.putBoolean(key, (Boolean) object);
39 | } else if ("Float".equals(type)) {
40 | edit.putFloat(key, (Float) object);
41 | } else if ("Long".equals(type)) {
42 | edit.putLong(key, (Long) object);
43 | }
44 | edit.apply();
45 | }
46 |
47 | public static Object getSp(Context context, String key, Object defaultObject) {
48 | String type = defaultObject.getClass().getSimpleName();
49 | String packageName = context.getPackageName();
50 | SharedPreferences sp = context.getSharedPreferences(packageName, Context.MODE_PRIVATE);
51 | if ("String".equals(type)) {
52 | return sp.getString(key, (String) defaultObject);
53 | } else if ("Integer".equals(type)) {
54 | return sp.getInt(key, (Integer) defaultObject);
55 | } else if ("Boolean".equals(type)) {
56 | return sp.getBoolean(key, (Boolean) defaultObject);
57 | } else if ("Float".equals(type)) {
58 | return sp.getFloat(key, (Float) defaultObject);
59 | } else if ("Long".equals(type)) {
60 | return sp.getLong(key, (Long) defaultObject);
61 | }
62 | return null;
63 | }
64 |
65 | public static void cleanAllSP(Context context) {
66 | String packageName = context.getPackageName();
67 | SharedPreferences sp = context.getSharedPreferences(packageName, Context.MODE_PRIVATE);
68 | Editor editor = sp.edit();
69 | editor.clear();
70 | editor.apply();
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/StringUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import java.text.DecimalFormat;
20 |
21 | /**
22 | * Created by Gh0st on 2016/6/2 002.
23 | */
24 | public class StringUtils {
25 | /**
26 | * The pyvalue.
27 | */
28 | private static int[] pyvalue = new int[]{-20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032,
29 | -20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728,
30 | -19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261,
31 | -19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961,
32 | -18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490,
33 | -18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988,
34 | -17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692,
35 | -17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733,
36 | -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419,
37 | -16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959,
38 | -15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631,
39 | -15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180,
40 | -15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941,
41 | -14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857,
42 | -14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353,
43 | -14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094,
44 | -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831,
45 | -13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329,
46 | -13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860,
47 | -12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300,
48 | -12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358,
49 | -11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014,
50 | -10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309,
51 | -10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254};
52 |
53 | /**
54 | * The pystr.
55 | */
56 | public static String[] pystr = new String[]{"a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian",
57 | "biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", "chao", "che",
58 | "chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou", "cu", "cuan",
59 | "cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du",
60 | "duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang",
61 | "gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang",
62 | "hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian",
63 | "jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken",
64 | "keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng",
65 | "li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai",
66 | "man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai",
67 | "nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan",
68 | "nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu",
69 | "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re",
70 | "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha",
71 | "shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun",
72 | "shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao",
73 | "tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi",
74 | "xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi",
75 | "yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha",
76 | "zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui",
77 | "zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo"};
78 |
79 |
80 | public static int getChsAscii(String chs) {
81 | int asc = 0;
82 | try {
83 | byte[] bytes = chs.getBytes("gb2312");
84 | /*if (bytes == null || bytes.length > 2 || bytes.length <= 0) {
85 | throw new RuntimeException("illegal resource string");
86 | }*/
87 | if (bytes.length == 1) {
88 | asc = bytes[0];
89 | }
90 | if (bytes.length == 2) {
91 | int hightByte = 256 + bytes[0];
92 | int lowByte = 256 + bytes[1];
93 | asc = (256 * hightByte + lowByte) - 256 * 256;
94 | }
95 | } catch (Exception e) {
96 | System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);
97 | }
98 | return asc;
99 | }
100 |
101 | public static String convert(String str) {
102 | String result = null;
103 | int ascii = getChsAscii(str);
104 | if (ascii > 0 && ascii < 160) {
105 | result = String.valueOf((char) ascii);
106 | } else {
107 | for (int i = (pyvalue.length - 1); i >= 0; i--) {
108 | if (pyvalue[i] <= ascii) {
109 | result = pystr[i];
110 | break;
111 | }
112 | }
113 | }
114 | return result;
115 | }
116 |
117 | public String getSelling(String chs) {
118 | String key, value;
119 | StringBuilder buffer = new StringBuilder();
120 | for (int i = 0; i < chs.length(); i++) {
121 | key = chs.substring(i, i + 1);
122 | if (key.getBytes().length >= 2) {
123 | value = convert(key);
124 | if (value == null) {
125 | value = "unknown";
126 | }
127 | } else {
128 | value = key;
129 | }
130 | buffer.append(value);
131 | }
132 | return buffer.toString();
133 | }
134 |
135 | public static String parseEmpty(String str) {
136 | if (str == null || "null".equals(str.trim())) {
137 | str = "";
138 | }
139 | return str.trim();
140 | }
141 |
142 | public static boolean isEmpty(String str) {
143 | return str == null || str.trim().length() == 0;
144 | }
145 |
146 | public static int chineseLength(String str) {
147 | int valueLength = 0;
148 | String chinese = "[\u0391-\uFFE5]";
149 | if (!isEmpty(str)) {
150 | for (int i = 0; i < str.length(); i++) {
151 | String temp = str.substring(i, i + 1);
152 | if (temp.matches(chinese)) {
153 | valueLength += 2;
154 | }
155 | }
156 | }
157 | return valueLength;
158 | }
159 |
160 | public static int strLength(String str) {
161 | int valueLength = 0;
162 | String chinese = "[\u0391-\uFFE5]";
163 | if (!isEmpty(str)) {
164 | for (int i = 0; i < str.length(); i++) {
165 | String temp = str.substring(i, i + 1);
166 | if (temp.matches(chinese)) {
167 | valueLength += 2;
168 | } else {
169 | valueLength += 1;
170 | }
171 | }
172 | }
173 | return valueLength;
174 | }
175 |
176 | public static int subStringLength(String str, int maxL) {
177 | int currentIndex = 0;
178 | int valueLength = 0;
179 | String chinese = "[\u0391-\uFFE5]";
180 | for (int i = 0; i < str.length(); i++) {
181 | String temp = str.substring(i, i + 1);
182 | if (temp.matches(chinese)) {
183 | valueLength += 2;
184 | } else {
185 | valueLength += 1;
186 | }
187 | if (valueLength >= maxL) {
188 | currentIndex = i;
189 | break;
190 | }
191 | }
192 | return currentIndex;
193 | }
194 |
195 | public static Boolean isChinese(String str) {
196 | Boolean isChinese = true;
197 | String chinese = "[\u0391-\uFFE5]";
198 | if (!isEmpty(str)) {
199 | for (int i = 0; i < str.length(); i++) {
200 | String temp = str.substring(i, i + 1);
201 | isChinese = temp.matches(chinese);
202 | }
203 | }
204 | return isChinese;
205 | }
206 |
207 | public static Boolean isContainChinese(String str) {
208 | Boolean isChinese = false;
209 | String chinese = "[\u0391-\uFFE5]";
210 | if (!isEmpty(str)) {
211 | for (int i = 0; i < str.length(); i++) {
212 | String temp = str.substring(i, i + 1);
213 | isChinese = temp.matches(chinese);
214 | }
215 | }
216 | return isChinese;
217 | }
218 |
219 | public static String strFormat2(String str) {
220 | try {
221 | if (str.length() <= 1) {
222 | str = "0" + str;
223 | }
224 | } catch (Exception e) {
225 | e.printStackTrace();
226 | }
227 | return str;
228 | }
229 |
230 | public static int convert2Int(Object value, int defaultValue) {
231 | if (value == null || "".equals(value.toString().trim())) {
232 | return defaultValue;
233 | }
234 | try {
235 | return Double.valueOf(value.toString()).intValue();
236 | } catch (Exception e) {
237 | e.printStackTrace();
238 | return defaultValue;
239 | }
240 | }
241 |
242 | public static String decimalFormat(String s, String format) {
243 | DecimalFormat decimalFormat = new DecimalFormat(format);
244 | return decimalFormat.format(s);
245 | }
246 |
247 | }
248 |
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/SystemUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.code19.library;
17 |
18 | import android.annotation.SuppressLint;
19 | import android.app.Activity;
20 | import android.app.ActivityManager;
21 | import android.app.ActivityManager.MemoryInfo;
22 | import android.app.ActivityManager.RunningAppProcessInfo;
23 | import android.app.ActivityManager.RunningServiceInfo;
24 | import android.app.KeyguardManager;
25 | import android.content.ComponentName;
26 | import android.content.Context;
27 | import android.content.Intent;
28 | import android.content.pm.PackageManager;
29 | import android.content.pm.ResolveInfo;
30 | import android.location.LocationManager;
31 | import android.net.Uri;
32 | import android.os.Build;
33 | import android.os.Parcelable;
34 | import android.text.TextUtils;
35 | import android.view.inputmethod.InputMethodManager;
36 | import android.widget.EditText;
37 | import android.widget.Toast;
38 |
39 | import java.io.File;
40 | import java.security.MessageDigest;
41 | import java.util.List;
42 | import java.util.Locale;
43 | import java.util.Random;
44 |
45 | @SuppressLint("SimpleDateFormat")
46 | public final class SystemUtils {
47 |
48 | public static void sendSMS(Context cxt, String smsBody) {
49 | Uri smsToUri = Uri.parse("smsto:");
50 | Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
51 | intent.putExtra("sms_body", smsBody);
52 | cxt.startActivity(intent);
53 | }
54 |
55 | public static void forwardToDial(Activity activity, String phoneNumber) {
56 | if (activity != null && !TextUtils.isEmpty(phoneNumber)) {
57 | activity.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
58 | }
59 | }
60 |
61 | public static void sendMail(Context mContext, String mailID) {
62 | Uri uri = Uri.parse("mailto:" + mailID);
63 | mContext.startActivity(new Intent(Intent.ACTION_SENDTO, uri));
64 | }
65 |
66 | public static void openWeb(Context context, String url) {
67 | Uri uri = Uri.parse(url);
68 | context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
69 | }
70 |
71 | public static void openContacts(Activity context, int requestCode) {
72 | Uri uri = Uri.parse("content://contacts/people");
73 | context.startActivityForResult(new Intent(Intent.ACTION_PICK, uri), requestCode);
74 | }
75 |
76 | public static void openSettings(Activity context, String action) {
77 | Intent intent = new Intent();
78 | ComponentName comp = new ComponentName("com.android.settings", action);
79 | intent.setComponent(comp);
80 | intent.setAction("android.intent.action.VIEW");
81 | context.startActivityForResult(intent, 0);
82 | }
83 |
84 | public static void hideKeyBoard(Activity aty) {
85 | ((InputMethodManager) aty.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(aty.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
86 | }
87 | /* public static void openInputKeyBoard(Context mContext, EditText mEditText){
88 | InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
89 | imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
90 | imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
91 | }
92 |
93 | public static void closeInputKeyBoard(Context mContext, EditText mEditText){
94 | InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
95 | imm.hideSoftInputFromWindow(mEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
96 | }*/
97 |
98 | public static boolean isBackground(Context context) {
99 | ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
100 | List appProcesses = activityManager.getRunningAppProcesses();
101 | for (RunningAppProcessInfo appProcess : appProcesses) {
102 | if (appProcess.processName.equals(context.getPackageName())) {
103 | return appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
104 | }
105 | }
106 | return false;
107 | }
108 |
109 | public static boolean isSleeping(Context context) {
110 | KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
111 | return kgMgr.inKeyguardRestrictedInputMode();
112 | }
113 |
114 |
115 | public static void installApk(Context context, File apkfile) {
116 | Intent intent = new Intent();
117 | intent.setAction("android.intent.action.VIEW");
118 | intent.addCategory("android.intent.category.DEFAULT");
119 | intent.setType("application/vnd.android.package-archive");
120 | intent.setData(Uri.fromFile(apkfile));
121 | intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
122 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
123 | context.startActivity(intent);
124 | }
125 |
126 | private static final String suSearchPaths[] = {"/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/"};
127 |
128 | public static boolean isRooted() {
129 | File file;
130 | boolean flag1 = false;
131 | for (String suSearchPath : suSearchPaths) {
132 | file = new File(suSearchPath + "su");
133 | if (file.isFile() && file.exists()) {
134 | flag1 = true;
135 | break;
136 | }
137 | }
138 | return flag1;
139 | }
140 |
141 | public static boolean isRunningOnEmulator() {
142 | return Build.BRAND.contains("generic")
143 | || Build.DEVICE.contains("generic")
144 | || Build.PRODUCT.contains("sdk")
145 | || Build.HARDWARE.contains("goldfish")
146 | || Build.MANUFACTURER.contains("Genymotion")
147 | || Build.PRODUCT.contains("vbox86p")
148 | || Build.DEVICE.contains("vbox86p")
149 | || Build.HARDWARE.contains("vbox86");
150 | }
151 |
152 |
153 | public static void goHome(Context context) {
154 | Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
155 | mHomeIntent.addCategory(Intent.CATEGORY_HOME);
156 | mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
157 | context.startActivity(mHomeIntent);
158 | }
159 |
160 |
161 | public static String hexdigest(byte[] paramArrayOfByte) {
162 | final char[] hexDigits = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102};
163 | try {
164 | MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
165 | localMessageDigest.update(paramArrayOfByte);
166 | byte[] arrayOfByte = localMessageDigest.digest();
167 | char[] arrayOfChar = new char[32];
168 | for (int i = 0, j = 0; ; i++, j++) {
169 | if (i >= 16) {
170 | return new String(arrayOfChar);
171 | }
172 | int k = arrayOfByte[i];
173 | arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
174 | arrayOfChar[++j] = hexDigits[(k & 0xF)];
175 | }
176 | } catch (Exception e) {
177 | e.printStackTrace();
178 | }
179 | return "";
180 | }
181 |
182 |
183 | public static int getDeviceUsableMemory(Context cxt) {
184 | ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
185 | MemoryInfo mi = new MemoryInfo();
186 | am.getMemoryInfo(mi);
187 | return (int) (mi.availMem / (1024 * 1024));
188 | }
189 |
190 |
191 | public static int gc(Context cxt) {
192 | //long i = getDeviceUsableMemory(cxt);
193 | int count = 0;
194 | ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
195 | List serviceList = am.getRunningServices(100);
196 | if (serviceList != null)
197 | for (RunningServiceInfo service : serviceList) {
198 | if (service.pid == android.os.Process.myPid())
199 | continue;
200 | try {
201 | android.os.Process.killProcess(service.pid);
202 | count++;
203 | } catch (Exception e) {
204 | e.getStackTrace();
205 | //continue;
206 | }
207 | }
208 |
209 | List processList = am.getRunningAppProcesses();
210 | if (processList != null)
211 | for (RunningAppProcessInfo process : processList) {
212 | if (process.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
213 | String[] pkgList = process.pkgList;
214 | for (String pkgName : pkgList) {
215 | try {
216 | am.killBackgroundProcesses(pkgName);
217 | count++;
218 | } catch (Exception e) {
219 | e.getStackTrace();
220 | //continue;
221 | }
222 | }
223 | }
224 | }
225 | return count;
226 | }
227 |
228 | public static String getProcessName(Context appContext) {
229 | String currentProcessName = null;
230 | int pid = android.os.Process.myPid();
231 | ActivityManager manager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
232 | for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
233 | if (processInfo.pid == pid) {
234 | currentProcessName = processInfo.processName;
235 | break;
236 | }
237 | }
238 | return currentProcessName;
239 | }
240 |
241 | public static void createDeskShortCut(Context cxt, String shortCutName, int icon, Class> cls) {
242 | Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
243 | shortcutIntent.putExtra("duplicate", false);
244 | shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortCutName);
245 | Parcelable ico = Intent.ShortcutIconResource.fromContext(cxt.getApplicationContext(), icon);
246 | shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, ico);
247 | Intent intent = new Intent(cxt, cls);
248 | intent.setAction("android.intent.action.MAIN");
249 | intent.addCategory("android.intent.category.LAUNCHER");
250 | shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
251 | cxt.sendBroadcast(shortcutIntent);
252 | }
253 |
254 | public static void createShortcut(Context ctx, String shortCutName, int iconId, Intent presentIntent) {
255 | Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
256 | shortcutIntent.putExtra("duplicate", false);
257 | shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortCutName);
258 | shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(ctx, iconId));
259 | shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, presentIntent);
260 | ctx.sendBroadcast(shortcutIntent);
261 | }
262 |
263 | public static void shareText(Context ctx, String title, String text) {
264 | Intent intent = new Intent(Intent.ACTION_SEND);
265 | intent.setType("text/plain");
266 | //intent.putExtra(Intent.EXTRA_SUBJECT, title);
267 | intent.putExtra(Intent.EXTRA_TEXT, text);
268 | ctx.startActivity(Intent.createChooser(intent, title));
269 | /* List ris = getShareTargets(ctx);
270 | if (ris != null && ris.size() > 0) {
271 | ctx.startActivity(Intent.createChooser(intent, title));
272 | }*/
273 | }
274 |
275 | public static void shareFile(Context ctx, String title, String filePath) {
276 | FileUtils.shareFile(ctx, title, filePath);
277 | }
278 |
279 |
280 | public static List getShareTargets(Context ctx) {
281 | Intent intent = new Intent(Intent.ACTION_SEND, null);
282 | intent.addCategory(Intent.CATEGORY_DEFAULT);
283 | intent.setType("text/plain");
284 | PackageManager pm = ctx.getPackageManager();
285 | return pm.queryIntentActivities(intent, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
286 | }
287 |
288 | public static String getCurrentLanguage() {
289 | return Locale.getDefault().getLanguage();
290 | }
291 |
292 | public static String getLanguage(Context ctx) {
293 | if (ctx != null) {
294 | return ctx.getResources().getConfiguration().locale.getLanguage();
295 | }
296 | return null;
297 | }
298 |
299 | //
300 | public static boolean isGpsEnabled(Context context) {
301 | LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
302 | return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
303 | }
304 |
305 | public static void showSoftInputMethod(Context context, EditText editText) {
306 | if (context != null && editText != null) {
307 | editText.requestFocus();
308 | InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
309 | inputManager.showSoftInput(editText, 0);
310 | }
311 | }
312 |
313 |
314 | public static void closeSoftInputMethod(Context context, EditText editText) {
315 | if (context != null && editText != null) {
316 | InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
317 | if (imm != null) {
318 | imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
319 | }
320 | }
321 | }
322 |
323 | public static void showSoftInput(Context context) {
324 | InputMethodManager inputMethodManager = (InputMethodManager) context
325 | .getSystemService(Context.INPUT_METHOD_SERVICE);
326 | inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
327 | }
328 |
329 |
330 | public static void closeSoftInput(Context context) {
331 | InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
332 | if (inputMethodManager != null && ((Activity) context).getCurrentFocus() != null) {
333 | inputMethodManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
334 | }
335 | }
336 |
337 | public static void toWeChatScan(Context context) {
338 | try {
339 | Uri uri = Uri.parse("weixin://dl/scan");
340 | Intent intent = new Intent(Intent.ACTION_VIEW, uri);
341 | context.startActivity(intent);
342 | } catch (Exception e) {
343 | Toast.makeText(context, R.string.wechaterr, Toast.LENGTH_SHORT).show();
344 | }
345 | }
346 |
347 | public static void toAliPayScan(Context context) {
348 | try {
349 | Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=10000007");
350 | Intent intent = new Intent(Intent.ACTION_VIEW, uri);
351 | context.startActivity(intent);
352 | } catch (Exception e) {
353 | Toast.makeText(context, R.string.alipayerr, Toast.LENGTH_SHORT).show();
354 | }
355 | }
356 |
357 | public static void toAliPayPayCode(Context context) {
358 | try {
359 | Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=20000056");
360 | Intent intent = new Intent(Intent.ACTION_VIEW, uri);
361 | context.startActivity(intent);
362 | } catch (Exception e) {
363 | Toast.makeText(context, R.string.alipayerr, Toast.LENGTH_SHORT).show();
364 | }
365 | }
366 |
367 | public static int getRandomNumber(int min, int max) {
368 | return new Random().nextInt(max) % (max - min + 1) + min;
369 | }
370 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/code19/library/VerificationUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.code19.library;
18 |
19 | import android.text.TextUtils;
20 |
21 | import java.text.SimpleDateFormat;
22 | import java.util.regex.Pattern;
23 |
24 | /**
25 | * Create by h4de5ing 2016/5/21 021
26 | * https://github.com/sharinghuang/ASRabbit/blob/7350ea1c212946633316d36760c7088728dc2730/baselib/src/main/java/com/ht/baselib/utils/FormatVerificationUtils.java
27 | */
28 | public class VerificationUtils {
29 | public static boolean matcherRealName(String value) {
30 | String regex = "^([\\u4e00-\\u9fa5]+|([a-zA-Z]+\\s?)+)$";
31 | return testRegex(regex, value);
32 | }
33 |
34 | public static boolean matcherPhoneNum(String value) {
35 | String regex = "^(\\+?\\d{2}-?)?(1[0-9])\\d{9}$";
36 | return testRegex(regex, value);
37 | }
38 |
39 | public static boolean matcherAccount(String value) {
40 | String regex = "[\\u4e00-\\u9fa5a-zA-Z0-9\\-]{4,20}";
41 | return testRegex(regex, value);
42 | }
43 |
44 | public static boolean matcherPassword(String value) {
45 | String regex = "^[a-zA-Z0-9]{6,12}$";
46 | return testRegex(regex, value);
47 | }
48 |
49 | public static boolean matcherPassword2(String value) {
50 | String regex = "(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}";
51 | return testRegex(regex, value);
52 | }
53 |
54 |
55 | public static boolean matcherEmail(String value) {
56 | // String regex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)" +
57 | // "+[a-zA-Z]{2,}$";
58 | String regex = "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+" +
59 | "(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+" +
60 | "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$";
61 | return testRegex(regex, value);
62 | }
63 |
64 | public static boolean matcherIP(String value) {
65 | String regex = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\" +
66 | "d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\" +
67 | "d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
68 | return testRegex(regex, value.toLowerCase());
69 | }
70 |
71 | public static boolean matcherUrl(String value) {
72 | //String regex = "^(([hH][tT]{2}[pP][sS]?)|([fF][tT][pP]))\\:\\/\\/[wW]{3}\\.[\\w-]+\\.\\w{2,4}(\\/.*)?$";
73 | String regex = "^(([hH][tT]{2}[pP][sS]?)|([fF][tT][pP]))\\:\\/\\/[\\w-]+\\.\\w{2,4}(\\/.*)?$";
74 | return testRegex(regex, value.toLowerCase());
75 | }
76 |
77 | public static boolean matcherVehicleNumber(String value) {
78 | String regex = "^[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云藏陕甘青宁新渝]?[A-Z][A-HJ-NP-Z0-9学挂港澳练]{5}$";
79 | return testRegex(regex, value.toLowerCase());
80 | }
81 |
82 |
83 | public static boolean matcherIdentityCard(String value) {
84 | // String regex = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|" +
85 | // "(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|" +
86 | // "\\d{3}[Xx])$)$";
87 | // return testRegex(regex, value);
88 | IDCardTester idCardTester = new IDCardTester();
89 | return idCardTester.test(value);
90 | }
91 |
92 | private static class IDCardTester {
93 | public boolean test(String content) {
94 | if (TextUtils.isEmpty(content)) {
95 | return false;
96 | }
97 | final int length = content.length();
98 | if (15 == length) {
99 | try {
100 | return isOldCNIDCard(content);
101 | } catch (NumberFormatException e) {
102 | e.printStackTrace();
103 | return false;
104 | }
105 | } else if (18 == length) {
106 | return isNewCNIDCard(content);
107 | } else {
108 | return false;
109 | }
110 | }
111 |
112 | final int[] WEIGHT = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
113 |
114 | final char[] VALID = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
115 |
116 | public boolean isNewCNIDCard(String numbers) {
117 | numbers = numbers.toUpperCase();
118 | int sum = 0;
119 | for (int i = 0; i < WEIGHT.length; i++) {
120 | final int cell = Character.getNumericValue(numbers.charAt(i));
121 | sum += WEIGHT[i] * cell;
122 | }
123 | int index = sum % 11;
124 | return VALID[index] == numbers.charAt(17);
125 | }
126 |
127 | public boolean isOldCNIDCard(String numbers) {
128 | String yymmdd = numbers.substring(6, 11);
129 | boolean aPass = numbers.equals(String.valueOf(Long.parseLong(numbers)));
130 | boolean yPass = true;
131 | try {
132 | new SimpleDateFormat("yyMMdd").parse(yymmdd);
133 | } catch (Exception e) {
134 | e.printStackTrace();
135 | yPass = false;
136 | }
137 | return aPass && yPass;
138 | }
139 | }
140 |
141 | public static boolean isNumeric(String input) {
142 | if (TextUtils.isEmpty(input)) {
143 | return false;
144 | }
145 | char[] chars = input.toCharArray();
146 | int sz = chars.length;
147 | boolean hasExp = false;
148 | boolean hasDecPoint = false;
149 | boolean allowSigns = false;
150 | boolean foundDigit = false;
151 | int start = (chars[0] == '-' || chars[0] == '+') ? 1 : 0;
152 | if (sz > start + 1) {
153 | if (chars[start] == '0' && chars[start + 1] == 'x') {
154 | int i = start + 2;
155 | if (i == sz) {
156 | return false;
157 | }
158 | for (; i < chars.length; i++) {
159 | if ((chars[i] < '0' || chars[i] > '9')
160 | && (chars[i] < 'a' || chars[i] > 'f')
161 | && (chars[i] < 'A' || chars[i] > 'F')) {
162 | return false;
163 | }
164 | }
165 | return true;
166 | }
167 | }
168 | sz--;
169 | int i = start;
170 | while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
171 | if (chars[i] >= '0' && chars[i] <= '9') {
172 | foundDigit = true;
173 | allowSigns = false;
174 |
175 | } else if (chars[i] == '.') {
176 | if (hasDecPoint || hasExp) {
177 | return false;
178 | }
179 | hasDecPoint = true;
180 | } else if (chars[i] == 'e' || chars[i] == 'E') {
181 | if (hasExp) {
182 | return false;
183 | }
184 | if (!foundDigit) {
185 | return false;
186 | }
187 | hasExp = true;
188 | allowSigns = true;
189 | } else if (chars[i] == '+' || chars[i] == '-') {
190 | if (!allowSigns) {
191 | return false;
192 | }
193 | allowSigns = false;
194 | foundDigit = false;
195 | } else {
196 | return false;
197 | }
198 | i++;
199 | }
200 | if (i < chars.length) {
201 | if (chars[i] >= '0' && chars[i] <= '9') {
202 | return true;
203 | }
204 | if (chars[i] == 'e' || chars[i] == 'E') {
205 | return false;
206 | }
207 | if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) {
208 | return foundDigit;
209 | }
210 | if (chars[i] == 'l' || chars[i] == 'L') {
211 | return foundDigit && !hasExp;
212 | }
213 | return false;
214 | }
215 | return !allowSigns && foundDigit;
216 | }
217 |
218 | public static boolean testRegex(String regex, String inputValue) {
219 | return Pattern.compile(regex).matcher(inputValue).matches();
220 | }
221 |
222 | public static boolean checkPostcode(String postcode) {
223 | String regex = "[1-9]\\d{5}";
224 | return Pattern.matches(regex, postcode);
225 | }
226 | }
227 |
--------------------------------------------------------------------------------
/library/src/main/res/drawable/divider.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
7 |
8 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | 无法跳转到微信,请检查您是否安装了微信!
3 | 无法跳转到支付宝,请检查您是否安装了支付宝!
4 |
5 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library'
2 |
--------------------------------------------------------------------------------