├── .gitignore ├── LICENSE.txt ├── README.md ├── android-common.iml ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── litesuits │ │ ├── android │ │ ├── async │ │ │ └── AsyncExecutor.java │ │ ├── log │ │ │ ├── Log.java │ │ │ └── LogReader.java │ │ └── view │ │ │ └── TipsView.java │ │ └── common │ │ ├── assist │ │ ├── Averager.java │ │ ├── Base64.java │ │ ├── Check.java │ │ ├── FlashLight.java │ │ ├── KeyguardLock.java │ │ ├── Network.java │ │ ├── SilentInstaller.java │ │ ├── TimeAverager.java │ │ ├── TimeCounter.java │ │ ├── TimeKeeper.java │ │ ├── Toastor.java │ │ └── WakeLock.java │ │ ├── data │ │ ├── DataKeeper.java │ │ └── cipher │ │ │ ├── Base64Cipher.java │ │ │ ├── Cipher.java │ │ │ ├── Decrypt.java │ │ │ └── Encrypt.java │ │ ├── io │ │ ├── Charsets.java │ │ ├── FileUtils.java │ │ ├── FilenameUtils.java │ │ ├── IOUtils.java │ │ ├── StringCodingUtils.java │ │ └── stream │ │ │ ├── ByteArrayOutputStream.java │ │ │ ├── ClosedInputStream.java │ │ │ └── StringBuilderWriter.java │ │ ├── receiver │ │ ├── PhoneReceiver.java │ │ ├── ScreenReceiver.java │ │ ├── SmsReceiver.java │ │ └── TimeReceiver.java │ │ ├── service │ │ └── NotificationService.java │ │ └── utils │ │ ├── AlarmUtil.java │ │ ├── AndroidUtil.java │ │ ├── AppUtil.java │ │ ├── BitmapUtil.java │ │ ├── ByteUtil.java │ │ ├── ClassUtil.java │ │ ├── ClipboardUtil.java │ │ ├── CpuUtil.java │ │ ├── DialogUtil.java │ │ ├── DisplayUtil.java │ │ ├── FieldUtil.java │ │ ├── FileUtil.java │ │ ├── HandlerUtil.java │ │ ├── HexUtil.java │ │ ├── InputMethodUtils.java │ │ ├── MD5Util.java │ │ ├── MemoryUtil.java │ │ ├── NotificationUtil.java │ │ ├── NumberUtil.java │ │ ├── PackageUtil.java │ │ ├── PollingUtil.java │ │ ├── RandomUtil.java │ │ ├── SdCardUtil.java │ │ ├── ShellUtil.java │ │ ├── TelephoneUtil.java │ │ └── VibrateUtil.java │ └── res │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # root files 2 | 3 | # built application files 4 | *.apk 5 | *.ap_ 6 | 7 | # files for the dex VM 8 | *.dex 9 | 10 | # Java class files 11 | *.class 12 | 13 | # generated files 14 | bin/ 15 | gen/ 16 | out/ 17 | 18 | # Local configuration file (sdk path, etc) 19 | *.properties 20 | proguard-project.txt 21 | 22 | # Eclipse project files 23 | .classpath 24 | .project 25 | .settings 26 | 27 | # Proguard folder generated by Eclipse 28 | proguard/ 29 | 30 | # Intellij project files 31 | *.iml 32 | *.ipr 33 | *.iws 34 | .idea/ 35 | 36 | .DS_Store 37 | 38 | 39 | gen/com/litesuits/common/BuildConfig.java 40 | 41 | lint.xml 42 | 43 | project.properties 44 | 45 | .gradle 46 | /local.properties 47 | /.idea 48 | /build -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | LiteCommon项目简介 2 | --- 3 | 4 | Android Common Utils or Helper. 5 | 6 | Such as Log, Averager, Base64, Check, FlashLight, KeyguardLock, LogReader, Network, SilentInstaller, TimeAverager, TimeCounter, Toastor, WakeLock, ScreenReceiver, SmsReceiver, PhoneReceiver, NotificationService, AndroidUtil, AppUtil, BitmapUtil, ByteUtil, ClassUtil, DialogUtil, FieldUtil, FileUtil, HexUtil, MD5Util, NotificationUtil, NumberUtil, PackageUtil, RandomUtil, ShellUtil, TelephoneUtil, VibrateUtil, IOUtils, FileUtils, AsyncExecutor, etc. 7 | 8 | ##使用方法 9 | 10 | build.gradle文件中添加: 11 | 12 | dependencies { 13 | ... 14 | compile 'com.luffykou:android-common-utils:1.1.3' 15 | } 16 | 17 | ##详细介绍 18 | 19 | LiteCommon是一系列通用类、辅助类、工具类的集合,有以下特点: 20 | - **1. 通用性强**:只有常用、通用才集入。 21 | - **2. 体积超小**:不到50K!加入增强IO包混淆后70K! 22 | - **3. 纯 纯 纯**:类间独立,单挑大梁,极少耦合,就是单纯! 23 | 24 | 其中包括bitmap处理,文件操作,加密存储器,shell命令,静默安装,计数器,均值器,吐司,日志,校验,提示,网络监测等基础功能,以及一些Base64、MD5、Hex、Byte、Number、Dialog、Filed、Class、Package、Telephone、Random等工具类。 25 | 26 | 1. async包:异步与并发 27 | ----- 28 | - **AsyncExecutor**: 一个简单的可以自定义线程池并发执行器 29 | 2. log包:日志 30 | ----- 31 | - **Log**: 一个和android系统日志类同名(方便快速替换)的Log工具类,不同的是这个Log具有一键开关功能,方便快速开发打开调试模式。 32 | 3. assit包:辅助 33 | ----- 34 | - **Averager**: 均值器, 添加一些列数字或时间戳,获取其均值。 35 | - **Base64**: Base64, 兼容到android1.0版本的Base64编解码器。 36 | - **Check**: 检测类, 检测各种对象是否为null或empty。 37 | - **FlashLight**: 闪光灯, 开启、关闭闪光灯。 38 | - **KeyguardLock**: 锁屏管理, 锁屏、禁用锁屏,判断是否锁屏 39 | - **LogReader**: 日志捕获器, 将某个程序、级别的日志记录到sd卡中,方便远程调试。 40 | - **Network**: 网络探测器, 判断网络是否打开、连接、可用,以及当前网络状态。 41 | - **SilentInstaller**: 安装器, 静默安装、卸载(仅在root过的手机上)。 42 | - **TimeAverager**: 计时均值器, 统计耗时的同时,多次调用可得出其花费时间均值。 43 | - **TimeCounter**: 计时器, 顾名思义,统计耗时用的。 44 | - **Toastor**: 吐司, 解决多次连续弹出提示问题,可只弹出最后一次,也可连续弹出轻量级提示。 45 | - **WakeLock**: 屏幕管理, 点亮、关闭屏幕,判断屏幕是否点亮 46 | 4. data包:数据处理 47 | ----- 48 | - **DataKeeper**: 加密存储器,持久化工具,可加密,更简单、安全的存储(持久化)、获取数字、布尔值、甚至对象。 49 | - **chipher包**: 放置加解密辅助类。 50 | 5. io包:文件与IO 51 | ----- 52 | - **Charsets**: 字节编码类 53 | - **FilenameUtils**: 通用的文件名字、路径操作工具类 54 | - **FileUtils**: 通用文件操作工具类 55 | - **IOUtils**: 通用IO流操作工具类 56 | - **StringCodingUtils**:字符串编码工具类 57 | - **stream包**: IO流操作辅助类 58 | - 59 | 6. receiver包:通用广播接收器 60 | ----- 61 | - **ScreenReceiver**: 屏幕接收器,可收到屏幕点亮、关闭的广播,并通过回调通知给调用者 62 | - **PhoneReceiver**: 电话监听,来电、去电、通话、挂断的监听以及来去电话号码的获取。 63 | - **SmsReceiver**: 短信接收器,可获取短信内容,发送者号码,短信中心号码等。 64 | 65 | 7. utils包:常用工具类 66 | ----- 67 | - **AndroidUtil**: android信息, 获取android手机品牌、商家、版本号等信息 68 | - **AppUtil**: app工具, 检测是否前台运行 69 | - **BitmapUtil**: 位图操作, 拍照,裁剪,圆角,byte、string互转,压缩,放缩,保存等 70 | - **ByteUtil**: byte工具类 71 | - **ClassUtil**: 类工具, 新建实例,判断类的类型等 72 | - **DialogUtil**: 对话框工具类, 统一全局对话框 73 | - **FieldUtil**: 属性工具类,获取属性值、获取属性泛型类型等 74 | - **FileUtil**: 文件工具类 75 | - **HexUtil**: 16进制工具类,16进制和byte、char像话转化 76 | - **MD5Util**: MD5工具类 77 | - **NotificationUtil**:通知工具类,便捷显示到顶部栏 78 | - **NumberUtil**: 数字工具类,各种数字安全转化 79 | - **PackageUtil**: 应用程序类,打开、安装,卸载,启动应用以及获取应用信息 80 | - **RandomUtil**: 随机工具类,产生随机string或数字,随机洗牌等 81 | - **ShellUtil**: shell 命令工具类 82 | - **TelephoneUtil**: 电话工具类,手机号、运营商、IMEI、IMSI等信息 83 | - **VibrateUtil**: 震动工具类,调用系统震动功能 84 | 85 | 8. service包:通用服务 86 | ----- 87 | - **NotificationService**:通知监听,各类通知服务的监听,获取通知的简述、标题、内容等信息,可以获取诸如QQ、微信、淘宝、浏览器等所有的在通知栏提示的消息。 88 | 89 | 90 | 关于作者(About Author) 91 | ----- 92 | 我的博客 :[http://vmatianyu.cn](http://vmatianyu.cn/) 93 | 94 | 我的开源站点 :[http://litesuits.com](http://litesuits.com/) 95 | 96 | 点击加入QQ群: 97 | [42960650](http://jq.qq.com/?_wv=1027&k=cxjcDa) 98 | 99 | [47357508](http://jq.qq.com/?_wv=1027&k=Z7l0Av) 100 | 101 | 我的论坛帖子 102 | ----- 103 | [LiteHttp:极简且智能的 android HTTP 框架库 (专注于网络)](http://www.eoeandroid.com/thread-326584-1-1.html) 104 | 105 | [LiteOrm:极简且智能的 android ORM 框架库 (专注数据库)](http://www.eoeandroid.com/thread-538203-1-1.html) 106 | 107 | [LiteAsync:强势的 android 异步 框架库 (专注异步与并发)](http://www.eoeandroid.com/thread-538212-1-1.html) 108 | 109 | [LiteCommon:丰富通用的android工具类库(专注于基础组件)](http://www.eoeandroid.com/thread-557246-1-1.html) 110 | 111 | 我的博客帖子 112 | ----- 113 | [关于java的线程并发和锁的总结](http://www.vmatianyu.cn/summary-of-the-java-thread-concurrency-and-locking.html) 114 | 115 | [android开发技术经验总结60条](http://www.vmatianyu.cn/summarization-of-technical-experience.html) 116 | 117 | [聚划算android客户端1期教训总结](http://www.vmatianyu.cn/poly-effective-client-1-issues-lessons.html) 118 | 119 | [移动互联网产品设计小结](http://www.vmatianyu.cn/summary-of-mobile-internet-product-design.html) 120 | -------------------------------------------------------------------------------- /android-common.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | *.iml -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.novoda.bintray-release' 3 | 4 | android { 5 | compileSdkVersion 20 6 | buildToolsVersion '25.0.0' 7 | 8 | defaultConfig { 9 | minSdkVersion 7 10 | targetSdkVersion 20 11 | versionCode 13 12 | versionName "1.1.3" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | lintOptions { 21 | abortOnError false 22 | } 23 | } 24 | 25 | 26 | buildscript { 27 | repositories { 28 | jcenter() 29 | } 30 | dependencies { 31 | classpath 'com.novoda:bintray-release:0.3.4' 32 | } 33 | } 34 | 35 | 36 | dependencies { 37 | compile fileTree(dir: 'libs', include: ['*.jar']) 38 | } 39 | 40 | tasks.withType(Javadoc) { 41 | options.addStringOption('Xdoclint:none', '-quiet') 42 | options.addStringOption('encoding', 'UTF-8') 43 | } 44 | 45 | publish { 46 | userOrg = 'litesuits' //bintray.com username 47 | groupId = 'com.litesuits' //jcenter url 48 | artifactId = 'android-common' //library name 49 | publishVersion = '1.0.0' //version 50 | desc = 'A powerful android common utils library.' //description 51 | website = 'https://litesuits.com' 52 | } 53 | 54 | def libVersion = '1.2.0' 55 | task makeJar(type: Jar) { 56 | // 指定生成的jar名 57 | def rootDir = project.getRootDir(); 58 | def parentDir = project.getRootDir().getParentFile().getAbsolutePath(); 59 | 60 | delete 'build/libs/*.*' 61 | archiveName 'android-common-' + libVersion + '.jar' 62 | destinationDir = file('build/libs') 63 | // 从哪里打包class文件 64 | from('build/intermediates/classes/release/') 65 | // 打包到jar后的目录结构 66 | // 去掉不需要打包的目录和文件 67 | exclude('test/', 'BuildConfig.class', 'R.class', 'R\$*.class', 'META-INF/') 68 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/luffy/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/android/async/AsyncExecutor.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.android.async; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | import com.litesuits.android.log.Log; 6 | 7 | import java.util.concurrent.*; 8 | 9 | /** 10 | * 异步执行 11 | * 12 | * @author MaTianyu 13 | */ 14 | public class AsyncExecutor { 15 | private static final String TAG = AsyncExecutor.class.getSimpleName(); 16 | private static ExecutorService threadPool; 17 | public static Handler handler = new Handler(Looper.getMainLooper()); 18 | 19 | public AsyncExecutor() { 20 | this(null); 21 | } 22 | 23 | public AsyncExecutor(ExecutorService threadPool) { 24 | if (AsyncExecutor.threadPool != null) { 25 | shutdownNow(); 26 | } 27 | if (threadPool == null) { 28 | AsyncExecutor.threadPool = Executors.newCachedThreadPool(); 29 | } else { 30 | AsyncExecutor.threadPool = threadPool; 31 | } 32 | } 33 | 34 | public static synchronized void shutdownNow() { 35 | if (threadPool != null && !threadPool.isShutdown()) threadPool.shutdownNow(); 36 | threadPool = null; 37 | } 38 | 39 | /** 40 | * 将任务投入线程池执行 41 | * 42 | * @param worker 43 | * @return 44 | */ 45 | public FutureTask execute(final Worker worker) { 46 | Callable call = new Callable() { 47 | @Override 48 | public T call() throws Exception { 49 | return postResult(worker, worker.doInBackground()); 50 | } 51 | }; 52 | FutureTask task = new FutureTask(call) { 53 | @Override 54 | protected void done() { 55 | try { 56 | get(); 57 | } catch (InterruptedException e) { 58 | Log.e(TAG, e); 59 | worker.abort(); 60 | postCancel(worker); 61 | e.printStackTrace(); 62 | } catch (ExecutionException e) { 63 | Log.e(TAG, e.getMessage()); 64 | e.printStackTrace(); 65 | throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); 66 | } catch (CancellationException e) { 67 | worker.abort(); 68 | postCancel(worker); 69 | Log.e(TAG, e); 70 | e.printStackTrace(); 71 | } 72 | } 73 | }; 74 | threadPool.execute(task); 75 | return task; 76 | } 77 | 78 | /** 79 | * 将子线程结果传递到UI线程 80 | * 81 | * @param worker 82 | * @param result 83 | * @return 84 | */ 85 | private T postResult(final Worker worker, final T result) { 86 | handler.post(new Runnable() { 87 | @Override 88 | public void run() { 89 | worker.onPostExecute(result); 90 | } 91 | }); 92 | return result; 93 | } 94 | 95 | /** 96 | * 将子线程结果传递到UI线程 97 | * 98 | * @param worker 99 | * @return 100 | */ 101 | private void postCancel(final Worker worker) { 102 | handler.post(new Runnable() { 103 | @Override 104 | public void run() { 105 | worker.onCanceled(); 106 | } 107 | }); 108 | } 109 | 110 | public FutureTask execute(Callable call) { 111 | FutureTask task = new FutureTask(call); 112 | threadPool.execute(task); 113 | return task; 114 | } 115 | 116 | public static abstract class Worker { 117 | protected abstract T doInBackground(); 118 | 119 | protected void onPostExecute(T data) {} 120 | 121 | protected void onCanceled() {} 122 | 123 | protected void abort() {} 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/android/log/Log.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 litesuits.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.litesuits.android.log; 17 | 18 | /** 19 | * the logger 20 | * 21 | * @author MaTianyu 22 | * 2014-1-1下午4:05:39 23 | */ 24 | public final class Log { 25 | 26 | /** 27 | * isPrint: print switch, true will print. false not print 28 | */ 29 | public static boolean isPrint = true; 30 | private static String defaultTag = "Log"; 31 | 32 | private Log() {} 33 | 34 | public static void setTag(String tag) { 35 | defaultTag = tag; 36 | } 37 | 38 | public static int i(Object o) { 39 | return isPrint && o != null ? android.util.Log.i(defaultTag, o.toString()) : -1; 40 | } 41 | 42 | public static int i(String m) { 43 | return isPrint && m != null ? android.util.Log.i(defaultTag, m) : -1; 44 | } 45 | 46 | /** 47 | * ******************** Log ************************** 48 | */ 49 | public static int v(String tag, String msg) { 50 | return isPrint && msg != null ? android.util.Log.v(tag, msg) : -1; 51 | } 52 | 53 | public static int d(String tag, String msg) { 54 | return isPrint && msg != null ? android.util.Log.d(tag, msg) : -1; 55 | } 56 | 57 | public static int i(String tag, String msg) { 58 | return isPrint && msg != null ? android.util.Log.i(tag, msg) : -1; 59 | } 60 | 61 | public static int w(String tag, String msg) { 62 | return isPrint && msg != null ? android.util.Log.w(tag, msg) : -1; 63 | } 64 | 65 | public static int e(String tag, String msg) { 66 | return isPrint && msg != null ? android.util.Log.e(tag, msg) : -1; 67 | } 68 | 69 | /** 70 | * ******************** Log with object list ************************** 71 | */ 72 | public static int v(String tag, Object... msg) { 73 | return isPrint ? android.util.Log.v(tag, getLogMessage(msg)) : -1; 74 | } 75 | 76 | public static int d(String tag, Object... msg) { 77 | return isPrint ? android.util.Log.d(tag, getLogMessage(msg)) : -1; 78 | } 79 | 80 | public static int i(String tag, Object... msg) { 81 | return isPrint ? android.util.Log.i(tag, getLogMessage(msg)) : -1; 82 | } 83 | 84 | public static int w(String tag, Object... msg) { 85 | return isPrint ? android.util.Log.w(tag, getLogMessage(msg)) : -1; 86 | } 87 | 88 | public static int e(String tag, Object... msg) { 89 | return isPrint ? android.util.Log.e(tag, getLogMessage(msg)) : -1; 90 | } 91 | 92 | private static String getLogMessage(Object... msg) { 93 | if (msg != null && msg.length > 0) { 94 | StringBuilder sb = new StringBuilder(); 95 | for (Object s : msg) { 96 | if (s != null) { 97 | sb.append(s.toString()); 98 | } 99 | } 100 | return sb.toString(); 101 | } 102 | return ""; 103 | } 104 | 105 | /** 106 | * ******************** Log with Throwable ************************** 107 | */ 108 | public static int v(String tag, String msg, Throwable tr) { 109 | return isPrint && msg != null ? android.util.Log.v(tag, msg, tr) : -1; 110 | } 111 | 112 | public static int d(String tag, String msg, Throwable tr) { 113 | return isPrint && msg != null ? android.util.Log.d(tag, msg, tr) : -1; 114 | } 115 | 116 | public static int i(String tag, String msg, Throwable tr) { 117 | return isPrint && msg != null ? android.util.Log.i(tag, msg, tr) : -1; 118 | } 119 | 120 | public static int w(String tag, String msg, Throwable tr) { 121 | return isPrint && msg != null ? android.util.Log.w(tag, msg, tr) : -1; 122 | } 123 | 124 | public static int e(String tag, String msg, Throwable tr) { 125 | return isPrint && msg != null ? android.util.Log.e(tag, msg, tr) : -1; 126 | } 127 | 128 | /** 129 | * ******************** TAG use Object Tag ************************** 130 | */ 131 | public static int v(Object tag, String msg) { 132 | return isPrint ? android.util.Log.v(tag.getClass().getSimpleName(), msg) : -1; 133 | } 134 | 135 | public static int d(Object tag, String msg) { 136 | return isPrint ? android.util.Log.d(tag.getClass().getSimpleName(), msg) : -1; 137 | } 138 | 139 | public static int i(Object tag, String msg) { 140 | return isPrint ? android.util.Log.i(tag.getClass().getSimpleName(), msg) : -1; 141 | } 142 | 143 | public static int w(Object tag, String msg) { 144 | return isPrint ? android.util.Log.w(tag.getClass().getSimpleName(), msg) : -1; 145 | } 146 | 147 | public static int e(Object tag, String msg) { 148 | return isPrint ? android.util.Log.e(tag.getClass().getSimpleName(), msg) : -1; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/android/log/LogReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 litesuits.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.litesuits.android.log; 17 | 18 | import java.io.*; 19 | import java.text.DecimalFormat; 20 | import java.text.SimpleDateFormat; 21 | import java.util.Date; 22 | 23 | /** 24 | * 打印日志 25 | * 26 | * @author mty 27 | * @time 2011-11-2下午06:23:29 28 | */ 29 | public class LogReader extends Thread { 30 | public static final String TAG = "LogReader"; 31 | public static final String LOG_FILE_PATH = "/bonglog.txt"; 32 | public static final String LOG_ROOT_PATH = "/sdcard"; 33 | 34 | public static boolean open = true; 35 | private static LogReader instance = null; 36 | private static Process mLogcatProc = null; 37 | 38 | private BufferedReader mReader = null; 39 | private String packageName = "*"; 40 | 41 | public static void startCatchLog(String packageName) { 42 | if (!open) return; 43 | if (instance == null) { 44 | instance = new LogReader(); 45 | instance.packageName = packageName; 46 | instance.start(); 47 | } 48 | } 49 | 50 | public static void stopCatchLog() { 51 | if (!open) return; 52 | if (mLogcatProc != null) { 53 | mLogcatProc.destroy(); 54 | mLogcatProc = null; 55 | } 56 | } 57 | 58 | @Override 59 | public void run() { 60 | Log.i(TAG, "log reader(catcher) is running..---------------------------"); 61 | BufferedWriter bw = null; 62 | try { 63 | mLogcatProc = Runtime.getRuntime().exec("logcat " + packageName + ":I"); 64 | mReader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream())); 65 | 66 | // 打印系统信息。 67 | logSystemInfo(); 68 | 69 | String line; 70 | File file = new File(LOG_ROOT_PATH + LOG_FILE_PATH); 71 | if (file.exists() && isFileSizeOutof10M(file)) { 72 | file.delete(); 73 | } 74 | if (file.exists()) { 75 | System.out.println("log file size is :" 76 | + FormatFileSize(file.length())); 77 | } 78 | FileWriter fw = new FileWriter(file, true); 79 | bw = new BufferedWriter(fw); 80 | while ((line = mReader.readLine()) != null) { 81 | bw.append(line); 82 | bw.newLine(); 83 | bw.flush(); 84 | } 85 | } catch (Exception e) { 86 | e.printStackTrace(); 87 | } finally { 88 | Log.i(TAG, "Log reader(catcher) and bufferwriter has closed. ------------------"); 89 | try { 90 | if (mReader != null) { 91 | mReader.close(); 92 | mReader = null; 93 | } 94 | if (bw != null) { 95 | bw.close(); 96 | } 97 | } catch (IOException e) { 98 | e.printStackTrace(); 99 | } 100 | instance = null; 101 | } 102 | 103 | } 104 | 105 | public static String FormatFileSize(long fileS) {// 转换文件大小 106 | DecimalFormat df = new DecimalFormat("#.00"); 107 | String fileSizeString = ""; 108 | if (fileS < 1024) { 109 | fileSizeString = df.format((double) fileS) + "B"; 110 | } else if (fileS < 1048576) { 111 | fileSizeString = df.format((double) fileS / 1024) + "K"; 112 | } else if (fileS < 1073741824) { 113 | fileSizeString = df.format((double) fileS / 1048576) + "M"; 114 | } else { 115 | fileSizeString = df.format((double) fileS / 1073741824) + "G"; 116 | } 117 | return fileSizeString; 118 | } 119 | 120 | /** 121 | * 判断文件是否大于10M。 122 | * 123 | * @param file 124 | * @return 125 | * @throws Exception 126 | */ 127 | public static boolean isFileSizeOutof10M(File file) throws Exception { 128 | if (file == null) return false; 129 | return file.length() >= 10485760; 130 | } 131 | 132 | public static void logSystemInfo() { 133 | Date date = new Date(System.currentTimeMillis()); 134 | SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 135 | String time = dateFormat.format(date); 136 | android.util.Log.w("system", "New Start $$$$$$$$$$$$$$########### " + time + "############$$$$$$$$$$$$$$$"); 137 | android.util.Log.w("system", "android.os.Build.BOARD:" + android.os.Build.BOARD); 138 | android.util.Log.w("system", "android.os.Build.DEVICE:" + android.os.Build.DEVICE); 139 | android.util.Log.w("system", "android.os.Build.MANUFACTURER:" 140 | + android.os.Build.MANUFACTURER); 141 | android.util.Log.w("system", "android.os.Build.MODEL:" + android.os.Build.MODEL); 142 | android.util.Log.w("system", "android.os.Build.PRODUCT:" + android.os.Build.PRODUCT); 143 | android.util.Log.w("system", "android.os.Build.VERSION.CODENAME:" 144 | + android.os.Build.VERSION.CODENAME); 145 | android.util.Log.w("system", "android.os.Build.VERSION.RELEASE:" 146 | + android.os.Build.VERSION.RELEASE); 147 | //android.util.Log.w("system", "android.os.Build.VERSION.SDK:" 148 | // + android.os.Build.VERSION.SDK); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/android/view/TipsView.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.android.view; 2 | 3 | import android.content.Context; 4 | import android.util.AttributeSet; 5 | import android.view.Gravity; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | import android.widget.LinearLayout; 10 | 11 | /** 12 | * @author MaTianyu 13 | * @date 2014-08-15 14 | */ 15 | public class TipsView extends LinearLayout { 16 | protected View realView; 17 | protected ViewGroup parentView; 18 | 19 | protected Context context; 20 | protected boolean isThisInLayout = false; 21 | 22 | public TipsView(Context context) { 23 | this(context, (AttributeSet) null); 24 | } 25 | 26 | public TipsView(Context context, AttributeSet attrs) { 27 | this(context, attrs, null, null); 28 | } 29 | 30 | public TipsView(Context context, View realView, View tipView) { 31 | this(context, null, realView, tipView); 32 | } 33 | 34 | public TipsView(Context context, View realView) { 35 | this(context, null, realView, null); 36 | } 37 | 38 | public TipsView(Context context, AttributeSet attrs, View realView, View tipView) { 39 | super(context, attrs); 40 | this.context = context; 41 | initSelf(); 42 | setRealView(realView); 43 | setTipView(tipView); 44 | } 45 | 46 | public void initSelf() { 47 | setOrientation(HORIZONTAL); 48 | setGravity(Gravity.CENTER); 49 | } 50 | 51 | public TipsView setTipView(View tipView) { 52 | if (tipView != null) { 53 | removeAllViews(); 54 | addView(tipView); 55 | } 56 | return this; 57 | } 58 | 59 | public TipsView setTipView(int resID) { 60 | removeAllViews(); 61 | LayoutInflater.from(context).inflate(resID, this, true); 62 | return this; 63 | } 64 | 65 | 66 | public View getRealView() { 67 | return realView; 68 | } 69 | 70 | 71 | public TipsView setRealView(View realView) { 72 | if (realView != null) { 73 | showRealView(); 74 | this.realView = realView; 75 | parentView = (ViewGroup) realView.getParent(); 76 | setLayoutParams(realView.getLayoutParams()); 77 | } 78 | return this; 79 | } 80 | 81 | 82 | public void showRealView() { 83 | if (realView != null && parentView != null) { 84 | if (isThisInLayout) { 85 | for (int i = 0, size = parentView.getChildCount(); i < size; i++) { 86 | if (parentView.getChildAt(i) == this) { 87 | parentView.removeView(this); 88 | //realView.setId(getId()); 89 | //setId(0); 90 | parentView.addView(realView, i); 91 | isThisInLayout = false; 92 | break; 93 | } 94 | } 95 | } 96 | } 97 | } 98 | 99 | public void showTipsView() { 100 | if (realView != null && parentView != null) { 101 | if (!isThisInLayout) { 102 | for (int i = 0, size = parentView.getChildCount(); i < size; i++) { 103 | if (parentView.getChildAt(i) == realView) { 104 | parentView.removeView(realView); 105 | //setId(realView.getId()); 106 | //realView.setId(0); 107 | parentView.addView(this, i); 108 | isThisInLayout = true; 109 | break; 110 | } 111 | } 112 | } 113 | } 114 | } 115 | 116 | public void gone() { 117 | setVisibility(GONE); 118 | } 119 | 120 | public void visible() { 121 | setVisibility(VISIBLE); 122 | } 123 | 124 | public void inVisible() { 125 | setVisibility(INVISIBLE); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/assist/Averager.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.assist; 2 | 3 | import com.litesuits.android.log.Log; 4 | 5 | import java.util.ArrayList; 6 | 7 | /** 8 | * 用以统计平均数 9 | * 10 | * @author MaTianyu 11 | * 2013-12-11下午3:31:03 12 | */ 13 | public class Averager { 14 | private static final String TAG = "Averager"; 15 | private ArrayList numList = new ArrayList(); 16 | 17 | /** 18 | * 添加一个数字 19 | * 20 | * @param num 21 | */ 22 | public synchronized void add(Number num) { 23 | numList.add(num); 24 | } 25 | 26 | /** 27 | * 清除全部 28 | */ 29 | public void clear() { 30 | numList.clear(); 31 | } 32 | 33 | /** 34 | * 返回参与均值计算的数字个数 35 | * 36 | * @return 37 | */ 38 | public Number size() { 39 | return numList.size(); 40 | } 41 | 42 | /** 43 | * 获取平均数 44 | * 45 | * @return 46 | */ 47 | public Number getAverage() { 48 | if (numList.size() == 0) { 49 | return 0; 50 | } else { 51 | Float sum = 0f; 52 | for (int i = 0, size = numList.size(); i < size; i++) { 53 | sum = sum.floatValue() + numList.get(i).floatValue(); 54 | } 55 | return sum / numList.size(); 56 | } 57 | } 58 | 59 | /** 60 | * 打印数字列 61 | * 62 | * @return 63 | */ 64 | public String print() { 65 | String str = "PrintList(" + size() + "): " + numList; 66 | Log.i(TAG, str); 67 | return str; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/assist/Check.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.assist; 2 | 3 | import java.util.Collection; 4 | import java.util.Map; 5 | 6 | /** 7 | * 辅助判断 8 | * 9 | * @author mty 10 | * @date 2013-6-10下午5:50:57 11 | */ 12 | public class Check { 13 | 14 | public static boolean isEmpty(CharSequence str) { 15 | return isNull(str) || str.length() == 0; 16 | } 17 | 18 | public static boolean isEmpty(Object[] os) { 19 | return isNull(os) || os.length == 0; 20 | } 21 | 22 | public static boolean isEmpty(Collection l) { 23 | return isNull(l) || l.isEmpty(); 24 | } 25 | 26 | public static boolean isEmpty(Map m) { 27 | return isNull(m) || m.isEmpty(); 28 | } 29 | 30 | public static boolean isNull(Object o) { 31 | return o == null; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/assist/FlashLight.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.assist; 2 | 3 | import android.hardware.Camera; 4 | import android.os.Build; 5 | import android.os.Handler; 6 | 7 | /** 8 | * 9 | * Call requires API level 5 10 | * 11 | * 12 | * 13 | * @author MaTianyu 14 | * @date 2014-11-04 15 | */ 16 | public class FlashLight { 17 | 18 | private Camera camera; 19 | private Handler handler = new Handler(); 20 | 21 | /** 22 | * 超过3分钟自动关闭,防止损伤硬件 23 | */ 24 | private static final int OFF_TIME = 3 * 60 * 1000; 25 | 26 | public boolean turnOnFlashLight() { 27 | if (camera == null) { 28 | camera = Camera.open(); 29 | camera.startPreview(); 30 | Camera.Parameters parameter = camera.getParameters(); 31 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { 32 | parameter.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); 33 | } else { 34 | parameter.set("flash-mode", "torch"); 35 | } 36 | camera.setParameters(parameter); 37 | handler.removeCallbacksAndMessages(null); 38 | handler.postDelayed(new Runnable() { 39 | @Override 40 | public void run() { 41 | turnOffFlashLight(); 42 | } 43 | }, OFF_TIME); 44 | } 45 | return true; 46 | } 47 | 48 | public boolean turnOffFlashLight() { 49 | if (camera != null) { 50 | handler.removeCallbacksAndMessages(null); 51 | Camera.Parameters parameter = camera.getParameters(); 52 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { 53 | parameter.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); 54 | } else { 55 | parameter.set("flash-mode", "off"); 56 | } 57 | camera.setParameters(parameter); 58 | camera.stopPreview(); 59 | camera.release(); 60 | camera = null; 61 | } 62 | return true; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/assist/KeyguardLock.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.assist; 2 | 3 | import android.app.KeyguardManager; 4 | import android.content.Context; 5 | import android.os.Build; 6 | import com.litesuits.android.log.Log; 7 | 8 | /** 9 | * 10 | * require 11 | * 12 | * @author MaTianyu 13 | * @date 2014-12-12 14 | */ 15 | public class KeyguardLock { 16 | KeyguardManager keyguardManager; 17 | KeyguardManager.KeyguardLock keyguardLock; 18 | 19 | public KeyguardLock(Context context, String tag) { 20 | //获取系统服务 21 | keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); 22 | //初始化键盘锁,可以锁定或解开键盘锁 23 | keyguardLock = keyguardManager.newKeyguardLock(tag); 24 | } 25 | 26 | /** 27 | * Call requires API level 16 28 | */ 29 | public boolean isKeyguardLocked() { 30 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { 31 | Log.e("Log : ", "can not call isKeyguardLocked if SDK_INT < 16 "); 32 | return false; 33 | } else { 34 | return keyguardManager.isKeyguardLocked(); 35 | } 36 | 37 | } 38 | 39 | /** 40 | * Call requires API level 16 41 | */ 42 | public boolean isKeyguardSecure() { 43 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { 44 | Log.e("Log : ", "can not call isKeyguardSecure if SDK_INT < 16 "); 45 | return false; 46 | } else { 47 | return keyguardManager.isKeyguardSecure(); 48 | } 49 | } 50 | 51 | public boolean inKeyguardRestrictedInputMode() { 52 | return keyguardManager.inKeyguardRestrictedInputMode(); 53 | } 54 | 55 | public void disableKeyguard() { 56 | keyguardLock.disableKeyguard(); 57 | } 58 | 59 | public void reenableKeyguard() { 60 | keyguardLock.reenableKeyguard(); 61 | } 62 | 63 | public void release() { 64 | if (keyguardLock != null) { 65 | //禁用显示键盘锁定 66 | keyguardLock.reenableKeyguard(); 67 | } 68 | } 69 | 70 | public KeyguardManager getKeyguardManager() { 71 | return keyguardManager; 72 | } 73 | 74 | public void setKeyguardManager(KeyguardManager keyguardManager) { 75 | this.keyguardManager = keyguardManager; 76 | } 77 | 78 | public KeyguardManager.KeyguardLock getKeyguardLock() { 79 | return keyguardLock; 80 | } 81 | 82 | public void setKeyguardLock(KeyguardManager.KeyguardLock keyguardLock) { 83 | this.keyguardLock = keyguardLock; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/assist/Network.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.assist; 2 | 3 | import android.content.Context; 4 | import android.net.ConnectivityManager; 5 | import android.net.NetworkInfo; 6 | import android.telephony.TelephonyManager; 7 | import com.litesuits.android.log.Log; 8 | 9 | import java.lang.reflect.Method; 10 | 11 | /** 12 | * assist us in sensing state of the networks. 13 | * 14 | * need 15 | * 16 | * 半夜了,研究了一下Android的Network方面,发现网上有些文章理解的是不对的。 17 | * 以下方法是我研究得出的结论和方法,如有误也感谢指出。 18 | * 19 | * @author MaTianyu 20 | * 2014-1-8上午 00:33:11 21 | */ 22 | public class Network { 23 | private static final String TAG = Network.class.getSimpleName(); 24 | 25 | public enum NetType { 26 | None(1), 27 | Mobile(2), 28 | Wifi(4), 29 | Other(8); 30 | 31 | NetType(int value) { 32 | this.value = value; 33 | } 34 | 35 | public int value; 36 | } 37 | 38 | public enum NetWorkType { 39 | UnKnown(-1), 40 | Wifi(1), 41 | Net2G(2), 42 | Net3G(3), 43 | Net4G(4); 44 | 45 | NetWorkType(int value) { 46 | this.value = value; 47 | } 48 | 49 | public int value; 50 | } 51 | // 52 | //public enum NetSubType { 53 | // None(1), 54 | // Mobile(2), 55 | // Wifi(4), 56 | // Other(8); 57 | // 58 | // NetType(int value) { 59 | // this.value = value; 60 | // } 61 | // 62 | // public int value; 63 | //} 64 | 65 | /** 66 | * 获取ConnectivityManager 67 | */ 68 | public static ConnectivityManager getConnectivityManager(Context context) { 69 | return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 70 | } 71 | 72 | /** 73 | * 获取ConnectivityManager 74 | */ 75 | public static TelephonyManager getTelephonyManager(Context context) { 76 | return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 77 | } 78 | 79 | /** 80 | * 判断网络连接是否有效(此时可传输数据)。 81 | * 82 | * @return boolean 不管wifi,还是mobile net,只有当前在连接状态(可有效传输数据)才返回true,反之false。 83 | */ 84 | public static boolean isConnected(Context context) { 85 | NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo(); 86 | return net != null && net.isConnected(); 87 | } 88 | 89 | /** 90 | * 判断有无网络正在连接中(查找网络、校验、获取IP等)。 91 | * 92 | * @return boolean 不管wifi,还是mobile net,只有当前在连接状态(可有效传输数据)才返回true,反之false。 93 | */ 94 | public static boolean isConnectedOrConnecting(Context context) { 95 | NetworkInfo[] nets = getConnectivityManager(context).getAllNetworkInfo(); 96 | if (nets != null) { 97 | for (NetworkInfo net : nets) { 98 | if (net.isConnectedOrConnecting()) { return true; } 99 | } 100 | } 101 | return false; 102 | } 103 | 104 | public static NetType getConnectedType(Context context) { 105 | NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo(); 106 | if (net != null) { 107 | switch (net.getType()) { 108 | case ConnectivityManager.TYPE_WIFI: 109 | return NetType.Wifi; 110 | case ConnectivityManager.TYPE_MOBILE: 111 | return NetType.Mobile; 112 | default: 113 | return NetType.Other; 114 | } 115 | } 116 | return NetType.None; 117 | } 118 | 119 | /** 120 | * 是否存在有效的WIFI连接 121 | */ 122 | public static boolean isWifiConnected(Context context) { 123 | NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo(); 124 | return net != null && net.getType() == ConnectivityManager.TYPE_WIFI && net.isConnected(); 125 | } 126 | 127 | /** 128 | * 是否存在有效的移动连接 129 | * 130 | * @return boolean 131 | */ 132 | public static boolean isMobileConnected(Context context) { 133 | NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo(); 134 | return net != null && net.getType() == ConnectivityManager.TYPE_MOBILE && net.isConnected(); 135 | } 136 | 137 | /** 138 | * 检测网络是否为可用状态 139 | */ 140 | public static boolean isAvailable(Context context) { 141 | return isWifiAvailable(context) || (isMobileAvailable(context) && isMobileEnabled(context)); 142 | } 143 | 144 | /** 145 | * 判断是否有可用状态的Wifi,以下情况返回false: 146 | * 1. 设备wifi开关关掉; 147 | * 2. 已经打开飞行模式; 148 | * 3. 设备所在区域没有信号覆盖; 149 | * 4. 设备在漫游区域,且关闭了网络漫游。 150 | * 151 | * @return boolean wifi为可用状态(不一定成功连接,即Connected)即返回ture 152 | */ 153 | public static boolean isWifiAvailable(Context context) { 154 | NetworkInfo[] nets = getConnectivityManager(context).getAllNetworkInfo(); 155 | if (nets != null) { 156 | for (NetworkInfo net : nets) { 157 | if (net.getType() == ConnectivityManager.TYPE_WIFI) { return net.isAvailable(); } 158 | } 159 | } 160 | return false; 161 | } 162 | 163 | /** 164 | * 判断有无可用状态的移动网络,注意关掉设备移动网络直接不影响此函数。 165 | * 也就是即使关掉移动网络,那么移动网络也可能是可用的(彩信等服务),即返回true。 166 | * 以下情况它是不可用的,将返回false: 167 | * 1. 设备打开飞行模式; 168 | * 2. 设备所在区域没有信号覆盖; 169 | * 3. 设备在漫游区域,且关闭了网络漫游。 170 | * 171 | * @return boolean 172 | */ 173 | public static boolean isMobileAvailable(Context context) { 174 | NetworkInfo[] nets = getConnectivityManager(context).getAllNetworkInfo(); 175 | if (nets != null) { 176 | for (NetworkInfo net : nets) { 177 | if (net.getType() == ConnectivityManager.TYPE_MOBILE) { return net.isAvailable(); } 178 | } 179 | } 180 | return false; 181 | } 182 | 183 | /** 184 | * 设备是否打开移动网络开关 185 | * 186 | * @return boolean 打开移动网络返回true,反之false 187 | */ 188 | public static boolean isMobileEnabled(Context context) { 189 | try { 190 | Method getMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled"); 191 | getMobileDataEnabledMethod.setAccessible(true); 192 | return (Boolean) getMobileDataEnabledMethod.invoke(getConnectivityManager(context)); 193 | } catch (Exception e) { 194 | e.printStackTrace(); 195 | } 196 | // 反射失败,默认开启 197 | return true; 198 | } 199 | 200 | /** 201 | * 打印当前各种网络状态 202 | * 203 | * @return boolean 204 | */ 205 | public static boolean printNetworkInfo(Context context) { 206 | ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 207 | if (connectivity != null) { 208 | NetworkInfo in = connectivity.getActiveNetworkInfo(); 209 | Log.i(TAG, "-------------$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$-------------"); 210 | Log.i(TAG, "getActiveNetworkInfo: " + in); 211 | NetworkInfo[] info = connectivity.getAllNetworkInfo(); 212 | if (info != null) { 213 | for (int i = 0; i < info.length; i++) { 214 | // if (info[i].getType() == ConnectivityManager.TYPE_WIFI) { 215 | Log.i(TAG, "NetworkInfo[" + i + "]isAvailable : " + info[i].isAvailable()); 216 | Log.i(TAG, "NetworkInfo[" + i + "]isConnected : " + info[i].isConnected()); 217 | Log.i(TAG, "NetworkInfo[" + i + "]isConnectedOrConnecting : " + info[i].isConnectedOrConnecting()); 218 | Log.i(TAG, "NetworkInfo[" + i + "]: " + info[i]); 219 | // } 220 | } 221 | Log.i(TAG, "\n"); 222 | } else { 223 | Log.i(TAG, "getAllNetworkInfo is null"); 224 | } 225 | } 226 | return false; 227 | } 228 | 229 | /** 230 | * get connected network type by {@link ConnectivityManager} 231 | * 232 | * such as WIFI, MOBILE, ETHERNET, BLUETOOTH, etc. 233 | * 234 | * @return {@link ConnectivityManager#TYPE_WIFI}, {@link ConnectivityManager#TYPE_MOBILE}, 235 | * {@link ConnectivityManager#TYPE_ETHERNET}... 236 | */ 237 | public static int getConnectedTypeINT(Context context) { 238 | NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo(); 239 | if (net != null) { 240 | if (Log.isPrint) { 241 | Log.i(TAG, "NetworkInfo: " + net.toString()); 242 | } 243 | return net.getType(); 244 | } 245 | return -1; 246 | } 247 | 248 | /** 249 | * get network type by {@link TelephonyManager} 250 | * 251 | * such as 2G, 3G, 4G, etc. 252 | * 253 | * @return {@link TelephonyManager#NETWORK_TYPE_CDMA}, {@link TelephonyManager#NETWORK_TYPE_GPRS}, 254 | * {@link TelephonyManager#NETWORK_TYPE_LTE}... 255 | */ 256 | public static int getTelNetworkTypeINT(Context context) { 257 | return getTelephonyManager(context).getNetworkType(); 258 | } 259 | 260 | /** 261 | * GPRS 2G(2.5) General Packet Radia Service 114kbps 262 | * EDGE 2G(2.75G) Enhanced Data Rate for GSM Evolution 384kbps 263 | * UMTS 3G WCDMA 联通3G Universal Mobile Telecommunication System 完整的3G移动通信技术标准 264 | * CDMA 2G 电信 Code Division Multiple Access 码分多址 265 | * EVDO_0 3G (EVDO 全程 CDMA2000 1xEV-DO) Evolution - Data Only (Data Optimized) 153.6kps - 2.4mbps 属于3G 266 | * EVDO_A 3G 1.8mbps - 3.1mbps 属于3G过渡,3.5G 267 | * 1xRTT 2G CDMA2000 1xRTT (RTT - 无线电传输技术) 144kbps 2G的过渡, 268 | * HSDPA 3.5G 高速下行分组接入 3.5G WCDMA High Speed Downlink Packet Access 14.4mbps 269 | * HSUPA 3.5G High Speed Uplink Packet Access 高速上行链路分组接入 1.4 - 5.8 mbps 270 | * HSPA 3G (分HSDPA,HSUPA) High Speed Packet Access 271 | * IDEN 2G Integrated Dispatch Enhanced Networks 集成数字增强型网络 (属于2G,来自维基百科) 272 | * EVDO_B 3G EV-DO Rev.B 14.7Mbps 下行 3.5G 273 | * LTE 4G Long Term Evolution FDD-LTE 和 TDD-LTE , 3G过渡,升级版 LTE Advanced 才是4G 274 | * EHRPD 3G CDMA2000向LTE 4G的中间产物 Evolved High Rate Packet Data HRPD的升级 275 | * HSPAP 3G HSPAP 比 HSDPA 快些 276 | * 277 | * @return {@link NetWorkType} 278 | */ 279 | public static NetWorkType getNetworkType(Context context) { 280 | int type = getConnectedTypeINT(context); 281 | switch (type) { 282 | case ConnectivityManager.TYPE_WIFI: 283 | return NetWorkType.Wifi; 284 | case ConnectivityManager.TYPE_MOBILE: 285 | case ConnectivityManager.TYPE_MOBILE_DUN: 286 | case ConnectivityManager.TYPE_MOBILE_HIPRI: 287 | case ConnectivityManager.TYPE_MOBILE_MMS: 288 | case ConnectivityManager.TYPE_MOBILE_SUPL: 289 | int teleType = getTelephonyManager(context).getNetworkType(); 290 | switch (teleType) { 291 | case TelephonyManager.NETWORK_TYPE_GPRS: 292 | case TelephonyManager.NETWORK_TYPE_EDGE: 293 | case TelephonyManager.NETWORK_TYPE_CDMA: 294 | case TelephonyManager.NETWORK_TYPE_1xRTT: 295 | case TelephonyManager.NETWORK_TYPE_IDEN: 296 | return NetWorkType.Net2G; 297 | case TelephonyManager.NETWORK_TYPE_UMTS: 298 | case TelephonyManager.NETWORK_TYPE_EVDO_0: 299 | case TelephonyManager.NETWORK_TYPE_EVDO_A: 300 | case TelephonyManager.NETWORK_TYPE_HSDPA: 301 | case TelephonyManager.NETWORK_TYPE_HSUPA: 302 | case TelephonyManager.NETWORK_TYPE_HSPA: 303 | case TelephonyManager.NETWORK_TYPE_EVDO_B: 304 | case TelephonyManager.NETWORK_TYPE_EHRPD: 305 | case TelephonyManager.NETWORK_TYPE_HSPAP: 306 | return NetWorkType.Net3G; 307 | case TelephonyManager.NETWORK_TYPE_LTE: 308 | return NetWorkType.Net4G; 309 | default: 310 | return NetWorkType.UnKnown; 311 | } 312 | default: 313 | return NetWorkType.UnKnown; 314 | } 315 | } 316 | } -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/assist/TimeAverager.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.assist; 2 | 3 | 4 | /** 5 | * 时间均值计算器,只能用于单线程计时。 6 | * 7 | * @author MaTianyu 8 | * 2013-12-12上午1:23:19 9 | */ 10 | public class TimeAverager { 11 | /** 12 | * 计时器 13 | */ 14 | private TimeCounter tc = new TimeCounter(); 15 | /** 16 | * 均值器 17 | */ 18 | private Averager av = new Averager(); 19 | 20 | /** 21 | * 一个计时开始 22 | */ 23 | public long start() { 24 | return tc.start(); 25 | } 26 | 27 | /** 28 | * 一个计时结束 29 | */ 30 | public long end() { 31 | long time = tc.duration(); 32 | av.add(time); 33 | return time; 34 | } 35 | 36 | /** 37 | * 一个计时结束,并且启动下次计时。 38 | */ 39 | public long endAndRestart() { 40 | long time = tc.durationRestart(); 41 | av.add(time); 42 | return time; 43 | } 44 | 45 | /** 46 | * 求全部计时均值 47 | */ 48 | public Number average() { 49 | return av.getAverage(); 50 | } 51 | 52 | /** 53 | * 打印全部时间值 54 | */ 55 | public void print() { 56 | av.print(); 57 | } 58 | 59 | /** 60 | * 清楚数据 61 | */ 62 | public void clear() { 63 | av.clear(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/assist/TimeCounter.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.assist; 2 | 3 | import com.litesuits.android.log.Log; 4 | 5 | /** 6 | * Time Counter. 7 | * 8 | * @author MaTianyu 9 | * 2013-12-11下午3:42:28 10 | */ 11 | public class TimeCounter { 12 | 13 | private static final String TAG = TimeCounter.class.getSimpleName(); 14 | private long t; 15 | 16 | public TimeCounter() { 17 | start(); 18 | } 19 | 20 | /** 21 | * Count start. 22 | */ 23 | public long start() { 24 | t = System.currentTimeMillis(); 25 | return t; 26 | } 27 | 28 | /** 29 | * Get duration and restart. 30 | */ 31 | public long durationRestart() { 32 | long now = System.currentTimeMillis(); 33 | long d = now - t; 34 | t = now; 35 | return d; 36 | } 37 | 38 | /** 39 | * Get duration. 40 | */ 41 | public long duration() { 42 | return System.currentTimeMillis() - t; 43 | } 44 | 45 | /** 46 | * Print duration. 47 | */ 48 | public void printDuration(String tag) { 49 | Log.i(TAG, tag + " : " + duration()); 50 | } 51 | 52 | /** 53 | * Print duration. 54 | */ 55 | public void printDurationRestart(String tag) { 56 | Log.i(TAG, tag + " : " + durationRestart()); 57 | } 58 | } -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/assist/TimeKeeper.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.assist; 2 | 3 | import android.os.SystemClock; 4 | import com.litesuits.android.log.Log; 5 | 6 | /** 7 | * @author 氢一 @http://litesuits.com 8 | * @date 2017-05-27 9 | */ 10 | public class TimeKeeper { 11 | private static final String TAG = "TimeKeeper"; 12 | private long keepTimeMillis; 13 | private long startMillis; 14 | 15 | public TimeKeeper(long keepTimeMillis) { 16 | this.keepTimeMillis = keepTimeMillis; 17 | } 18 | 19 | public long getKeepTimeMillis() { 20 | return keepTimeMillis; 21 | } 22 | 23 | public TimeKeeper setKeepTimeMillis(long keepTimeMillis) { 24 | this.keepTimeMillis = keepTimeMillis; 25 | return this; 26 | } 27 | 28 | public TimeKeeper printTimeCost(String event) { 29 | long costMillis = SystemClock.elapsedRealtime() - startMillis; 30 | Log.d(TAG, event + " cost time millis: " + costMillis); 31 | return this; 32 | } 33 | 34 | public TimeKeeper startNow() { 35 | startMillis = SystemClock.elapsedRealtime(); 36 | return this; 37 | } 38 | 39 | public TimeKeeper waitForEnd(OnEndCallback endCallback) { 40 | long costMillis = SystemClock.elapsedRealtime() - startMillis; 41 | long leftMillis = keepTimeMillis - costMillis; 42 | if (leftMillis > 0) { 43 | SystemClock.sleep(leftMillis); 44 | endCallback.onEnd(costMillis, leftMillis); 45 | } else { 46 | endCallback.onEnd(costMillis, leftMillis); 47 | } 48 | return this; 49 | } 50 | 51 | public interface OnEndCallback { 52 | void onEnd(long costTime, long leftTime); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/assist/Toastor.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.assist; 2 | 3 | import android.content.Context; 4 | import android.widget.Toast; 5 | 6 | /** 7 | * @author MaTianyu 8 | * @date 2014-07-31 9 | */ 10 | public class Toastor { 11 | 12 | private Toast mToast; 13 | private Context context; 14 | 15 | public Toastor(Context context) { 16 | this.context = context.getApplicationContext(); 17 | } 18 | 19 | public Toast getSingletonToast(int resId) { 20 | if (mToast == null) { 21 | mToast = Toast.makeText(context, resId, Toast.LENGTH_SHORT); 22 | }else{ 23 | mToast.setText(resId); 24 | } 25 | return mToast; 26 | } 27 | 28 | public Toast getSingletonToast(String text) { 29 | if (mToast == null) { 30 | mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT); 31 | }else{ 32 | mToast.setText(text); 33 | } 34 | return mToast; 35 | } 36 | 37 | public Toast getSingleLongToast(int resId) { 38 | if (mToast == null) { 39 | mToast = Toast.makeText(context, resId, Toast.LENGTH_LONG); 40 | }else{ 41 | mToast.setText(resId); 42 | } 43 | return mToast; 44 | } 45 | 46 | public Toast getSingleLongToast(String text) { 47 | if (mToast == null) { 48 | mToast = Toast.makeText(context, text, Toast.LENGTH_LONG); 49 | }else{ 50 | mToast.setText(text); 51 | } 52 | return mToast; 53 | } 54 | 55 | public Toast getToast(int resId) { 56 | return Toast.makeText(context, resId, Toast.LENGTH_SHORT); 57 | } 58 | 59 | public Toast getToast(String text) { 60 | return Toast.makeText(context, text, Toast.LENGTH_SHORT); 61 | } 62 | 63 | public Toast getLongToast(int resId) { 64 | return Toast.makeText(context, resId, Toast.LENGTH_LONG); 65 | } 66 | 67 | public Toast getLongToast(String text) { 68 | return Toast.makeText(context, text, Toast.LENGTH_LONG); 69 | } 70 | 71 | public void showSingletonToast(int resId) { 72 | getSingletonToast(resId).show(); 73 | } 74 | 75 | 76 | public void showSingletonToast(String text) { 77 | getSingletonToast(text).show(); 78 | } 79 | 80 | public void showSingleLongToast(int resId) { 81 | getSingleLongToast(resId).show(); 82 | } 83 | 84 | 85 | public void showSingleLongToast(String text) { 86 | getSingleLongToast(text).show(); 87 | } 88 | 89 | public void showToast(int resId) { 90 | getToast(resId).show(); 91 | } 92 | 93 | public void showToast(String text) { 94 | getToast(text).show(); 95 | } 96 | 97 | public void showLongToast(int resId) { 98 | getLongToast(resId).show(); 99 | } 100 | 101 | public void showLongToast(String text) { 102 | getLongToast(text).show(); 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/assist/WakeLock.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.assist; 2 | 3 | import android.content.Context; 4 | import android.os.Build; 5 | import android.os.PowerManager; 6 | import com.litesuits.android.log.Log; 7 | 8 | /** 9 | * 10 | * require 11 | * 12 | * @author MaTianyu 13 | * @date 2014-11-04 14 | */ 15 | public class WakeLock { 16 | PowerManager powerManager; 17 | PowerManager.WakeLock wakeLock; 18 | 19 | public WakeLock(Context context, String tag) { 20 | ////获取电源的服务 声明电源管理器 21 | powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 22 | wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, tag); 23 | } 24 | 25 | /** 26 | * Call requires API level 7 27 | */ 28 | public boolean isScreenOn() { 29 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ECLAIR_MR1) { 30 | Log.e("Log : ", "can not call isScreenOn if SDK_INT < 7 "); 31 | return false; 32 | } else { 33 | return powerManager.isScreenOn(); 34 | } 35 | } 36 | 37 | public void turnScreenOn() { 38 | //点亮亮屏 39 | Log.i("Log : ", "PowerManager.WakeLock : wakeLock.isHeld: " + wakeLock.isHeld()); 40 | if (!wakeLock.isHeld()) { 41 | Log.i("Log : ", "PowerManager.WakeLock : 点亮屏幕"); 42 | wakeLock.acquire(); 43 | } 44 | } 45 | 46 | public void turnScreenOff() { 47 | //释放亮屏 48 | Log.i("Log : ", "PowerManager.WakeLock : wakeLock.isHeld: " + wakeLock.isHeld()); 49 | if (wakeLock.isHeld()) { 50 | Log.i("Log : ", "PowerManager.WakeLock : 灭掉屏幕"); 51 | try { 52 | wakeLock.release(); 53 | } catch (Exception e) { 54 | e.printStackTrace(); 55 | } 56 | } 57 | } 58 | 59 | public void release() { 60 | if (wakeLock != null && wakeLock.isHeld()) { 61 | try { 62 | wakeLock.release(); 63 | } catch (Exception e) { 64 | e.printStackTrace(); 65 | } 66 | } 67 | } 68 | 69 | public PowerManager.WakeLock getWakeLock() { 70 | return wakeLock; 71 | } 72 | 73 | public void setWakeLock(PowerManager.WakeLock wakeLock) { 74 | this.wakeLock = wakeLock; 75 | } 76 | 77 | public PowerManager getPowerManager() { 78 | return powerManager; 79 | } 80 | 81 | public void setPowerManager(PowerManager powerManager) { 82 | this.powerManager = powerManager; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/data/DataKeeper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 litesuits.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.litesuits.common.data; 17 | 18 | import android.content.Context; 19 | import android.content.SharedPreferences; 20 | import com.litesuits.android.log.Log; 21 | import com.litesuits.common.data.cipher.Cipher; 22 | import com.litesuits.common.utils.ByteUtil; 23 | import com.litesuits.common.utils.HexUtil; 24 | 25 | /** 26 | * @author MaTianyu 27 | * @date 14-7-10 28 | */ 29 | public class DataKeeper { 30 | private SharedPreferences sp; 31 | public static final String KEY_PK_HOME = "msg_pk_home"; 32 | public static final String KEY_PK_NEW = "msg_pk_new"; 33 | private static final String TAG = DataKeeper.class.getSimpleName(); 34 | 35 | public DataKeeper(Context context, String fileName) { 36 | sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE); 37 | } 38 | 39 | /** 40 | * *************** get ****************** 41 | */ 42 | 43 | public String get(String key, String defValue) { 44 | return sp.getString(key, defValue); 45 | } 46 | 47 | public boolean get(String key, boolean defValue) { 48 | return sp.getBoolean(key, defValue); 49 | } 50 | 51 | public float get(String key, float defValue) { 52 | return sp.getFloat(key, defValue); 53 | } 54 | 55 | public int getInt(String key, int defValue) { 56 | return sp.getInt(key, defValue); 57 | } 58 | 59 | public long get(String key, long defValue) { 60 | return sp.getLong(key, defValue); 61 | } 62 | 63 | public Object get(String key) { 64 | return get(key, (Cipher) null); 65 | } 66 | 67 | public Object get(String key, Cipher cipher) { 68 | try { 69 | String hex = get(key, (String) null); 70 | if (hex == null) return null; 71 | byte[] bytes = HexUtil.decodeHex(hex.toCharArray()); 72 | if (cipher != null) bytes = cipher.decrypt(bytes); 73 | Object obj = ByteUtil.byteToObject(bytes); 74 | Log.i(TAG, key + " get: " + obj); 75 | return obj; 76 | } catch (Exception e) { 77 | e.printStackTrace(); 78 | } 79 | return null; 80 | } 81 | 82 | /** 83 | * *************** put ****************** 84 | */ 85 | public void put(String key, Object ser) { 86 | put(key, ser, null); 87 | } 88 | 89 | public void put(String key, Object ser, Cipher cipher) { 90 | try { 91 | Log.i(TAG, key + " put: " + ser); 92 | if (ser == null) { 93 | sp.edit().remove(key).commit(); 94 | } else { 95 | byte[] bytes = ByteUtil.objectToByte(ser); 96 | if (cipher != null) bytes = cipher.encrypt(bytes); 97 | put(key, HexUtil.encodeHexStr(bytes)); 98 | } 99 | } catch (Exception e) { 100 | e.printStackTrace(); 101 | } 102 | } 103 | 104 | public void put(String key, String value) { 105 | if (value == null) { 106 | sp.edit().remove(key).commit(); 107 | } else { 108 | sp.edit().putString(key, value).commit(); 109 | } 110 | } 111 | 112 | public void put(String key, boolean value) { 113 | sp.edit().putBoolean(key, value).commit(); 114 | } 115 | 116 | public void put(String key, float value) { 117 | sp.edit().putFloat(key, value).commit(); 118 | } 119 | 120 | public void put(String key, long value) { 121 | sp.edit().putLong(key, value).commit(); 122 | } 123 | 124 | public void putInt(String key, int value) { 125 | sp.edit().putInt(key, value).commit(); 126 | } 127 | 128 | } 129 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/data/cipher/Base64Cipher.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.data.cipher; 2 | 3 | 4 | import com.litesuits.common.assist.Base64; 5 | 6 | /** 7 | * @author MaTianyu 8 | * @date 14-7-31 9 | */ 10 | public class Base64Cipher extends Cipher { 11 | private Cipher cipher; 12 | 13 | public Base64Cipher() { 14 | } 15 | 16 | public Base64Cipher(Cipher cipher) { 17 | this.cipher = cipher; 18 | } 19 | 20 | @Override 21 | public byte[] decrypt(byte[] res) { 22 | res = Base64.decode(res, Base64.DEFAULT); 23 | if (cipher != null) { 24 | res = cipher.decrypt(res); 25 | } 26 | return res; 27 | } 28 | 29 | @Override 30 | public byte[] encrypt(byte[] res) { 31 | if (cipher != null) { 32 | res = cipher.encrypt(res); 33 | } 34 | return Base64.encode(res, Base64.DEFAULT); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/data/cipher/Cipher.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.data.cipher; 2 | 3 | /** 4 | * @author MaTianyu 5 | * @date 14-7-31 6 | */ 7 | public abstract class Cipher implements Encrypt,Decrypt{ 8 | 9 | } 10 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/data/cipher/Decrypt.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.data.cipher; 2 | 3 | /** 4 | * @author MaTianyu 5 | * @date 14-7-31 6 | */ 7 | public interface Decrypt { 8 | public byte[] decrypt(byte[] res); 9 | } 10 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/data/cipher/Encrypt.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.data.cipher; 2 | 3 | /** 4 | * @author MaTianyu 5 | * @date 14-7-31 6 | */ 7 | public interface Encrypt { 8 | public byte[] encrypt(byte[] res); 9 | } 10 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/io/Charsets.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.litesuits.common.io; 18 | 19 | import java.nio.charset.Charset; 20 | 21 | /** 22 | * Charsets 23 | */ 24 | public class Charsets { 25 | public static Charset toCharset(Charset charset) { 26 | return charset == null ? Charset.defaultCharset() : charset; 27 | } 28 | public static Charset toCharset(String charset) { 29 | return charset == null ? Charset.defaultCharset() : Charset.forName(charset); 30 | } 31 | public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); 32 | public static final Charset US_ASCII = Charset.forName("US-ASCII"); 33 | public static final Charset UTF_16 = Charset.forName("UTF-16"); 34 | public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); 35 | public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); 36 | public static final Charset UTF_8 = Charset.forName("UTF-8"); 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/io/StringCodingUtils.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.io; 2 | 3 | import android.os.Build; 4 | 5 | import java.io.UnsupportedEncodingException; 6 | import java.nio.charset.Charset; 7 | 8 | /** 9 | * @author MaTianyu 10 | * @date 2014-12-05 11 | */ 12 | public class StringCodingUtils { 13 | 14 | public static byte[] getBytes(String src, Charset charSet) { 15 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { 16 | try { 17 | return src.getBytes(charSet.name()); 18 | } catch (UnsupportedEncodingException e) { 19 | e.printStackTrace(); 20 | } 21 | return null; 22 | } else { 23 | return src.getBytes(charSet); 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/io/stream/ClosedInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.litesuits.common.io.stream; 18 | 19 | import java.io.InputStream; 20 | 21 | /** 22 | * Closed input stream. This stream returns -1 to all attempts to read 23 | * something from the stream. 24 | *

25 | * Typically uses of this class include testing for corner cases in methods 26 | * that accept input streams and acting as a sentinel value instead of a 27 | * {@code null} input stream. 28 | * 29 | * @version $Id: ClosedInputStream.java 1307459 2012-03-30 15:11:44Z ggregory $ 30 | * @since 1.4 31 | */ 32 | public class ClosedInputStream extends InputStream { 33 | 34 | /** 35 | * A singleton. 36 | */ 37 | public static final ClosedInputStream CLOSED_INPUT_STREAM = new ClosedInputStream(); 38 | 39 | /** 40 | * Returns -1 to indicate that the stream is closed. 41 | * 42 | * @return always -1 43 | */ 44 | @Override 45 | public int read() { 46 | return -1; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/io/stream/StringBuilderWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.litesuits.common.io.stream; 18 | 19 | import java.io.Serializable; 20 | import java.io.Writer; 21 | 22 | /** 23 | * {@link java.io.Writer} implementation that outputs to a {@link StringBuilder}. 24 | *

25 | * NOTE: This implementation, as an alternative to 26 | * java.io.StringWriter, provides an un-synchronized 27 | * (i.e. for use in a single thread) implementation for better performance. 28 | * For safe usage with multiple {@link Thread}s then 29 | * java.io.StringWriter should be used. 30 | * 31 | * @version $Id: StringBuilderWriter.java 1304052 2012-03-22 20:55:29Z ggregory $ 32 | * @since 2.0 33 | */ 34 | public class StringBuilderWriter extends Writer implements Serializable { 35 | 36 | private final StringBuilder builder; 37 | 38 | /** 39 | * Construct a new {@link StringBuilder} instance with default capacity. 40 | */ 41 | public StringBuilderWriter() { 42 | this.builder = new StringBuilder(); 43 | } 44 | 45 | /** 46 | * Construct a new {@link StringBuilder} instance with the specified capacity. 47 | * 48 | * @param capacity The initial capacity of the underlying {@link StringBuilder} 49 | */ 50 | public StringBuilderWriter(int capacity) { 51 | this.builder = new StringBuilder(capacity); 52 | } 53 | 54 | /** 55 | * Construct a new instance with the specified {@link StringBuilder}. 56 | * 57 | * @param builder The String builder 58 | */ 59 | public StringBuilderWriter(StringBuilder builder) { 60 | this.builder = builder != null ? builder : new StringBuilder(); 61 | } 62 | 63 | /** 64 | * Append a single character to this Writer. 65 | * 66 | * @param value The character to append 67 | * @return This writer instance 68 | */ 69 | @Override 70 | public Writer append(char value) { 71 | builder.append(value); 72 | return this; 73 | } 74 | 75 | /** 76 | * Append a character sequence to this Writer. 77 | * 78 | * @param value The character to append 79 | * @return This writer instance 80 | */ 81 | @Override 82 | public Writer append(CharSequence value) { 83 | builder.append(value); 84 | return this; 85 | } 86 | 87 | /** 88 | * Append a portion of a character sequence to the {@link StringBuilder}. 89 | * 90 | * @param value The character to append 91 | * @param start The index of the first character 92 | * @param end The index of the last character + 1 93 | * @return This writer instance 94 | */ 95 | @Override 96 | public Writer append(CharSequence value, int start, int end) { 97 | builder.append(value, start, end); 98 | return this; 99 | } 100 | 101 | /** 102 | * Closing this writer has no effect. 103 | */ 104 | @Override 105 | public void close() { 106 | } 107 | 108 | /** 109 | * Flushing this writer has no effect. 110 | */ 111 | @Override 112 | public void flush() { 113 | } 114 | 115 | 116 | /** 117 | * Write a String to the {@link StringBuilder}. 118 | * 119 | * @param value The value to write 120 | */ 121 | @Override 122 | public void write(String value) { 123 | if (value != null) { 124 | builder.append(value); 125 | } 126 | } 127 | 128 | /** 129 | * Write a portion of a character array to the {@link StringBuilder}. 130 | * 131 | * @param value The value to write 132 | * @param offset The index of the first character 133 | * @param length The number of characters to write 134 | */ 135 | @Override 136 | public void write(char[] value, int offset, int length) { 137 | if (value != null) { 138 | builder.append(value, offset, length); 139 | } 140 | } 141 | 142 | /** 143 | * Return the underlying builder. 144 | * 145 | * @return The underlying builder 146 | */ 147 | public StringBuilder getBuilder() { 148 | return builder; 149 | } 150 | 151 | /** 152 | * Returns {@link StringBuilder#toString()}. 153 | * 154 | * @return The contents of the String builder. 155 | */ 156 | @Override 157 | public String toString() { 158 | return builder.toString(); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/receiver/PhoneReceiver.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.receiver; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.IntentFilter; 7 | import android.os.Bundle; 8 | import com.litesuits.android.log.Log; 9 | import com.litesuits.common.assist.Check; 10 | 11 | /** 12 | * 13 | * 14 | *

15 | * action: android.intent.action.PHONE_STATE; android.intent.action.NEW_OUTGOING_CALL; 16 | *

17 | * 去电时: 18 | * 未接:phone_state=OFFHOOK; 19 | * 挂断:phone_state=IDLE 20 | * 来电时: 21 | * 未接:phone_state=RINGING 22 | * 已接:phone_state=OFFHOOK; 23 | * 挂断:phone_state=IDLE 24 | * 25 | * @author MaTianyu 26 | * @date 2015-03-09 27 | */ 28 | public class PhoneReceiver extends BroadcastReceiver { 29 | 30 | private static final String TAG = "PhoneReceiver"; 31 | 32 | private static final String RINGING = "RINGING"; 33 | private static final String OFFHOOK = "OFFHOOK"; 34 | private static final String IDLE = "IDLE"; 35 | 36 | private static final String PHONE_STATE = "android.intent.action.PHONE_STATE"; 37 | private static final String NEW_OUTGOING_CALL = "android.intent.action.NEW_OUTGOING_CALL"; 38 | private static final String INTENT_STATE = "state"; 39 | private static final String INTENT_INCOMING_NUMBER = "incoming_number"; 40 | private PhoneListener phoneListener; 41 | private boolean isDialOut; 42 | private String number; 43 | 44 | @Override 45 | public void onReceive(Context context, Intent intent) { 46 | if (Log.isPrint) { 47 | Log.i(TAG, "action: " + intent.getAction()); 48 | Log.d(TAG, "intent : "); 49 | Bundle bundle = intent.getExtras(); 50 | for (String key : bundle.keySet()) { 51 | Log.d(TAG, key + " : " + bundle.get(key)); 52 | } 53 | } 54 | if (NEW_OUTGOING_CALL.equals(intent.getAction())) { 55 | isDialOut = true; 56 | String outNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); 57 | if (!Check.isEmpty(outNumber)) { 58 | this.number = outNumber; 59 | } 60 | if (phoneListener != null) { 61 | phoneListener.onPhoneStateChanged(CallState.Outgoing, number); 62 | } 63 | } else if (PHONE_STATE.equals(intent.getAction())) { 64 | String state = intent.getStringExtra(INTENT_STATE); 65 | String inNumber = intent.getStringExtra(INTENT_INCOMING_NUMBER); 66 | if (!Check.isEmpty(inNumber)) { 67 | this.number = inNumber; 68 | } 69 | if (RINGING.equals(state)) { 70 | isDialOut = false; 71 | if (phoneListener != null) { 72 | phoneListener.onPhoneStateChanged(CallState.IncomingRing, number); 73 | } 74 | } else if (OFFHOOK.equals(state)) { 75 | if (!isDialOut && phoneListener != null) { 76 | phoneListener.onPhoneStateChanged(CallState.Incoming, number); 77 | } 78 | } else if (IDLE.equals(state)) { 79 | if (isDialOut) { 80 | if (phoneListener != null) { 81 | phoneListener.onPhoneStateChanged(CallState.OutgoingEnd, number); 82 | } 83 | } else { 84 | if (phoneListener != null) { 85 | phoneListener.onPhoneStateChanged(CallState.IncomingEnd, number); 86 | } 87 | } 88 | } 89 | } 90 | } 91 | 92 | /** 93 | * 去电时: 94 | * 未接:phone_state=OFFHOOK; 95 | * 挂断:phone_state=IDLE 96 | * 来电时: 97 | * 未接:phone_state=RINGING 98 | * 已接:phone_state=OFFHOOK; 99 | * 挂断:phone_state=IDLE 100 | */ 101 | //public void registerCallStateListener(Context context, PhoneStateListener listener) { 102 | // try { 103 | // //获取电话通讯服务 104 | // TelephonyManager tpm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 105 | // tpm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); 106 | // } catch (Exception e) { 107 | // e.printStackTrace(); 108 | // } 109 | //} 110 | public void registerReceiver(Context context, PhoneListener phoneListener) { 111 | try { 112 | IntentFilter filter = new IntentFilter(); 113 | filter.addAction("android.intent.action.PHONE_STATE"); 114 | filter.addAction("android.intent.action.NEW_OUTGOING_CALL"); 115 | filter.setPriority(Integer.MAX_VALUE); 116 | context.registerReceiver(this, filter); 117 | this.phoneListener = phoneListener; 118 | } catch (Exception e) { 119 | e.printStackTrace(); 120 | } 121 | } 122 | 123 | public void unRegisterReceiver(Context context) { 124 | try { 125 | context.unregisterReceiver(this); 126 | } catch (Exception e) { 127 | e.printStackTrace(); 128 | } 129 | } 130 | 131 | public interface PhoneListener { 132 | void onPhoneStateChanged(CallState state, String number); 133 | } 134 | 135 | /** 136 | * 分别是: 137 | *

138 | * 播出电话 139 | * 播出电话结束 140 | * 接入电话铃响 141 | * 接入通话中 142 | * 接入通话完毕 143 | */ 144 | public enum CallState { 145 | Outgoing, 146 | OutgoingEnd, 147 | IncomingRing, 148 | Incoming, 149 | IncomingEnd 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/receiver/ScreenReceiver.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.receiver; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.IntentFilter; 7 | import com.litesuits.android.log.Log; 8 | 9 | public class ScreenReceiver extends BroadcastReceiver { 10 | private String TAG = "ScreenActionReceiver"; 11 | private ScreenListener screenListener; 12 | 13 | public ScreenReceiver() { 14 | 15 | } 16 | 17 | @Override 18 | public void onReceive(Context context, Intent intent) { 19 | String action = intent.getAction(); 20 | if (action.equals(Intent.ACTION_SCREEN_ON)) { 21 | Log.d(TAG, "屏幕解锁广播..."); 22 | if (screenListener != null) { 23 | screenListener.screenOn(); 24 | } 25 | } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { 26 | Log.d(TAG, "屏幕加锁广播..."); 27 | if (screenListener != null) { 28 | screenListener.screenOff(); 29 | } 30 | } 31 | } 32 | 33 | public void registerScreenReceiver(Context context, ScreenListener screenListener) { 34 | try { 35 | this.screenListener = screenListener; 36 | IntentFilter filter = new IntentFilter(); 37 | filter.addAction(Intent.ACTION_SCREEN_OFF); 38 | filter.addAction(Intent.ACTION_SCREEN_ON); 39 | Log.d(TAG, "注册屏幕解锁、加锁广播接收者..."); 40 | context.registerReceiver(this, filter); 41 | } catch (Exception e) { 42 | e.printStackTrace(); 43 | } 44 | } 45 | 46 | public void unRegisterScreenReceiver(Context context) { 47 | try { 48 | context.unregisterReceiver(this); 49 | Log.d(TAG, "注销屏幕解锁、加锁广播接收者..."); 50 | } catch (Exception e) { 51 | e.printStackTrace(); 52 | } 53 | } 54 | 55 | public static interface ScreenListener { 56 | public void screenOn(); 57 | 58 | public void screenOff(); 59 | } 60 | 61 | } -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/receiver/SmsReceiver.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.receiver; 2 | 3 | import android.content.*; 4 | import android.net.Uri; 5 | import android.os.Build; 6 | import android.os.Bundle; 7 | import android.telephony.SmsManager; 8 | import android.telephony.SmsMessage; 9 | import com.litesuits.android.log.Log; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * Call requires API level 4 15 | * 16 | *

17 | * action: android.provider.Telephony.SMS_RECEIVED 18 | * 19 | * @author MaTianyu 20 | * @date 14-7-23 21 | */ 22 | public class SmsReceiver extends BroadcastReceiver { 23 | private static final String TAG = SmsReceiver.class.getSimpleName(); 24 | private SmsListener smsListener; 25 | 26 | public SmsReceiver() { 27 | 28 | } 29 | 30 | @Override 31 | public void onReceive(Context context, Intent intent) { 32 | try { 33 | if (Log.isPrint) { 34 | Log.i(TAG, "收到广播:" + intent.getAction()); 35 | Bundle bundle = intent.getExtras(); 36 | for (String key : bundle.keySet()) { 37 | Log.i(TAG, key + " : " + bundle.get(key)); 38 | } 39 | } 40 | Object[] pdus = (Object[]) intent.getExtras().get("pdus"); 41 | String fromAddress = null; 42 | String serviceCenterAddress = null; 43 | if (pdus != null) { 44 | String msgBody = ""; 45 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) { 46 | for (Object obj : pdus) { 47 | SmsMessage sms = SmsMessage.createFromPdu((byte[]) obj); 48 | msgBody += sms.getMessageBody(); 49 | fromAddress = sms.getOriginatingAddress(); 50 | serviceCenterAddress = sms.getServiceCenterAddress(); 51 | 52 | if (smsListener != null) { 53 | smsListener.onMessage(sms); 54 | } 55 | //Log.i(TAG, "getDisplayMessageBody:" + sms.getDisplayMessageBody()); 56 | //Log.i(TAG, "getDisplayOriginatingAddress:" + sms.getDisplayOriginatingAddress()); 57 | //Log.i(TAG, "getEmailBody:" + sms.getEmailBody()); 58 | //Log.i(TAG, "getEmailFrom:" + sms.getEmailFrom()); 59 | //Log.i(TAG, "getMessageBody:" + sms.getMessageBody()); 60 | //Log.i(TAG, "getOriginatingAddress:" + sms.getOriginatingAddress()); 61 | //Log.i(TAG, "getPseudoSubject:" + sms.getPseudoSubject()); 62 | //Log.i(TAG, "getServiceCenterAddress:" + sms.getServiceCenterAddress()); 63 | //Log.i(TAG, "getIndexOnIcc:" + sms.getIndexOnIcc()); 64 | //Log.i(TAG, "getMessageClass:" + sms.getMessageClass()); 65 | //Log.i(TAG, "getUserData:" + new String(sms.getUserData())); 66 | } 67 | } 68 | if (smsListener != null) { 69 | smsListener.onMessage(msgBody, fromAddress, serviceCenterAddress); 70 | } 71 | } 72 | } catch (Exception e) { 73 | e.printStackTrace(); 74 | } 75 | } 76 | 77 | public void registerSmsReceiver(Context context, SmsListener smsListener) { 78 | try { 79 | this.smsListener = smsListener; 80 | IntentFilter filter = new IntentFilter(); 81 | filter.addAction("android.provider.Telephony.SMS_RECEIVED"); 82 | filter.setPriority(Integer.MAX_VALUE); 83 | context.registerReceiver(this, filter); 84 | } catch (Exception e) { 85 | e.printStackTrace(); 86 | } 87 | } 88 | 89 | public void unRegisterSmsReceiver(Context context) { 90 | try { 91 | context.unregisterReceiver(this); 92 | } catch (Exception e) { 93 | e.printStackTrace(); 94 | } 95 | } 96 | 97 | public static abstract class SmsListener { 98 | public abstract void onMessage(String msg, String fromAddress, String serviceCenterAddress); 99 | 100 | public void onMessage(SmsMessage msg) {} 101 | } 102 | 103 | /** 104 | * Call requires API level 4 105 | * 106 | * 107 | * @param phone 108 | * @param msg 109 | */ 110 | public static void sendMsgToPhone(String phone, String msg) { 111 | Log.i(TAG, "发送手机:" + phone + " ,内容: " + msg); 112 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) { 113 | SmsManager manager = SmsManager.getDefault(); 114 | List texts = manager.divideMessage(msg); 115 | for (String txt : texts) { 116 | manager.sendTextMessage(phone, null, txt, null, null); 117 | } 118 | }else{ 119 | Log.e(TAG, "发送失败,系统版本低于DONUT," + phone + " ,内容: " + msg); 120 | } 121 | 122 | } 123 | 124 | /** 125 | * Call requires API level 4 126 | * 127 | * 128 | * @param context 129 | * @param phone 130 | * @param msg 131 | */ 132 | public static void saveMsgToSystem(Context context, String phone, String msg) { 133 | ContentValues values = new ContentValues(); 134 | values.put("date", System.currentTimeMillis()); 135 | //阅读状态  136 | values.put("read", 0); 137 | //1为收 2为发   138 | values.put("type", 2); 139 | values.put("address", phone); 140 | values.put("body", msg); 141 | context.getContentResolver().insert(Uri.parse("content://sms/inbox"), values); 142 | } 143 | 144 | } 145 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/receiver/TimeReceiver.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.receiver; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.IntentFilter; 7 | import android.os.Bundle; 8 | import com.litesuits.android.log.Log; 9 | 10 | /** 11 | * 时间广播 12 | * 13 | * @author MaTianyu 14 | * @date 2015-03-09 15 | */ 16 | public class TimeReceiver extends BroadcastReceiver { 17 | 18 | private static final String TAG = "TimeReceiver"; 19 | 20 | private TimeListener timeListener; 21 | 22 | @Override 23 | public void onReceive(Context context, Intent intent) { 24 | if (Log.isPrint) { 25 | Log.i(TAG, "action: " + intent.getAction()); 26 | Log.d(TAG, "intent : "); 27 | Bundle bundle = intent.getExtras(); 28 | for (String key : bundle.keySet()) { 29 | Log.d(TAG, key + " : " + bundle.get(key)); 30 | } 31 | } 32 | if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) { 33 | if (timeListener != null) { 34 | timeListener.onTimeTick(); 35 | } 36 | } else if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) { 37 | if (timeListener != null) { 38 | timeListener.onTimeChanged(); 39 | } 40 | } else if (Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) { 41 | if (timeListener != null) { 42 | timeListener.onTimeZoneChanged(); 43 | } 44 | } 45 | } 46 | 47 | public void registerReceiver(Context context, TimeListener timeListener) { 48 | try { 49 | IntentFilter filter = new IntentFilter(); 50 | filter.addAction(Intent.ACTION_TIME_CHANGED); 51 | filter.addAction(Intent.ACTION_TIME_TICK); 52 | filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); 53 | filter.setPriority(Integer.MAX_VALUE); 54 | context.registerReceiver(this, filter); 55 | this.timeListener = timeListener; 56 | } catch (Exception e) { 57 | e.printStackTrace(); 58 | } 59 | } 60 | 61 | public void unRegisterReceiver(Context context) { 62 | try { 63 | context.unregisterReceiver(this); 64 | } catch (Exception e) { 65 | e.printStackTrace(); 66 | } 67 | } 68 | 69 | public static interface TimeListener { 70 | /** 71 | * 时区改变 72 | */ 73 | public void onTimeZoneChanged(); 74 | 75 | /** 76 | * 设置时间 77 | */ 78 | public void onTimeChanged(); 79 | 80 | /** 81 | * 每分钟调用 82 | */ 83 | public void onTimeTick(); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/service/NotificationService.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.service; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.Activity; 5 | import android.app.Notification; 6 | import android.content.ComponentName; 7 | import android.content.Context; 8 | import android.content.Intent; 9 | import android.os.Build; 10 | import android.os.Bundle; 11 | import android.provider.Settings; 12 | import android.service.notification.NotificationListenerService; 13 | import android.service.notification.StatusBarNotification; 14 | import android.text.TextUtils; 15 | import com.litesuits.android.log.Log; 16 | 17 | /** 18 | * note: VERSION_CODE >= API_18 19 | *

20 | * manifest: 21 | * 24 | * 25 | * 26 | * 27 | * 28 | * 29 | * @author MaTianyu 30 | * @date 2015-03-09 31 | */ 32 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 33 | public class NotificationService extends NotificationListenerService { 34 | private static final String TAG = "NotificationService"; 35 | public static final String ACTION_NOTIFICATION_LISTENER_SETTINGS = "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"; 36 | private static final String ENABLED_NOTIFICATION_LISTENERS = "enabled_notification_listeners"; 37 | private static NotificationService self; 38 | private static NotificationListener notificationListener; 39 | 40 | /*----------------- 静态方法 -----------------*/ 41 | public synchronized static void startNotificationService(Context context, NotificationListener notificationListener) { 42 | NotificationService.notificationListener = notificationListener; 43 | context.startService(new Intent(context, NotificationService.class)); 44 | } 45 | 46 | public synchronized static void stopNotificationService(Context context) { 47 | context.stopService(new Intent(context, NotificationService.class)); 48 | } 49 | 50 | 51 | public static void startNotificationListenSettings(Context context) { 52 | Intent intent = new Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS); 53 | if(!(context instanceof Activity)) { 54 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 55 | } 56 | context.startActivity(intent); 57 | } 58 | 59 | public static boolean isNotificationListenEnable(Context context) { 60 | return isNotificationListenEnable(context, context.getPackageName()); 61 | } 62 | 63 | public static boolean isNotificationListenEnable(Context context, String pkgName) { 64 | final String flat = Settings.Secure.getString(context.getContentResolver(), ENABLED_NOTIFICATION_LISTENERS); 65 | if (!TextUtils.isEmpty(flat)) { 66 | final String[] names = flat.split(":"); 67 | for (int i = 0; i < names.length; i++) { 68 | final ComponentName cn = ComponentName.unflattenFromString(names[i]); 69 | if (cn != null) { 70 | if (TextUtils.equals(pkgName, cn.getPackageName())) { 71 | return true; 72 | } 73 | } 74 | } 75 | } 76 | return false; 77 | } 78 | 79 | /*----------------- 生命周期 -----------------*/ 80 | @Override 81 | public void onCreate() { 82 | super.onCreate(); 83 | Log.i(TAG, "onCreate.."); 84 | 85 | if (notificationListener != null) { 86 | notificationListener.onServiceCreated(this); 87 | } 88 | self = this; 89 | } 90 | 91 | @Override 92 | public int onStartCommand(Intent intent, int flags, int startId) { 93 | Log.i(TAG, "onStartCommand.."); 94 | 95 | return notificationListener == null ? START_STICKY : notificationListener.onServiceStartCommand(this, intent, flags, startId); 96 | } 97 | 98 | @Override 99 | public void onDestroy() { 100 | super.onDestroy(); 101 | Log.i(TAG, "onDestroy.."); 102 | 103 | if (notificationListener != null) { 104 | notificationListener.onServiceDestroy(); 105 | notificationListener = null; 106 | } 107 | self = null; 108 | } 109 | 110 | /*----------------- 通知回调 -----------------*/ 111 | @Override 112 | public void onNotificationPosted(StatusBarNotification sbn) { 113 | if (Log.isPrint) { 114 | Log.i(TAG, sbn.toString()); 115 | Notification notification = sbn.getNotification(); 116 | Log.i(TAG, "tickerText : " + notification.tickerText); 117 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 118 | Bundle bundle = notification.extras; 119 | for (String key : bundle.keySet()) { 120 | Log.i(TAG, key + ": " + bundle.get(key)); 121 | } 122 | } 123 | } 124 | if (self != null && notificationListener != null) { 125 | notificationListener.onNotificationPosted(sbn); 126 | } 127 | } 128 | 129 | 130 | @Override 131 | public void onNotificationRemoved(StatusBarNotification sbn) { 132 | if (self != null && notificationListener != null) { 133 | notificationListener.onNotificationRemoved(sbn); 134 | } 135 | } 136 | 137 | public void printCurrentNotifications() { 138 | StatusBarNotification[] ns = getActiveNotifications(); 139 | for (StatusBarNotification n : ns) { 140 | Log.i(TAG, String.format("%20s",n.getPackageName()) + ": " + n.getNotification().tickerText); 141 | } 142 | } 143 | 144 | 145 | public static abstract class NotificationListener { 146 | public void onServiceCreated(NotificationService service) {} 147 | 148 | public abstract int onServiceStartCommand(NotificationService service, Intent intent, int flags, int startId); 149 | 150 | public void onServiceDestroy() {} 151 | 152 | /** 153 | * Implement this method to learn about new notifications as they are posted by apps. 154 | * 155 | * @param sbn A data structure encapsulating the original {@link android.app.Notification} 156 | * object as well as its identifying information (tag and id) and source 157 | * (package name). 158 | */ 159 | public abstract void onNotificationPosted(StatusBarNotification sbn); 160 | 161 | /** 162 | * Implement this method to learn when notifications are removed. 163 | *

164 | * This might occur because the user has dismissed the notification using system UI (or another 165 | * notification listener) or because the app has withdrawn the notification. 166 | *

167 | * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the 168 | * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight 169 | * fields such as {@link android.app.Notification#contentView} and 170 | * {@link android.app.Notification#largeIcon}. However, all other fields on 171 | * {@link StatusBarNotification}, sufficient to match this call with a prior call to 172 | * {@link #onNotificationPosted(StatusBarNotification)}, will be intact. 173 | * 174 | * @param sbn A data structure encapsulating at least the original information (tag and id) 175 | * and source (package name) used to post the {@link android.app.Notification} that 176 | * was just removed. 177 | */ 178 | public abstract void onNotificationRemoved(StatusBarNotification sbn); 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/AlarmUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.AlarmManager; 5 | import android.app.PendingIntent; 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.os.Build; 9 | 10 | /** 11 | * @author MaTianyu @http://litesuits.com 12 | * @date 2015-08-22 13 | */ 14 | public class AlarmUtil { 15 | /** 16 | * 开启定时器 17 | */ 18 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 19 | public static void startAlarmIntent(Context context, int triggerAtMillis, PendingIntent pendingIntent) { 20 | AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 21 | manager.set(AlarmManager.RTC_WAKEUP,triggerAtMillis, pendingIntent); 22 | } 23 | 24 | /** 25 | * 关闭定时器 26 | */ 27 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 28 | public static void stopAlarmIntent(Context context, PendingIntent pendingIntent) { 29 | AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 30 | manager.cancel(pendingIntent); 31 | } 32 | 33 | /** 34 | * 开启轮询服务 35 | */ 36 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 37 | public static void startAlarmService(Context context, int triggerAtMillis, Class cls, String action) { 38 | Intent intent = new Intent(context, cls); 39 | intent.setAction(action); 40 | PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 41 | startAlarmIntent(context, triggerAtMillis,pendingIntent); 42 | } 43 | 44 | /** 45 | * 停止启轮询服务 46 | */ 47 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 48 | public static void stopAlarmService(Context context, Class cls, String action) { 49 | Intent intent = new Intent(context, cls); 50 | intent.setAction(action); 51 | PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 52 | stopAlarmIntent(context, pendingIntent); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/AndroidUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.content.Context; 4 | import android.net.wifi.WifiInfo; 5 | import android.net.wifi.WifiManager; 6 | import android.os.Build; 7 | import android.os.SystemClock; 8 | import android.provider.Settings; 9 | 10 | import com.litesuits.android.log.Log; 11 | import com.litesuits.common.io.FileUtils; 12 | 13 | import java.io.File; 14 | import java.io.IOException; 15 | import java.text.SimpleDateFormat; 16 | import java.util.Date; 17 | 18 | /** 19 | * 手机信息 & MAC地址 & 开机时间 20 | * 21 | * @author MaTianyu 22 | * @date 2014-09-25 23 | */ 24 | public class AndroidUtil { 25 | private static final String TAG = AndroidUtil.class.getSimpleName(); 26 | //Ethernet Mac Address 27 | private static final String ETH0_MAC_ADDRESS = "/sys/class/net/eth0/address"; 28 | 29 | /** 30 | * 获取 Wifi MAC 地址 31 | * 32 | */ 33 | @Deprecated 34 | public static String getMacAddress(Context context) { 35 | return getWifiMacAddress(context); 36 | } 37 | 38 | /** 39 | * 获取 Wifi MAC 地址 40 | * 41 | */ 42 | public static String getWifiMacAddress(Context context) { 43 | //wifi mac地址 44 | WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 45 | WifiInfo info = wifi.getConnectionInfo(); 46 | String mac = info.getMacAddress(); 47 | if (Log.isPrint) { 48 | Log.i(TAG, "WIFI MAC:" + mac); 49 | } 50 | return mac; 51 | } 52 | 53 | 54 | /** 55 | * 获取 以太网 MAC 地址 56 | */ 57 | public static String getEthernetMacAddress() { 58 | try { 59 | String mac = FileUtils.readFileToString(new File(ETH0_MAC_ADDRESS)); 60 | if (Log.isPrint) { 61 | Log.i(TAG, "Ethernet MAC:" + mac); 62 | } 63 | return mac; 64 | } catch (IOException e) { 65 | Log.e(TAG, "IO Exception when getting eth0 mac address", e); 66 | e.printStackTrace(); 67 | return "unknown"; 68 | } 69 | } 70 | 71 | /** 72 | * 获取 ANDROID_ID 73 | */ 74 | public static String getAndroidId(Context context) { 75 | String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); 76 | if (Log.isPrint) { 77 | Log.i(TAG, "ANDROID_ID :" + androidId); 78 | } 79 | return androidId; 80 | } 81 | 82 | /** 83 | * 获取 开机时间 84 | */ 85 | public static String getBootTimeString() { 86 | long ut = SystemClock.elapsedRealtime() / 1000; 87 | int h = (int) ((ut / 3600)); 88 | int m = (int) ((ut / 60) % 60); 89 | if (Log.isPrint) { 90 | Log.i(TAG, h + ":" + m); 91 | } 92 | return h + ":" + m; 93 | } 94 | 95 | public static String printSystemInfo() { 96 | Date date = new Date(System.currentTimeMillis()); 97 | SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 98 | String time = dateFormat.format(date); 99 | StringBuilder sb = new StringBuilder(); 100 | sb.append("_______ 系统信息 ").append(time).append(" ______________"); 101 | sb.append("\nID :").append(Build.ID); 102 | sb.append("\nBRAND :").append(Build.BRAND); 103 | sb.append("\nMODEL :").append(Build.MODEL); 104 | sb.append("\nRELEASE :").append(Build.VERSION.RELEASE); 105 | sb.append("\nSDK :").append(Build.VERSION.SDK); 106 | 107 | sb.append("\n_______ OTHER _______"); 108 | sb.append("\nBOARD :").append(Build.BOARD); 109 | sb.append("\nPRODUCT :").append(Build.PRODUCT); 110 | sb.append("\nDEVICE :").append(Build.DEVICE); 111 | sb.append("\nFINGERPRINT :").append(Build.FINGERPRINT); 112 | sb.append("\nHOST :").append(Build.HOST); 113 | sb.append("\nTAGS :").append(Build.TAGS); 114 | sb.append("\nTYPE :").append(Build.TYPE); 115 | sb.append("\nTIME :").append(Build.TIME); 116 | sb.append("\nINCREMENTAL :").append(Build.VERSION.INCREMENTAL); 117 | 118 | sb.append("\n_______ CUPCAKE-3 _______"); 119 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) { 120 | sb.append("\nDISPLAY :").append(Build.DISPLAY); 121 | } 122 | 123 | sb.append("\n_______ DONUT-4 _______"); 124 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) { 125 | sb.append("\nSDK_INT :").append(Build.VERSION.SDK_INT); 126 | sb.append("\nMANUFACTURER :").append(Build.MANUFACTURER); 127 | sb.append("\nBOOTLOADER :").append(Build.BOOTLOADER); 128 | sb.append("\nCPU_ABI :").append(Build.CPU_ABI); 129 | sb.append("\nCPU_ABI2 :").append(Build.CPU_ABI2); 130 | sb.append("\nHARDWARE :").append(Build.HARDWARE); 131 | sb.append("\nUNKNOWN :").append(Build.UNKNOWN); 132 | sb.append("\nCODENAME :").append(Build.VERSION.CODENAME); 133 | } 134 | 135 | sb.append("\n_______ GINGERBREAD-9 _______"); 136 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { 137 | sb.append("\nSERIAL :").append(Build.SERIAL); 138 | } 139 | Log.i(TAG, sb.toString()); 140 | return sb.toString(); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/AppUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.app.ActivityManager; 4 | import android.content.ComponentName; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.content.pm.PackageInfo; 8 | import android.content.pm.PackageManager; 9 | import android.os.Process; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * @author MaTianyu 15 | * @date 2014-12-10 16 | */ 17 | public class AppUtil { 18 | 19 | /** 20 | * 是否是主进程 21 | */ 22 | public static boolean isMainProcess(Context context) { 23 | String procName = getCurrentProcessName(context); 24 | return procName == null || procName.equalsIgnoreCase(context.getPackageName()); 25 | } 26 | 27 | /** 28 | * 获取当前进程名字 29 | */ 30 | public static String getCurrentProcessName(Context context) { 31 | int pid = android.os.Process.myPid(); 32 | ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 33 | for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) { 34 | if (appProcess.pid == pid) { 35 | return appProcess.processName; 36 | } 37 | } 38 | return null; 39 | } 40 | 41 | /** 42 | * 调用系统分享 43 | */ 44 | public static void shareToOtherApp(Context context, String title, String content, String dialogTitle) { 45 | Intent intentItem = new Intent(Intent.ACTION_SEND); 46 | intentItem.setType("text/plain"); 47 | intentItem.putExtra(Intent.EXTRA_SUBJECT, title); 48 | intentItem.putExtra(Intent.EXTRA_TEXT, content); 49 | intentItem.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 50 | context.startActivity(Intent.createChooser(intentItem, dialogTitle)); 51 | } 52 | 53 | /** 54 | * need < uses-permission android:name =“android.permission.GET_TASKS” /> 55 | * 判断是否前台运行 56 | */ 57 | public static boolean isRunningForeground(Context context) { 58 | ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 59 | List taskList = am.getRunningTasks(1); 60 | if (taskList != null && !taskList.isEmpty()) { 61 | ComponentName componentName = taskList.get(0).topActivity; 62 | if (componentName != null && componentName.getPackageName().equals(context.getPackageName())) { 63 | return true; 64 | } 65 | } 66 | return false; 67 | } 68 | 69 | /** 70 | * 获取App包 信息版本号 71 | */ 72 | public PackageInfo getPackageInfo(Context context) { 73 | PackageManager packageManager = context.getPackageManager(); 74 | PackageInfo packageInfo = null; 75 | try { 76 | packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0); 77 | } catch (PackageManager.NameNotFoundException e) { 78 | e.printStackTrace(); 79 | } 80 | return packageInfo; 81 | } 82 | 83 | public static void killTheApp() { 84 | android.os.Process.killProcess(Process.myPid()); 85 | System.exit(0); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/BitmapUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.content.Intent; 4 | import android.graphics.*; 5 | import android.graphics.drawable.BitmapDrawable; 6 | import android.graphics.drawable.Drawable; 7 | import android.net.Uri; 8 | import android.os.Build; 9 | import android.provider.MediaStore; 10 | import com.litesuits.android.log.Log; 11 | import com.litesuits.common.assist.Base64; 12 | 13 | import java.io.ByteArrayOutputStream; 14 | import java.io.File; 15 | import java.io.FileOutputStream; 16 | import java.io.IOException; 17 | 18 | public class BitmapUtil { 19 | 20 | private static final String TAG = BitmapUtil.class.getSimpleName(); 21 | 22 | /** 23 | * convert Bitmap to byte array 24 | */ 25 | public static byte[] bitmapToByte(Bitmap b) { 26 | ByteArrayOutputStream o = new ByteArrayOutputStream(); 27 | b.compress(Bitmap.CompressFormat.PNG, 100, o); 28 | return o.toByteArray(); 29 | } 30 | 31 | /** 32 | * convert byte array to Bitmap 33 | */ 34 | public static Bitmap byteToBitmap(byte[] b) { 35 | return (b == null || b.length == 0) ? null : BitmapFactory.decodeByteArray(b, 0, b.length); 36 | } 37 | 38 | /** 39 | * 把bitmap转换成Base64编码String 40 | */ 41 | public static String bitmapToString(Bitmap bitmap) { 42 | return Base64.encodeToString(bitmapToByte(bitmap), Base64.DEFAULT); 43 | } 44 | 45 | /** 46 | * convert Drawable to Bitmap 47 | */ 48 | public static Bitmap drawableToBitmap(Drawable drawable) { 49 | return drawable == null ? null : ((BitmapDrawable) drawable).getBitmap(); 50 | } 51 | 52 | /** 53 | * convert Bitmap to Drawable 54 | */ 55 | public static Drawable bitmapToDrawable(Bitmap bitmap) { 56 | return bitmap == null ? null : new BitmapDrawable(bitmap); 57 | } 58 | 59 | /** 60 | * scale image 61 | */ 62 | public static Bitmap scaleImageTo(Bitmap org, int newWidth, int newHeight) { 63 | return scaleImage(org, (float) newWidth / org.getWidth(), (float) newHeight / org.getHeight()); 64 | } 65 | 66 | /** 67 | * scale image 68 | */ 69 | public static Bitmap scaleImage(Bitmap org, float scaleWidth, float scaleHeight) { 70 | if (org == null) { 71 | return null; 72 | } 73 | Matrix matrix = new Matrix(); 74 | matrix.postScale(scaleWidth, scaleHeight); 75 | return Bitmap.createBitmap(org, 0, 0, org.getWidth(), org.getHeight(), matrix, true); 76 | } 77 | 78 | public static Bitmap toRoundCorner(Bitmap bitmap) { 79 | int height = bitmap.getHeight(); 80 | int width = bitmap.getHeight(); 81 | Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 82 | 83 | Canvas canvas = new Canvas(output); 84 | 85 | final Paint paint = new Paint(); 86 | final Rect rect = new Rect(0, 0, width, height); 87 | 88 | paint.setAntiAlias(true); 89 | canvas.drawARGB(0, 0, 0, 0); 90 | //paint.setColor(0xff424242); 91 | paint.setColor(Color.TRANSPARENT); 92 | canvas.drawCircle(width / 2, height / 2, width / 2, paint); 93 | paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); 94 | canvas.drawBitmap(bitmap, rect, rect, paint); 95 | return output; 96 | } 97 | 98 | public static Bitmap createBitmapThumbnail(Bitmap bitMap, boolean needRecycle, int newHeight, int newWidth) { 99 | int width = bitMap.getWidth(); 100 | int height = bitMap.getHeight(); 101 | // 计算缩放比例 102 | float scaleWidth = ((float) newWidth) / width; 103 | float scaleHeight = ((float) newHeight) / height; 104 | // 取得想要缩放的matrix参数 105 | Matrix matrix = new Matrix(); 106 | matrix.postScale(scaleWidth, scaleHeight); 107 | // 得到新的图片 108 | Bitmap newBitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height, matrix, true); 109 | if (needRecycle) 110 | bitMap.recycle(); 111 | return newBitMap; 112 | } 113 | 114 | public static boolean saveBitmap(Bitmap bitmap, File file) { 115 | if (bitmap == null) 116 | return false; 117 | FileOutputStream fos = null; 118 | try { 119 | fos = new FileOutputStream(file); 120 | bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); 121 | fos.flush(); 122 | return true; 123 | } catch (Exception e) { 124 | e.printStackTrace(); 125 | } finally { 126 | if (fos != null) { 127 | try { 128 | fos.close(); 129 | } catch (IOException e) { 130 | e.printStackTrace(); 131 | } 132 | } 133 | } 134 | return false; 135 | } 136 | 137 | public static boolean saveBitmap(Bitmap bitmap, String absPath) { 138 | return saveBitmap(bitmap, new File(absPath)); 139 | } 140 | 141 | public static Intent buildImageGetIntent(Uri saveTo, int outputX, int outputY, boolean returnData) { 142 | return buildImageGetIntent(saveTo, 1, 1, outputX, outputY, returnData); 143 | } 144 | 145 | public static Intent buildImageGetIntent(Uri saveTo, int aspectX, int aspectY, 146 | int outputX, int outputY, boolean returnData) { 147 | Log.i(TAG, "Build.VERSION.SDK_INT : " + Build.VERSION.SDK_INT); 148 | Intent intent = new Intent(); 149 | if (Build.VERSION.SDK_INT < 19) { 150 | intent.setAction(Intent.ACTION_GET_CONTENT); 151 | } else { 152 | intent.setAction(Intent.ACTION_OPEN_DOCUMENT); 153 | intent.addCategory(Intent.CATEGORY_OPENABLE); 154 | } 155 | intent.setType("image/*"); 156 | intent.putExtra("output", saveTo); 157 | intent.putExtra("aspectX", aspectX); 158 | intent.putExtra("aspectY", aspectY); 159 | intent.putExtra("outputX", outputX); 160 | intent.putExtra("outputY", outputY); 161 | intent.putExtra("scale", true); 162 | intent.putExtra("return-data", returnData); 163 | intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); 164 | return intent; 165 | } 166 | 167 | public static Intent buildImageCropIntent(Uri uriFrom, Uri uriTo, int outputX, int outputY, boolean returnData) { 168 | return buildImageCropIntent(uriFrom, uriTo, 1, 1, outputX, outputY, returnData); 169 | } 170 | 171 | public static Intent buildImageCropIntent(Uri uriFrom, Uri uriTo, int aspectX, int aspectY, 172 | int outputX, int outputY, boolean returnData) { 173 | Intent intent = new Intent("com.android.camera.action.CROP"); 174 | intent.setDataAndType(uriFrom, "image/*"); 175 | intent.putExtra("crop", "true"); 176 | intent.putExtra("output", uriTo); 177 | intent.putExtra("aspectX", aspectX); 178 | intent.putExtra("aspectY", aspectY); 179 | intent.putExtra("outputX", outputX); 180 | intent.putExtra("outputY", outputY); 181 | intent.putExtra("scale", true); 182 | intent.putExtra("return-data", returnData); 183 | intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); 184 | return intent; 185 | } 186 | 187 | public static Intent buildImageCaptureIntent(Uri uri) { 188 | Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 189 | intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); 190 | return intent; 191 | } 192 | 193 | public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 194 | int h = options.outHeight; 195 | int w = options.outWidth; 196 | int inSampleSize = 0; 197 | if (h > reqHeight || w > reqWidth) { 198 | float ratioW = (float) w / reqWidth; 199 | float ratioH = (float) h / reqHeight; 200 | inSampleSize = (int) Math.min(ratioH, ratioW); 201 | } 202 | inSampleSize = Math.max(1, inSampleSize); 203 | return inSampleSize; 204 | } 205 | 206 | public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) { 207 | BitmapFactory.Options options = new BitmapFactory.Options(); 208 | options.inJustDecodeBounds = true; 209 | BitmapFactory.decodeFile(filePath, options); 210 | options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 211 | options.inJustDecodeBounds = false; 212 | return BitmapFactory.decodeFile(filePath, options); 213 | } 214 | 215 | public byte[] compressBitmapToBytes(String filePath, int reqWidth, int reqHeight, int quality) { 216 | Bitmap bitmap = getSmallBitmap(filePath, reqWidth, reqHeight); 217 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 218 | bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos); 219 | byte[] bytes = baos.toByteArray(); 220 | bitmap.recycle(); 221 | Log.i(TAG, "Bitmap compressed success, size: " + bytes.length); 222 | return bytes; 223 | } 224 | 225 | public byte[] compressBitmapSmallTo(String filePath, int reqWidth, int reqHeight, int maxLenth) { 226 | int quality = 100; 227 | byte[] bytes = compressBitmapToBytes(filePath, reqWidth, reqHeight, quality); 228 | while (bytes.length > maxLenth && quality > 0) { 229 | quality = quality / 2; 230 | bytes = compressBitmapToBytes(filePath, reqWidth, reqHeight, quality); 231 | } 232 | return bytes; 233 | } 234 | 235 | public byte[] compressBitmapQuikly(String filePath) { 236 | return compressBitmapToBytes(filePath, 480, 800, 50); 237 | } 238 | 239 | public byte[] compressBitmapQuiklySmallTo(String filePath, int maxLenth) { 240 | return compressBitmapSmallTo(filePath, 480, 800, maxLenth); 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/ByteUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.ObjectInputStream; 6 | import java.io.ObjectOutputStream; 7 | 8 | /** 9 | * @author MaTianyu 10 | * @date 14-7-31 11 | */ 12 | public class ByteUtil { 13 | /** 14 | * byte[] 转为 对象 15 | * 16 | * @param bytes 17 | * @return 18 | */ 19 | public static Object byteToObject(byte[] bytes) throws Exception { 20 | ObjectInputStream ois = null; 21 | try { 22 | ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); 23 | return ois.readObject(); 24 | } finally { 25 | if (ois != null) ois.close(); 26 | } 27 | } 28 | 29 | /** 30 | * 对象 转为 byte[] 31 | * 32 | * @param obj 33 | * @return 34 | */ 35 | public static byte[] objectToByte(Object obj) throws Exception { 36 | ObjectOutputStream oos = null; 37 | try { 38 | ByteArrayOutputStream bos = new ByteArrayOutputStream(); 39 | oos = new ObjectOutputStream(bos); 40 | oos.writeObject(obj); 41 | return bos.toByteArray(); 42 | } finally { 43 | if (oos != null) oos.close(); 44 | } 45 | } 46 | 47 | public static void byteToBit(byte[] bytes, StringBuilder sb) { 48 | for (int i = 0; i < Byte.SIZE * bytes.length; i++) 49 | sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1'); 50 | } 51 | 52 | public static String byteToBit(byte[] bytes) { 53 | StringBuilder sb = new StringBuilder(); 54 | for (int i = 0; i < Byte.SIZE * bytes.length; i++) 55 | sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1'); 56 | return sb.toString(); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/ClassUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import java.lang.reflect.Constructor; 4 | import java.util.Collection; 5 | import java.util.Date; 6 | 7 | /** 8 | * 类工具 9 | * 10 | * @author mty 11 | * @date 2013-6-10下午8:00:46 12 | */ 13 | public class ClassUtil { 14 | 15 | /** 16 | * 判断类是否是基础数据类型 17 | * 目前支持11种 18 | * 19 | * @param clazz 20 | * @return 21 | */ 22 | public static boolean isBaseDataType(Class clazz) { 23 | return clazz.isPrimitive() || clazz.equals(String.class) || clazz.equals(Boolean.class) 24 | || clazz.equals(Integer.class) || clazz.equals(Long.class) || clazz.equals(Float.class) 25 | || clazz.equals(Double.class) || clazz.equals(Byte.class) || clazz.equals(Character.class) 26 | || clazz.equals(Short.class) || clazz.equals(Date.class) || clazz.equals(byte[].class) 27 | || clazz.equals(Byte[].class); 28 | } 29 | 30 | /** 31 | * 根据类获取对象:不再必须一个无参构造 32 | * 33 | * @param claxx 34 | * @return 35 | * @throws Exception 36 | */ 37 | public static T newInstance(Class claxx) throws Exception { 38 | Constructor[] cons = claxx.getDeclaredConstructors(); 39 | for (Constructor c : cons) { 40 | Class[] cls = c.getParameterTypes(); 41 | if (cls.length == 0) { 42 | c.setAccessible(true); 43 | return (T) c.newInstance(); 44 | } else { 45 | Object[] objs = new Object[cls.length]; 46 | for (int i = 0; i < cls.length; i++) { 47 | objs[i] = getDefaultPrimiticeValue(cls[i]); 48 | } 49 | c.setAccessible(true); 50 | return (T) c.newInstance(objs); 51 | } 52 | } 53 | return null; 54 | } 55 | 56 | public static Object getDefaultPrimiticeValue(Class clazz) { 57 | if (clazz.isPrimitive()) { 58 | return clazz == boolean.class ? false : 0; 59 | } 60 | return null; 61 | } 62 | 63 | public static boolean isCollection(Class claxx) { 64 | return Collection.class.isAssignableFrom(claxx); 65 | } 66 | 67 | public static boolean isArray(Class claxx) { 68 | return claxx.isArray(); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/ClipboardUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.annotation.TargetApi; 4 | import android.content.ClipData; 5 | import android.content.ClipboardManager; 6 | import android.content.Context; 7 | import android.os.Build; 8 | 9 | /** 10 | * @author MaTianyu @http://litesuits.com 11 | * @date 2015-08-25 12 | */ 13 | public class ClipboardUtil { 14 | 15 | public static void copyToClipboardSupport(Context context, String text) { 16 | android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context 17 | .getSystemService(Context.CLIPBOARD_SERVICE); 18 | clipboard.setText(text); 19 | } 20 | 21 | public static void getLatestTextSupport(Context context) { 22 | android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context 23 | .getSystemService(Context.CLIPBOARD_SERVICE); 24 | clipboard.getText(); 25 | } 26 | 27 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 28 | public static void copyToClipboard(Context context, String text) { 29 | ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); 30 | clipboard.setPrimaryClip(ClipData.newPlainText(null, text)); 31 | } 32 | 33 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 34 | public static int getItemCount(Context context) { 35 | ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); 36 | ClipData data = clipboard.getPrimaryClip(); 37 | return data.getItemCount(); 38 | } 39 | 40 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 41 | public static String getText(Context context, int index) { 42 | ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); 43 | ClipData clip = clipboard.getPrimaryClip(); 44 | if (clip != null && clip.getItemCount() > index) { 45 | return String.valueOf(clip.getItemAt(0).coerceToText(context)); 46 | } 47 | return null; 48 | } 49 | 50 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 51 | public static String getLatestText(Context context) { 52 | ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); 53 | ClipData clip = clipboard.getPrimaryClip(); 54 | if (clip != null && clip.getItemCount() > 0) { 55 | return String.valueOf(clip.getItemAt(0).coerceToText(context)); 56 | } 57 | return null; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/CpuUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import com.litesuits.android.log.Log; 4 | import com.litesuits.common.assist.Check; 5 | 6 | import java.io.*; 7 | import java.util.regex.Pattern; 8 | 9 | /** 10 | * Get CPU info. 11 | * 12 | * @author MaTianyu 13 | * @date 2015-04-18 14 | */ 15 | public class CpuUtil { 16 | private static final String TAG = CpuUtil.class.getSimpleName(); 17 | private static final String CPU_INFO_PATH = "/proc/cpuinfo"; 18 | private static final String CPU_FREQ_NULL = "N/A"; 19 | private static final String CMD_CAT = "/system/bin/cat"; 20 | private static final String CPU_FREQ_CUR_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"; 21 | private static final String CPU_FREQ_MAX_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"; 22 | private static final String CPU_FREQ_MIN_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"; 23 | 24 | private static String CPU_NAME; 25 | private static int CPU_CORES = 0; 26 | private static long CPU_MAX_FREQENCY = 0; 27 | private static long CPU_MIN_FREQENCY = 0; 28 | 29 | /** 30 | * Print cpu info. 31 | */ 32 | public static String printCpuInfo() { 33 | String info = FileUtil.getFileOutputString(CPU_INFO_PATH); 34 | if (Log.isPrint) { 35 | Log.i(TAG, "_______ CPU : \n" + info); 36 | } 37 | return info; 38 | } 39 | 40 | /** 41 | * Get available processors. 42 | */ 43 | public static int getProcessorsCount() { 44 | return Runtime.getRuntime().availableProcessors(); 45 | } 46 | 47 | /** 48 | * Gets the number of cores available in this device, across all processors. 49 | * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu" 50 | * 51 | * @return The number of cores, or available processors if failed to get result 52 | */ 53 | public static int getCoresNumbers() { 54 | if (CPU_CORES != 0) { 55 | return CPU_CORES; 56 | } 57 | //Private Class to display only CPU devices in the directory listing 58 | class CpuFilter implements FileFilter { 59 | @Override 60 | public boolean accept(File pathname) { 61 | //Check if filename is "cpu", followed by a single digit number 62 | if (Pattern.matches("cpu[0-9]+", pathname.getName())) { 63 | return true; 64 | } 65 | return false; 66 | } 67 | } 68 | 69 | try { 70 | //Get directory containing CPU info 71 | File dir = new File("/sys/devices/system/cpu/"); 72 | //Filter to only list the devices we care about 73 | File[] files = dir.listFiles(new CpuFilter()); 74 | //Return the number of cores (virtual CPU devices) 75 | CPU_CORES = files.length; 76 | } catch (Exception e) { 77 | e.printStackTrace(); 78 | } 79 | if (CPU_CORES < 1) { 80 | CPU_CORES = Runtime.getRuntime().availableProcessors(); 81 | } 82 | if (CPU_CORES < 1) { 83 | CPU_CORES = 1; 84 | } 85 | return CPU_CORES; 86 | } 87 | 88 | /** 89 | * Get CPU name. 90 | */ 91 | public static String getCpuName() { 92 | if (!Check.isEmpty(CPU_NAME)) { 93 | return CPU_NAME; 94 | } 95 | try { 96 | BufferedReader bufferedReader = new BufferedReader(new FileReader(CPU_INFO_PATH), 8192); 97 | String line = bufferedReader.readLine(); 98 | bufferedReader.close(); 99 | String[] array = line.split(":\\s+", 2); 100 | if (array.length > 1) { 101 | if (Log.isPrint) { 102 | Log.i(TAG, array[1]); 103 | } 104 | CPU_NAME = array[1]; 105 | } 106 | } catch (IOException e) { 107 | e.printStackTrace(); 108 | } 109 | return CPU_NAME; 110 | } 111 | 112 | /** 113 | * Get current CPU freqency. 114 | */ 115 | public static long getCurrentFreqency() { 116 | try { 117 | return Long.parseLong(FileUtil.getFileOutputString(CPU_FREQ_CUR_PATH).trim()); 118 | } catch (Exception e) { 119 | e.printStackTrace(); 120 | } 121 | return 0; 122 | } 123 | 124 | /** 125 | * Get maximum CPU freqency 126 | */ 127 | public static long getMaxFreqency() { 128 | if (CPU_MAX_FREQENCY > 0) { 129 | return CPU_MAX_FREQENCY; 130 | } 131 | try { 132 | CPU_MAX_FREQENCY = Long.parseLong(getCMDOutputString(new String[]{CMD_CAT, CPU_FREQ_MAX_PATH}).trim()); 133 | } catch (Exception e) { 134 | e.printStackTrace(); 135 | } 136 | return CPU_MAX_FREQENCY; 137 | } 138 | 139 | /** 140 | * Get minimum frenqency. 141 | */ 142 | public static long getMinFreqency() { 143 | if (CPU_MIN_FREQENCY > 0) { 144 | return CPU_MIN_FREQENCY; 145 | } 146 | try { 147 | CPU_MIN_FREQENCY = Long.parseLong(getCMDOutputString(new String[]{CMD_CAT, CPU_FREQ_MIN_PATH}).trim()); 148 | } catch (Exception e) { 149 | e.printStackTrace(); 150 | } 151 | return CPU_MIN_FREQENCY; 152 | } 153 | 154 | /** 155 | * Get command output string. 156 | */ 157 | public static String getCMDOutputString(String[] args) { 158 | try { 159 | ProcessBuilder cmd = new ProcessBuilder(args); 160 | Process process = cmd.start(); 161 | InputStream in = process.getInputStream(); 162 | StringBuilder sb = new StringBuilder(); 163 | byte[] re = new byte[64]; 164 | int len; 165 | while ((len = in.read(re)) != -1) { 166 | sb.append(new String(re, 0, len)); 167 | } 168 | in.close(); 169 | process.destroy(); 170 | if (Log.isPrint) { 171 | Log.i(TAG, "CMD: " + sb.toString()); 172 | } 173 | return sb.toString(); 174 | } catch (IOException ex) { 175 | ex.printStackTrace(); 176 | } 177 | return null; 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/DialogUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.app.AlertDialog; 4 | import android.app.Dialog; 5 | import android.content.Context; 6 | import android.content.DialogInterface; 7 | import android.text.Html; 8 | import android.view.View; 9 | 10 | public class DialogUtil { 11 | 12 | public static AlertDialog.Builder dialogBuilder(Context context, String title, String msg) { 13 | AlertDialog.Builder builder = new AlertDialog.Builder(context); 14 | if (msg != null) { 15 | builder.setMessage(msg); 16 | } 17 | if (title != null) { 18 | builder.setTitle(title); 19 | } 20 | return builder; 21 | } 22 | 23 | public static AlertDialog.Builder dialogBuilder(Context context, String title, String msg, int i) { 24 | AlertDialog.Builder builder = new AlertDialog.Builder(context); 25 | if (msg != null) { 26 | builder.setMessage(Html.fromHtml(msg)); 27 | } 28 | if (title != null) { 29 | builder.setTitle(title); 30 | } 31 | return builder; 32 | } 33 | 34 | 35 | public static AlertDialog.Builder dialogBuilder(Context context, int title, View view) { 36 | AlertDialog.Builder builder = new AlertDialog.Builder(context); 37 | if (view != null) { 38 | builder.setView(view); 39 | } 40 | if (title > 0) { 41 | builder.setTitle(title); 42 | } 43 | return builder; 44 | } 45 | 46 | public static AlertDialog.Builder dialogBuilder(Context context, int titleResId, int msgResId) { 47 | String title = titleResId > 0 ? context.getResources().getString(titleResId) : null; 48 | String msg = msgResId > 0 ? context.getResources().getString(msgResId) : null; 49 | return dialogBuilder(context, title, msg); 50 | } 51 | 52 | public static Dialog showTips(Context context, String title, String des) { 53 | return showTips(context, title, des, null, null); 54 | } 55 | 56 | public static Dialog showTips(Context context, int title, int des) { 57 | return showTips(context, context.getString(title), context.getString(des)); 58 | } 59 | 60 | public static Dialog showTips(Context context, int title, int des, int btn, DialogInterface.OnDismissListener dismissListener) { 61 | return showTips(context, context.getString(title), context.getString(des), context.getString(btn), dismissListener); 62 | } 63 | 64 | public static Dialog showTips(Context context, String title, String des, String btn, DialogInterface.OnDismissListener dismissListener) { 65 | AlertDialog.Builder builder = dialogBuilder(context, title, des); 66 | builder.setCancelable(true); 67 | builder.setPositiveButton(btn, null); 68 | Dialog dialog = builder.show(); 69 | dialog.setCanceledOnTouchOutside(true); 70 | dialog.setOnDismissListener(dismissListener); 71 | return dialog; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/DisplayUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.content.Context; 4 | import android.util.DisplayMetrics; 5 | import com.litesuits.android.log.Log; 6 | 7 | /** 8 | * @author MaTianyu 9 | * @date 2015-04-19 10 | */ 11 | public class DisplayUtil { 12 | private static final String TAG = DisplayUtil.class.getSimpleName(); 13 | 14 | /** 15 | * 获取 显示信息 16 | */ 17 | public static DisplayMetrics getDisplayMetrics(Context context) { 18 | DisplayMetrics dm = context.getResources().getDisplayMetrics(); 19 | return dm; 20 | } 21 | 22 | /** 23 | * 打印 显示信息 24 | */ 25 | public static DisplayMetrics printDisplayInfo(Context context) { 26 | DisplayMetrics dm = getDisplayMetrics(context); 27 | if (Log.isPrint) { 28 | StringBuilder sb = new StringBuilder(); 29 | sb.append("_______ 显示信息: "); 30 | sb.append("\ndensity :").append(dm.density); 31 | sb.append("\ndensityDpi :").append(dm.densityDpi); 32 | sb.append("\nheightPixels :").append(dm.heightPixels); 33 | sb.append("\nwidthPixels :").append(dm.widthPixels); 34 | sb.append("\nscaledDensity :").append(dm.scaledDensity); 35 | sb.append("\nxdpi :").append(dm.xdpi); 36 | sb.append("\nydpi :").append(dm.ydpi); 37 | Log.i(TAG, sb.toString()); 38 | } 39 | return dm; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/FieldUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import java.io.Serializable; 4 | import java.lang.reflect.Field; 5 | import java.lang.reflect.Modifier; 6 | import java.lang.reflect.ParameterizedType; 7 | import java.lang.reflect.Type; 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | 11 | /** 12 | * 域工具 13 | * 14 | * @author mty 15 | * @date 2013-6-10下午6:36:29 16 | */ 17 | public class FieldUtil { 18 | 19 | /** 20 | * 判断是否序列化 21 | * 22 | * @param f 23 | * @return 24 | */ 25 | public static boolean isSerializable(Field f) { 26 | Class[] cls = f.getType().getInterfaces(); 27 | for (Class c : cls) { 28 | if (Serializable.class == c) { 29 | return true; 30 | } 31 | } 32 | return false; 33 | } 34 | 35 | /** 36 | * 设置域的值 37 | * 38 | * @param f 39 | * @param obj 40 | * @return 41 | * @throws IllegalAccessException 42 | * @throws IllegalArgumentException 43 | */ 44 | public static Object set(Field f, Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { 45 | f.setAccessible(true); 46 | f.set(obj, value); 47 | return f.get(obj); 48 | } 49 | 50 | /** 51 | * 获取域的值 52 | * 53 | * @param f 54 | * @param obj 55 | * @return 56 | * @throws IllegalAccessException 57 | * @throws IllegalArgumentException 58 | */ 59 | public static Object get(Field f, Object obj) throws IllegalArgumentException, IllegalAccessException { 60 | f.setAccessible(true); 61 | return f.get(obj); 62 | } 63 | 64 | public static boolean isLong(Field field) { 65 | return field.getType() == long.class || field.getType() == Long.class; 66 | } 67 | 68 | public static boolean isInteger(Field field) { 69 | return field.getType() == int.class || field.getType() != Integer.class; 70 | } 71 | 72 | /** 73 | * 获取域的泛型类型,如果不带泛型返回null 74 | * 75 | * @param f 76 | * @return 77 | */ 78 | public static Class getGenericType(Field f) { 79 | Type type = f.getGenericType(); 80 | if (type instanceof ParameterizedType) { 81 | type = ((ParameterizedType) type).getActualTypeArguments()[0]; 82 | if (type instanceof Class) return (Class) type; 83 | } else if (type instanceof Class) return (Class) type; 84 | return null; 85 | } 86 | 87 | /** 88 | * 获取数组的类型 89 | * 90 | * @param f 91 | * @return 92 | */ 93 | public static Class getComponentType(Field f) { 94 | return f.getType().getComponentType(); 95 | } 96 | 97 | /** 98 | * 获取全部Field,包括父类 99 | * 100 | * @param claxx 101 | * @return 102 | */ 103 | public static List getAllDeclaredFields(Class claxx) { 104 | // find all field. 105 | LinkedList fieldList = new LinkedList(); 106 | while (claxx != null && claxx != Object.class) { 107 | Field[] fs = claxx.getDeclaredFields(); 108 | for (int i = 0; i < fs.length; i++) { 109 | Field f = fs[i]; 110 | if (!isInvalid(f)) { 111 | fieldList.addLast(f); 112 | } 113 | } 114 | claxx = claxx.getSuperclass(); 115 | } 116 | return fieldList; 117 | } 118 | 119 | /** 120 | * 是静态常量或者内部结构属性 121 | * 122 | * @param f 123 | * @return 124 | */ 125 | public static boolean isInvalid(Field f) { 126 | return (Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers())) || f.isSynthetic(); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/FileUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import java.io.*; 4 | import java.nio.channels.FileChannel; 5 | import java.text.DecimalFormat; 6 | 7 | /** 8 | * @author MaTianyu 9 | * @date 2014-08-10 10 | */ 11 | public class FileUtil { 12 | 13 | private static final String TAG = FileUtil.class.getSimpleName(); 14 | 15 | public static void fileChannelCopy(File s, File t) { 16 | FileInputStream fi = null; 17 | FileOutputStream fo = null; 18 | try { 19 | fi = new FileInputStream(s); 20 | fo = new FileOutputStream(t); 21 | FileChannel in = fi.getChannel();//得到对应的文件通道 22 | FileChannel out = fo.getChannel();//得到对应的文件通道 23 | in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道 24 | } catch (IOException e) { 25 | e.printStackTrace(); 26 | } finally { 27 | try { 28 | if (fo != null) fo.close(); 29 | if (fi != null) fi.close(); 30 | } catch (IOException e) { 31 | e.printStackTrace(); 32 | } 33 | 34 | } 35 | } 36 | 37 | public static String formatFileSizeToString(long fileLen) {// 转换文件大小 38 | DecimalFormat df = new DecimalFormat("#.00"); 39 | String fileSizeString = ""; 40 | if (fileLen < 1024) { 41 | fileSizeString = df.format((double) fileLen) + "B"; 42 | } else if (fileLen < 1048576) { 43 | fileSizeString = df.format((double) fileLen / 1024) + "K"; 44 | } else if (fileLen < 1073741824) { 45 | fileSizeString = df.format((double) fileLen / 1048576) + "M"; 46 | } else { 47 | fileSizeString = df.format((double) fileLen / 1073741824) + "G"; 48 | } 49 | return fileSizeString; 50 | } 51 | 52 | /*** 53 | * 根据路径删除图片 54 | */ 55 | public static boolean deleteFile(File file)throws IOException{ 56 | return file != null && file.delete(); 57 | } 58 | 59 | /*** 60 | * 获取文件扩展名 61 | * @param filename 62 | * @return 返回文件扩展名 63 | */ 64 | public static String getExtensionName(String filename) { 65 | if ((filename != null) && (filename.length() > 0)) { 66 | int dot = filename.lastIndexOf('.'); 67 | if ((dot >-1) && (dot < (filename.length() - 1))) { 68 | return filename.substring(dot + 1); 69 | } 70 | } 71 | return filename; 72 | } 73 | 74 | 75 | /** 76 | * 读取指定文件的输出 77 | */ 78 | public static String getFileOutputString(String path) { 79 | try { 80 | BufferedReader bufferedReader = new BufferedReader(new FileReader(path), 8192); 81 | StringBuilder sb = new StringBuilder(); 82 | String line = null; 83 | while ((line = bufferedReader.readLine()) != null) { 84 | sb.append("\n").append(line); 85 | } 86 | bufferedReader.close(); 87 | return sb.toString(); 88 | } catch (IOException e) { 89 | e.printStackTrace(); 90 | } 91 | return null; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/HandlerUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | /** 7 | * @author MaTianyu 8 | * @date 2015-03-12 9 | */ 10 | public class HandlerUtil { 11 | public static final Handler HANDLER = new Handler(Looper.getMainLooper()); 12 | 13 | public static void runOnUiThread(Runnable runnable){ 14 | HANDLER.post(runnable); 15 | } 16 | 17 | public static void runOnUiThreadDelay(Runnable runnable, long delayMillis){ 18 | HANDLER.postDelayed(runnable,delayMillis); 19 | } 20 | 21 | public static void removeRunable(Runnable runnable){ 22 | HANDLER.removeCallbacks(runnable); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/HexUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | /** 4 | * reference apache commons http://commons.apache.org/codec/ 6 | * 7 | * @author Aub 8 | * 9 | */ 10 | public class HexUtil { 11 | 12 | /** 13 | * 用于建立十六进制字符的输出的小写字符数组 14 | */ 15 | private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', 16 | '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; 17 | 18 | /** 19 | * 用于建立十六进制字符的输出的大写字符数组 20 | */ 21 | private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', 22 | '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; 23 | 24 | /** 25 | * 将字节数组转换为十六进制字符数组 26 | * 27 | * @param data 28 | * byte[] 29 | * @return 十六进制char[] 30 | */ 31 | public static char[] encodeHex(byte[] data) { 32 | return encodeHex(data, true); 33 | } 34 | 35 | /** 36 | * 将字节数组转换为十六进制字符数组 37 | * 38 | * @param data 39 | * byte[] 40 | * @param toLowerCase 41 | * true 传换成小写格式 , false 传换成大写格式 42 | * @return 十六进制char[] 43 | */ 44 | public static char[] encodeHex(byte[] data, boolean toLowerCase) { 45 | return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); 46 | } 47 | 48 | /** 49 | * 将字节数组转换为十六进制字符数组 50 | * 51 | * @param data 52 | * byte[] 53 | * @param toDigits 54 | * 用于控制输出的char[] 55 | * @return 十六进制char[] 56 | */ 57 | protected static char[] encodeHex(byte[] data, char[] toDigits) { 58 | int l = data.length; 59 | char[] out = new char[l << 1]; 60 | // two characters form the hex value. 61 | for (int i = 0, j = 0; i < l; i++) { 62 | out[j++] = toDigits[(0xF0 & data[i]) >>> 4]; 63 | out[j++] = toDigits[0x0F & data[i]]; 64 | } 65 | return out; 66 | } 67 | 68 | /** 69 | * 将字节数组转换为十六进制字符串 70 | * 71 | * @param data 72 | * byte[] 73 | * @return 十六进制String 74 | */ 75 | public static String encodeHexStr(byte[] data) { 76 | return encodeHexStr(data, true); 77 | } 78 | 79 | /** 80 | * 将字节数组转换为十六进制字符串 81 | * 82 | * @param data 83 | * byte[] 84 | * @param toLowerCase 85 | * true 传换成小写格式 , false 传换成大写格式 86 | * @return 十六进制String 87 | */ 88 | public static String encodeHexStr(byte[] data, boolean toLowerCase) { 89 | return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); 90 | } 91 | 92 | /** 93 | * 将字节数组转换为十六进制字符串 94 | * 95 | * @param data 96 | * byte[] 97 | * @param toDigits 98 | * 用于控制输出的char[] 99 | * @return 十六进制String 100 | */ 101 | protected static String encodeHexStr(byte[] data, char[] toDigits) { 102 | return new String(encodeHex(data, toDigits)); 103 | } 104 | 105 | /** 106 | * 将十六进制字符数组转换为字节数组 107 | * 108 | * @param data 109 | * 十六进制char[] 110 | * @return byte[] 111 | * @throws RuntimeException 112 | * 如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常 113 | */ 114 | public static byte[] decodeHex(char[] data) { 115 | 116 | int len = data.length; 117 | 118 | if ((len & 0x01) != 0) { 119 | throw new RuntimeException("Odd number of characters."); 120 | } 121 | 122 | byte[] out = new byte[len >> 1]; 123 | 124 | // two characters form the hex value. 125 | for (int i = 0, j = 0; j < len; i++) { 126 | int f = toDigit(data[j], j) << 4; 127 | j++; 128 | f = f | toDigit(data[j], j); 129 | j++; 130 | out[i] = (byte) (f & 0xFF); 131 | } 132 | 133 | return out; 134 | } 135 | 136 | /** 137 | * 将十六进制字符转换成一个整数 138 | * 139 | * @param ch 140 | * 十六进制char 141 | * @param index 142 | * 十六进制字符在字符数组中的位置 143 | * @return 一个整数 144 | * @throws RuntimeException 145 | * 当ch不是一个合法的十六进制字符时,抛出运行时异常 146 | */ 147 | protected static int toDigit(char ch, int index) { 148 | int digit = Character.digit(ch, 16); 149 | if (digit == -1) { 150 | throw new RuntimeException("Illegal hexadecimal character " + ch 151 | + " at index " + index); 152 | } 153 | return digit; 154 | } 155 | 156 | public static void main(String[] args) { 157 | String srcStr = "待转换字符串"; 158 | String encodeStr = encodeHexStr(srcStr.getBytes()); 159 | String decodeStr = new String(decodeHex(encodeStr.toCharArray())); 160 | System.out.println("转换前:" + srcStr); 161 | System.out.println("转换后:" + encodeStr); 162 | System.out.println("还原后:" + decodeStr); 163 | } 164 | 165 | } 166 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/InputMethodUtils.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.Activity; 5 | import android.content.Context; 6 | import android.os.Build; 7 | import android.view.View; 8 | import android.view.inputmethod.InputMethodManager; 9 | 10 | /** 11 | * @author MaTianyu(http://litesuits.com) on 2015-06-01 12 | */ 13 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 14 | public class InputMethodUtils { 15 | 16 | public static void toggleSoftInput(Context context) { 17 | InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); 18 | imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); 19 | } 20 | 21 | public static boolean showSoftInput(View view) { 22 | InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 23 | return imm.showSoftInput(view, InputMethodManager.SHOW_FORCED); 24 | } 25 | 26 | public static boolean showSoftInput(Activity activity) { 27 | View view = activity.getCurrentFocus(); 28 | if (view != null) { 29 | InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService( 30 | Context.INPUT_METHOD_SERVICE); 31 | return imm.showSoftInput(view, InputMethodManager.SHOW_FORCED); 32 | } 33 | return false; 34 | } 35 | 36 | public static boolean hideSoftInput(View view) { 37 | InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 38 | return imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 39 | } 40 | 41 | public static boolean hideSoftInput(Activity activity) { 42 | if (activity.getCurrentFocus() != null) { 43 | InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); 44 | return imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); 45 | } 46 | return false; 47 | } 48 | 49 | public static boolean isActive(Context context) { 50 | InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); 51 | return imm.isActive(); 52 | } 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/MD5Util.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.security.MessageDigest; 6 | import java.security.NoSuchAlgorithmException; 7 | 8 | /** 9 | * MS5 10 | */ 11 | public class MD5Util { 12 | private static final String TAG = MD5Util.class.getSimpleName(); 13 | private static final int STREAM_BUFFER_LENGTH = 1024; 14 | 15 | public static MessageDigest getDigest(final String algorithm) throws NoSuchAlgorithmException { 16 | return MessageDigest.getInstance(algorithm); 17 | } 18 | 19 | public static byte[] md5(String txt) { 20 | return md5(txt.getBytes()); 21 | } 22 | 23 | public static byte[] md5(byte[] bytes) { 24 | try { 25 | MessageDigest digest = getDigest("MD5"); 26 | digest.update(bytes); 27 | return digest.digest(); 28 | } catch (NoSuchAlgorithmException e) { 29 | e.printStackTrace(); 30 | } 31 | return null; 32 | } 33 | 34 | public static byte[] md5(InputStream is) throws NoSuchAlgorithmException, IOException { 35 | return updateDigest(getDigest("MD5"), is).digest(); 36 | } 37 | 38 | public static MessageDigest updateDigest(final MessageDigest digest, final InputStream data) throws IOException { 39 | final byte[] buffer = new byte[STREAM_BUFFER_LENGTH]; 40 | int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH); 41 | 42 | while (read > -1) { 43 | digest.update(buffer, 0, read); 44 | read = data.read(buffer, 0, STREAM_BUFFER_LENGTH); 45 | } 46 | 47 | return digest; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/MemoryUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.ActivityManager; 5 | import android.content.Context; 6 | import android.os.Build; 7 | import android.text.format.Formatter; 8 | import com.litesuits.android.log.Log; 9 | 10 | /** 11 | * Get memory info. 12 | * 13 | * @author MaTianyu 14 | * @date 2015-04-19 15 | */ 16 | public class MemoryUtil { 17 | private static final String TAG = MemoryUtil.class.getSimpleName(); 18 | private static final String MEM_INFO_PATH = "/proc/meminfo"; 19 | 20 | /** 21 | * Print memory info. such as: 22 | * 23 | * MemTotal: 1864292 kB 24 | * MemFree: 779064 kB 25 | * Buffers: 4540 kB 26 | * Cached: 185656 kB 27 | * SwapCached: 13160 kB 28 | * Active: 435588 kB 29 | * Inactive: 269312 kB 30 | * Active(anon): 386188 kB 31 | * Inactive(anon): 132576 kB 32 | * Active(file): 49400 kB 33 | * Inactive(file): 136736 kB 34 | * Unevictable: 2420 kB 35 | * Mlocked: 0 kB 36 | * HighTotal: 1437692 kB 37 | * HighFree: 520212 kB 38 | * LowTotal: 426600 kB 39 | * LowFree: 258852 kB 40 | * SwapTotal: 511996 kB 41 | * SwapFree: 171876 kB 42 | * Dirty: 412 kB 43 | * Writeback: 0 kB 44 | * AnonPages: 511924 kB 45 | * Mapped: 152368 kB 46 | * Shmem: 1636 kB 47 | * Slab: 109224 kB 48 | * SReclaimable: 75932 kB 49 | * SUnreclaim: 33292 kB 50 | * KernelStack: 13056 kB 51 | * PageTables: 28032 kB 52 | * NFS_Unstable: 0 kB 53 | * Bounce: 0 kB 54 | * WritebackTmp: 0 kB 55 | * CommitLimit: 1444140 kB 56 | * Committed_AS: 25977748 kB 57 | * VmallocTotal: 458752 kB 58 | * VmallocUsed: 123448 kB 59 | * VmallocChunk: 205828 kB 60 | */ 61 | public static String printMemInfo() { 62 | String info = FileUtil.getFileOutputString(MEM_INFO_PATH); 63 | if (Log.isPrint) { 64 | Log.i(TAG, "_______ 内存信息: \n" + info); 65 | } 66 | return info; 67 | } 68 | 69 | /** 70 | * Get memory info of device. 71 | */ 72 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 73 | public static ActivityManager.MemoryInfo getMemoryInfo(Context context) { 74 | ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 75 | ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); 76 | am.getMemoryInfo(mi); 77 | return mi; 78 | } 79 | 80 | /** 81 | * Print Memory info. 82 | */ 83 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 84 | public static ActivityManager.MemoryInfo printMemoryInfo(Context context) { 85 | ActivityManager.MemoryInfo mi = getMemoryInfo(context); 86 | if (Log.isPrint) { 87 | StringBuilder sb = new StringBuilder(); 88 | sb.append("_______ Memory : "); 89 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 90 | sb.append("\ntotalMem :").append(mi.totalMem); 91 | } 92 | sb.append("\navailMem :").append(mi.availMem); 93 | sb.append("\nlowMemory :").append(mi.lowMemory); 94 | sb.append("\nthreshold :").append(mi.threshold); 95 | Log.i(TAG, sb.toString()); 96 | } 97 | return mi; 98 | } 99 | 100 | /** 101 | * Get available memory info. 102 | */ 103 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 104 | public static String getAvailMemory(Context context) {// 获取android当前可用内存大小 105 | ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 106 | ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); 107 | am.getMemoryInfo(mi); 108 | // mi.availMem; 当前系统的可用内存 109 | return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/NotificationUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.app.Notification; 4 | import android.app.NotificationManager; 5 | import android.app.PendingIntent; 6 | import android.content.ComponentName; 7 | import android.content.Context; 8 | import android.content.Intent; 9 | import android.graphics.Color; 10 | import android.net.Uri; 11 | import android.os.Build; 12 | import android.os.Bundle; 13 | import android.os.Handler; 14 | import android.os.Looper; 15 | import com.litesuits.android.log.Log; 16 | 17 | import java.util.ArrayList; 18 | 19 | /** 20 | * @author MaTianyu 21 | * @date 2014-11-19 22 | */ 23 | public class NotificationUtil { 24 | private static int LedID = 0; 25 | private static final String TAG = NotificationUtil.class.getSimpleName(); 26 | 27 | public static void notification(Context context, Uri uri, 28 | int icon, String ticker, String title, String msg) { 29 | Log.i(TAG, "notiry uri :" + uri); 30 | // 设置通知的事件消息 31 | Intent intent = new Intent(); 32 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) { 33 | intent.setPackage(context.getPackageName()); 34 | } 35 | intent.setData(uri); 36 | notification(context, intent, 0, icon, ticker, title, msg); 37 | } 38 | 39 | public static void notification(Context context, String activityClass, Bundle bundle, 40 | int icon, String ticker, String title, String msg) { 41 | // 设置通知的事件消息 42 | Intent intent = new Intent(); 43 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) { 44 | intent.setPackage(context.getPackageName()); 45 | } 46 | intent.putExtras(bundle); 47 | intent.setComponent(new ComponentName(context.getPackageName(), activityClass)); 48 | notification(context, intent, 0, icon, ticker, title, msg); 49 | } 50 | 51 | public static void notification(Context context, Intent intent, int id, 52 | int icon, String ticker, String title, String msg) { 53 | PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 54 | notification(context, pendingIntent, id, icon, ticker, title, msg); 55 | } 56 | 57 | public static void notification(Context context, PendingIntent pendingIntent, int id, 58 | int icon, String ticker, String title, String msg) { 59 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 60 | Notification.Builder builder = new Notification.Builder(context); 61 | builder.setSmallIcon(icon); 62 | 63 | builder.setContentTitle(title); 64 | builder.setTicker(ticker); 65 | builder.setContentText(msg); 66 | 67 | builder.setDefaults(Notification.DEFAULT_SOUND); 68 | builder.setLights(0xFFFFFF00, 0, 2000); 69 | builder.setVibrate(new long[]{0, 100, 300}); 70 | builder.setAutoCancel(true); 71 | builder.setContentIntent(pendingIntent); 72 | Notification baseNF; 73 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { 74 | baseNF = builder.getNotification(); 75 | } else { 76 | baseNF = builder.build(); 77 | } 78 | //发出状态栏通知 79 | NotificationManager nm = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); 80 | nm.notify(id, baseNF); 81 | } else { 82 | // 创建一个NotificationManager的引用 83 | NotificationManager notificationManager = (NotificationManager) context 84 | .getSystemService(android.content.Context.NOTIFICATION_SERVICE); 85 | // 定义Notification的各种属性 86 | Notification notification = new Notification(icon, ticker, System.currentTimeMillis()); 87 | notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_SHOW_LIGHTS; 88 | notification.defaults = Notification.DEFAULT_ALL; 89 | notification.ledARGB = Color.GREEN; 90 | notification.ledOnMS = 5000; //闪光时间,毫秒 91 | 92 | notification.tickerText = ticker; 93 | notification.setLatestEventInfo(context, title, msg, pendingIntent); 94 | // 把Notification传递给NotificationManager 95 | notificationManager.notify(id, notification); 96 | } 97 | } 98 | 99 | public static void lightLed(Context context, int colorOx, int durationMS) { 100 | lightLed(context, colorOx, 0, durationMS); 101 | } 102 | 103 | public static void lightLed(Context context, int colorOx, int startOffMS, int durationMS) { 104 | NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 105 | Notification notification = new Notification(); 106 | notification.ledARGB = colorOx; 107 | notification.ledOffMS = startOffMS; 108 | notification.ledOnMS = durationMS; 109 | notification.flags = Notification.FLAG_SHOW_LIGHTS; 110 | LedID++; 111 | nm.notify(LedID, notification); 112 | nm.cancel(LedID); 113 | } 114 | 115 | public static void lightLed(final Context context, final int colorOx, final int startOffMS, final int durationMS, 116 | int repeat) { 117 | if (repeat < 1) { 118 | repeat = 1; 119 | } 120 | Handler handler = new Handler(Looper.getMainLooper()); 121 | for (int i = 0; i < repeat; i++) { 122 | handler.postDelayed(new Runnable() { 123 | @Override 124 | public void run() { 125 | lightLed(context, colorOx, startOffMS, durationMS); 126 | } 127 | }, (startOffMS + durationMS) * i); 128 | } 129 | } 130 | 131 | public static void lightLed(Context context, ArrayList patterns) { 132 | if (patterns == null) { 133 | return; 134 | } 135 | for (LightPattern lp : patterns) { 136 | lightLed(context, lp.argb, lp.startOffMS, lp.durationMS); 137 | } 138 | } 139 | 140 | public static class LightPattern { 141 | public int argb = 0; 142 | public int startOffMS = 0; 143 | public int durationMS = 0; 144 | 145 | public LightPattern(int argb, int startOffMS, int durationMS) { 146 | this.argb = argb; 147 | this.startOffMS = startOffMS; 148 | this.durationMS = durationMS; 149 | } 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/NumberUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | /** 4 | * @author MaTianyu 5 | * @date 2014-11-21 6 | */ 7 | public class NumberUtil { 8 | 9 | public static int convertToint(String intStr, int defValue) { 10 | try { 11 | return Integer.parseInt(intStr); 12 | } catch (NumberFormatException e) { 13 | //e.printStackTrace(); 14 | } 15 | return defValue; 16 | } 17 | 18 | public static long convertTolong(String longStr, long defValue) { 19 | try { 20 | return Long.parseLong(longStr); 21 | } catch (NumberFormatException e) { 22 | //e.printStackTrace(); 23 | } 24 | return defValue; 25 | } 26 | 27 | public static float convertTofloat(String fStr, float defValue) { 28 | try { 29 | return Float.parseFloat(fStr); 30 | } catch (NumberFormatException e) { 31 | //e.printStackTrace(); 32 | } 33 | return defValue; 34 | } 35 | 36 | public static double convertTodouble(String dStr, double defValue) { 37 | try { 38 | return Double.parseDouble(dStr); 39 | } catch (NumberFormatException e) { 40 | //e.printStackTrace(); 41 | } 42 | return defValue; 43 | } 44 | 45 | 46 | public static Integer convertToInteger(String intStr) { 47 | try { 48 | return Integer.parseInt(intStr); 49 | } catch (NumberFormatException e) { 50 | //e.printStackTrace(); 51 | } 52 | return null; 53 | } 54 | 55 | public static Long convertToLong(String longStr) { 56 | try { 57 | return Long.parseLong(longStr); 58 | } catch (NumberFormatException e) { 59 | //e.printStackTrace(); 60 | } 61 | return null; 62 | } 63 | 64 | public static Float convertToFloat(String fStr) { 65 | try { 66 | return Float.parseFloat(fStr); 67 | } catch (NumberFormatException e) { 68 | //e.printStackTrace(); 69 | } 70 | return null; 71 | } 72 | 73 | public static Double convertToDouble(String dStr) { 74 | try { 75 | return Double.parseDouble(dStr); 76 | } catch (NumberFormatException e) { 77 | //e.printStackTrace(); 78 | } 79 | return null; 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/PackageUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.app.ActivityManager; 4 | import android.content.ComponentName; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.content.pm.ApplicationInfo; 8 | import android.content.pm.PackageInfo; 9 | import android.content.pm.PackageManager; 10 | import android.content.pm.PackageManager.NameNotFoundException; 11 | import android.content.pm.ResolveInfo; 12 | import android.net.Uri; 13 | import android.os.Build; 14 | import android.provider.Settings; 15 | import android.widget.Toast; 16 | import com.litesuits.common.assist.Check; 17 | 18 | import java.io.File; 19 | import java.util.List; 20 | import java.util.Map; 21 | 22 | /** 23 | * @author MaTianyu 24 | * @date 14-11-7 25 | */ 26 | public class PackageUtil { 27 | /** 28 | * App installation location flags of android system 29 | */ 30 | public static final int APP_INSTALL_AUTO = 0; 31 | public static final int APP_INSTALL_INTERNAL = 1; 32 | public static final int APP_INSTALL_EXTERNAL = 2; 33 | 34 | /** 35 | * 调用系统安装应用 36 | */ 37 | public static boolean install(Context context, File file) { 38 | if (file == null || !file.exists() || !file.isFile()) { 39 | return false; 40 | } 41 | Intent intent = new Intent(Intent.ACTION_VIEW); 42 | intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); 43 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 44 | context.startActivity(intent); 45 | return true; 46 | } 47 | 48 | /** 49 | * 调用系统卸载应用 50 | */ 51 | public static void uninstallApk(Context context, String packageName) { 52 | Intent intent = new Intent(Intent.ACTION_DELETE); 53 | Uri packageURI = Uri.parse("package:" + packageName); 54 | intent.setData(packageURI); 55 | context.startActivity(intent); 56 | } 57 | 58 | /** 59 | * 打开已安装应用的详情 60 | */ 61 | public static void goToInstalledAppDetails(Context context, String packageName) { 62 | Intent intent = new Intent(); 63 | int sdkVersion = Build.VERSION.SDK_INT; 64 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { 65 | intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); 66 | intent.setData(Uri.fromParts("package", packageName, null)); 67 | } else { 68 | intent.setAction(Intent.ACTION_VIEW); 69 | intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); 70 | intent.putExtra((sdkVersion == Build.VERSION_CODES.FROYO ? "pkg" 71 | : "com.android.settings.ApplicationPkgName"), packageName); 72 | } 73 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 74 | context.startActivity(intent); 75 | } 76 | 77 | 78 | /** 79 | * 获取指定程序信息 80 | */ 81 | public static ActivityManager.RunningTaskInfo getTopRunningTask(Context context) { 82 | try { 83 | ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 84 | // 得到当前正在运行的任务栈 85 | List runningTasks = am.getRunningTasks(1); 86 | // 得到前台显示的任务栈 87 | ActivityManager.RunningTaskInfo runningTaskInfo = runningTasks.get(0); 88 | return runningTaskInfo; 89 | } catch (Exception e) { 90 | e.printStackTrace(); 91 | } 92 | return null; 93 | } 94 | 95 | 96 | public static String getAppVersionName(Context context) { 97 | try { 98 | PackageManager pm = context.getPackageManager(); 99 | PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0); 100 | return pi.versionName; 101 | } catch (NameNotFoundException e) { 102 | e.printStackTrace(); 103 | } 104 | return ""; 105 | } 106 | 107 | public static int getAppVersionCode(Context context) { 108 | try { 109 | PackageManager pm = context.getPackageManager(); 110 | PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0); 111 | return pi.versionCode; 112 | } catch (NameNotFoundException e) { 113 | e.printStackTrace(); 114 | } 115 | return -1; 116 | } 117 | 118 | /** 119 | * 获取当前系统安装应用的默认位置 120 | * 121 | * @return APP_INSTALL_AUTO or APP_INSTALL_INTERNAL or APP_INSTALL_EXTERNAL. 122 | */ 123 | public static int getInstallLocation() { 124 | ShellUtil.CommandResult commandResult = ShellUtil.execCommand( 125 | "LD_LIBRARY_PATH=/vendor/lib:/system/lib pm get-install-location", false, true); 126 | if (commandResult.result == 0 && commandResult.responseMsg != null && commandResult.responseMsg.length() > 0) { 127 | try { 128 | return Integer.parseInt(commandResult.responseMsg.substring(0, 1)); 129 | } catch (NumberFormatException e) { 130 | e.printStackTrace(); 131 | } 132 | } 133 | return APP_INSTALL_AUTO; 134 | } 135 | 136 | 137 | /** 138 | * get app package info 139 | */ 140 | public static PackageInfo getAppPackageInfo(Context context) { 141 | if (context != null) { 142 | PackageManager pm = context.getPackageManager(); 143 | if (pm != null) { 144 | PackageInfo pi; 145 | try { 146 | return pm.getPackageInfo(context.getPackageName(), 0); 147 | } catch (Exception e) { 148 | e.printStackTrace(); 149 | } 150 | } 151 | } 152 | return null; 153 | } 154 | 155 | /** 156 | * whether context is system application 157 | */ 158 | public static boolean isSystemApplication(Context context) { 159 | if (context == null) { 160 | return false; 161 | } 162 | return isSystemApplication(context, context.getPackageName()); 163 | } 164 | 165 | /** 166 | * whether packageName is system application 167 | */ 168 | public static boolean isSystemApplication(Context context, String packageName) { 169 | PackageManager packageManager = context.getPackageManager(); 170 | if (packageManager == null || packageName == null || packageName.length() == 0) { 171 | return false; 172 | } 173 | try { 174 | ApplicationInfo app = packageManager.getApplicationInfo(packageName, 0); 175 | return (app != null && (app.flags & ApplicationInfo.FLAG_SYSTEM) > 0); 176 | } catch (Exception e) { 177 | e.printStackTrace(); 178 | } 179 | return false; 180 | } 181 | 182 | /** 183 | * 获取已安装的全部应用信息 184 | */ 185 | public static List getInsatalledPackages(Context context) { 186 | return context.getPackageManager().getInstalledPackages(0); 187 | } 188 | 189 | /** 190 | * 获取已安装的全部应用信息 191 | */ 192 | public static boolean isInsatalled(Context context, String pkg) { 193 | if (!Check.isEmpty(pkg)) { 194 | List list = getInsatalledPackages(context); 195 | if (!Check.isEmpty(list)) { 196 | for (PackageInfo pi : list) { 197 | if (pkg.equalsIgnoreCase(pi.packageName)) { 198 | return true; 199 | } 200 | } 201 | } 202 | } 203 | return false; 204 | } 205 | 206 | /** 207 | * 获取指定程序信息 208 | */ 209 | public static ApplicationInfo getApplicationInfo(Context context, String pkg) { 210 | try { 211 | return context.getPackageManager().getApplicationInfo(pkg, 0); 212 | } catch (NameNotFoundException e) { 213 | e.printStackTrace(); 214 | } 215 | return null; 216 | } 217 | 218 | /** 219 | * 获取指定程序信息 220 | */ 221 | public static android.content.pm.PackageInfo getPackageInfo(Context context, String pkg) { 222 | try { 223 | return context.getPackageManager().getPackageInfo(pkg, 0); 224 | } catch (NameNotFoundException e) { 225 | e.printStackTrace(); 226 | } 227 | return null; 228 | } 229 | 230 | /** 231 | * 启动应用 232 | */ 233 | public static boolean startAppByPackageName(Context context, String packageName) { 234 | return startAppByPackageName(context, packageName, null); 235 | } 236 | 237 | /** 238 | * 启动应用 239 | */ 240 | public static boolean startAppByPackageName(Context context, String packageName, Map param) { 241 | android.content.pm.PackageInfo pi = null; 242 | try { 243 | pi = context.getPackageManager().getPackageInfo(packageName, 0); 244 | Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null); 245 | resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER); 246 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) { 247 | resolveIntent.setPackage(pi.packageName); 248 | } 249 | 250 | List apps = context.getPackageManager().queryIntentActivities(resolveIntent, 0); 251 | 252 | ResolveInfo ri = apps.iterator().next(); 253 | if (ri != null) { 254 | String packageName1 = ri.activityInfo.packageName; 255 | String className = ri.activityInfo.name; 256 | 257 | Intent intent = new Intent(Intent.ACTION_MAIN); 258 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 259 | intent.addCategory(Intent.CATEGORY_LAUNCHER); 260 | 261 | ComponentName cn = new ComponentName(packageName1, className); 262 | 263 | intent.setComponent(cn); 264 | if (param != null) { 265 | for (Map.Entry en : param.entrySet()) { 266 | intent.putExtra(en.getKey(), en.getValue()); 267 | } 268 | } 269 | context.startActivity(intent); 270 | return true; 271 | } 272 | } catch (Exception e) { 273 | e.printStackTrace(); 274 | Toast.makeText(context.getApplicationContext(), "启动失败", 275 | Toast.LENGTH_LONG).show(); 276 | } 277 | return false; 278 | } 279 | 280 | } 281 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/PollingUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.AlarmManager; 5 | import android.app.PendingIntent; 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.os.Build; 9 | import android.os.SystemClock; 10 | 11 | /** 12 | * @author MaTianyu 13 | * @date 2015-03-26 14 | */ 15 | public class PollingUtil { 16 | 17 | /** 18 | * 开启轮询 19 | */ 20 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 21 | public static void startPolling(Context context, int mills, PendingIntent pendingIntent) { 22 | AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 23 | manager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 24 | mills, pendingIntent); 25 | } 26 | 27 | /** 28 | * 停止轮询 29 | */ 30 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 31 | public static void stopPolling(Context context, PendingIntent pendingIntent) { 32 | AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 33 | manager.cancel(pendingIntent); 34 | } 35 | 36 | /** 37 | * 开启轮询服务 38 | */ 39 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 40 | public static void startPollingService(Context context, int mills, Class cls, String action) { 41 | Intent intent = new Intent(context, cls); 42 | intent.setAction(action); 43 | PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 44 | startPolling(context, mills, pendingIntent); 45 | } 46 | 47 | /** 48 | * 停止启轮询服务 49 | */ 50 | @TargetApi(Build.VERSION_CODES.CUPCAKE) 51 | public static void stopPollingService(Context context, Class cls, String action) { 52 | Intent intent = new Intent(context, cls); 53 | intent.setAction(action); 54 | PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 55 | stopPolling(context, pendingIntent); 56 | } 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/RandomUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * 随机工具类 7 | * modified form Trinea 8 | * @author trinea 9 | * @date 2014-12-10 10 | */ 11 | public class RandomUtil { 12 | public static final String NUMBERS_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 13 | public static final String NUMBERS = "0123456789"; 14 | public static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 15 | public static final String CAPITAL_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 16 | public static final String LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"; 17 | 18 | private RandomUtil() { 19 | throw new AssertionError(); 20 | } 21 | 22 | /** 23 | * get a fixed-length random string, its a mixture of uppercase, lowercase letters and numbers 24 | * 25 | * @param length 26 | * @return 27 | * @see RandomUtil#getRandom(String source, int length) 28 | */ 29 | public static String getRandomNumbersAndLetters(int length) { 30 | return getRandom(NUMBERS_AND_LETTERS, length); 31 | } 32 | 33 | /** 34 | * get a fixed-length random string, its a mixture of numbers 35 | * 36 | * @param length 37 | * @return 38 | * @see RandomUtil#getRandom(String source, int length) 39 | */ 40 | public static String getRandomNumbers(int length) { 41 | return getRandom(NUMBERS, length); 42 | } 43 | 44 | /** 45 | * get a fixed-length random string, its a mixture of uppercase and lowercase letters 46 | * 47 | * @param length 48 | * @return 49 | * @see RandomUtil#getRandom(String source, int length) 50 | */ 51 | public static String getRandomLetters(int length) { 52 | return getRandom(LETTERS, length); 53 | } 54 | 55 | /** 56 | * get a fixed-length random string, its a mixture of uppercase letters 57 | * 58 | * @param length 59 | * @return 60 | * @see RandomUtil#getRandom(String source, int length) 61 | */ 62 | public static String getRandomCapitalLetters(int length) { 63 | return getRandom(CAPITAL_LETTERS, length); 64 | } 65 | 66 | /** 67 | * get a fixed-length random string, its a mixture of lowercase letters 68 | * 69 | * @param length 70 | * @return 71 | * @see RandomUtil#getRandom(String source, int length) 72 | */ 73 | public static String getRandomLowerCaseLetters(int length) { 74 | return getRandom(LOWER_CASE_LETTERS, length); 75 | } 76 | 77 | /** 78 | * get a fixed-length random string, its a mixture of chars in source 79 | * 80 | * @param source 81 | * @param length 82 | * @return

    83 | *
  • if source is null or empty, return null
  • 84 | *
  • else see {@link RandomUtil#getRandom(char[] sourceChar, int length)}
  • 85 | *
86 | */ 87 | public static String getRandom(String source, int length) { 88 | return source == null ? null : getRandom(source.toCharArray(), length); 89 | } 90 | 91 | /** 92 | * get a fixed-length random string, its a mixture of chars in sourceChar 93 | * 94 | * @param sourceChar 95 | * @param length 96 | * @return
    97 | *
  • if sourceChar is null or empty, return null
  • 98 | *
  • if length less than 0, return null
  • 99 | *
100 | */ 101 | public static String getRandom(char[] sourceChar, int length) { 102 | if (sourceChar == null || sourceChar.length == 0 || length < 0) { 103 | return null; 104 | } 105 | 106 | StringBuilder str = new StringBuilder(length); 107 | Random random = new Random(); 108 | for (int i = 0; i < length; i++) { 109 | str.append(sourceChar[random.nextInt(sourceChar.length)]); 110 | } 111 | return str.toString(); 112 | } 113 | 114 | /** 115 | * get random int between 0 and max 116 | * 117 | * @param max 118 | * @return
    119 | *
  • if max <= 0, return 0
  • 120 | *
  • else return random int between 0 and max
  • 121 | *
122 | */ 123 | public static int getRandom(int max) { 124 | return getRandom(0, max); 125 | } 126 | 127 | /** 128 | * get random int between min and max 129 | * 130 | * @param min 131 | * @param max 132 | * @return
    133 | *
  • if min > max, return 0
  • 134 | *
  • if min == max, return min
  • 135 | *
  • else return random int between min and max
  • 136 | *
137 | */ 138 | public static int getRandom(int min, int max) { 139 | if (min > max) { 140 | return 0; 141 | } 142 | if (min == max) { 143 | return min; 144 | } 145 | return min + new Random().nextInt(max - min); 146 | } 147 | 148 | /** 149 | * Shuffling algorithm, Randomly permutes the specified array using a default source of randomness 150 | */ 151 | public static boolean shuffle(Object[] objArray) { 152 | if (objArray == null) { 153 | return false; 154 | } 155 | return shuffle(objArray, getRandom(objArray.length)); 156 | } 157 | 158 | /** 159 | * Shuffling algorithm, Randomly permutes the specified array 160 | */ 161 | public static boolean shuffle(Object[] objArray, int shuffleCount) { 162 | int length; 163 | if (objArray == null || shuffleCount < 0 || (length = objArray.length) < shuffleCount) { 164 | return false; 165 | } 166 | 167 | for (int i = 1; i <= shuffleCount; i++) { 168 | int random = getRandom(length - i); 169 | Object temp = objArray[length - i]; 170 | objArray[length - i] = objArray[random]; 171 | objArray[random] = temp; 172 | } 173 | return true; 174 | } 175 | 176 | /** 177 | * Shuffling algorithm, Randomly permutes the specified int array using a default source of randomness 178 | */ 179 | public static int[] shuffle(int[] intArray) { 180 | if (intArray == null) { 181 | return null; 182 | } 183 | 184 | return shuffle(intArray, getRandom(intArray.length)); 185 | } 186 | 187 | /** 188 | * Shuffling algorithm, Randomly permutes the specified int array 189 | */ 190 | public static int[] shuffle(int[] intArray, int shuffleCount) { 191 | int length; 192 | if (intArray == null || shuffleCount < 0 || (length = intArray.length) < shuffleCount) { 193 | return null; 194 | } 195 | 196 | int[] out = new int[shuffleCount]; 197 | for (int i = 1; i <= shuffleCount; i++) { 198 | int random = getRandom(length - i); 199 | out[i - 1] = intArray[random]; 200 | int temp = intArray[length - i]; 201 | intArray[length - i] = intArray[random]; 202 | intArray[random] = temp; 203 | } 204 | return out; 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/SdCardUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.annotation.TargetApi; 4 | import android.os.Build; 5 | import android.os.Environment; 6 | import android.os.StatFs; 7 | import com.litesuits.android.log.Log; 8 | 9 | import java.io.*; 10 | import java.util.ArrayList; 11 | 12 | /** 13 | * Get SD card info. 14 | * 15 | * @author MaTianyu 16 | * @date 2015-04-19 17 | */ 18 | public class SdCardUtil { 19 | private static final String TAG = SdCardUtil.class.getSimpleName(); 20 | 21 | /** 22 | * is sd card available. 23 | * @return true if available 24 | */ 25 | public boolean isSdCardAvailable() { 26 | return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); 27 | } 28 | 29 | /** 30 | * Get {@link android.os.StatFs}. 31 | */ 32 | public static StatFs getStatFs(String path) { 33 | return new StatFs(path); 34 | } 35 | 36 | /** 37 | * Get phone data path. 38 | */ 39 | public static String getDataPath() { 40 | return Environment.getDataDirectory().getPath(); 41 | 42 | } 43 | 44 | /** 45 | * Get SD card path. 46 | */ 47 | public static String getNormalSDCardPath() { 48 | return Environment.getExternalStorageDirectory().getPath(); 49 | } 50 | 51 | /** 52 | * Get SD card path by CMD. 53 | */ 54 | public static String getSDCardPath() { 55 | String cmd = "cat /proc/mounts"; 56 | String sdcard = null; 57 | Runtime run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象 58 | BufferedReader bufferedReader = null; 59 | try { 60 | Process p = run.exec(cmd);// 启动另一个进程来执行命令 61 | bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getInputStream()))); 62 | String lineStr; 63 | while ((lineStr = bufferedReader.readLine()) != null) { 64 | Log.i(TAG, "proc/mounts: " + lineStr); 65 | if (lineStr.contains("sdcard") 66 | && lineStr.contains(".android_secure")) { 67 | String[] strArray = lineStr.split(" "); 68 | if (strArray.length >= 5) { 69 | sdcard = strArray[1].replace("/.android_secure", ""); 70 | Log.i(TAG, "find sd card path: " + sdcard); 71 | return sdcard; 72 | } 73 | } 74 | if (p.waitFor() != 0 && p.exitValue() == 1) { 75 | // p.exitValue()==0表示正常结束,1:非正常结束 76 | Log.e(TAG, cmd + " 命令执行失败"); 77 | } 78 | } 79 | } catch (Exception e) { 80 | e.printStackTrace(); 81 | } finally { 82 | try { 83 | if (bufferedReader != null) { 84 | bufferedReader.close(); 85 | } 86 | } catch (IOException e) { 87 | e.printStackTrace(); 88 | } 89 | } 90 | sdcard = Environment.getExternalStorageDirectory().getPath(); 91 | Log.i(TAG, "not find sd card path return default: " + sdcard); 92 | return sdcard; 93 | } 94 | 95 | /** 96 | * Get SD card path list. 97 | */ 98 | public static ArrayList getSDCardPathEx() { 99 | ArrayList list = new ArrayList(); 100 | try { 101 | Runtime runtime = Runtime.getRuntime(); 102 | Process proc = runtime.exec("mount"); 103 | InputStream is = proc.getInputStream(); 104 | InputStreamReader isr = new InputStreamReader(is); 105 | String line; 106 | BufferedReader br = new BufferedReader(isr); 107 | while ((line = br.readLine()) != null) { 108 | Log.i(TAG, "mount: " + line); 109 | if (line.contains("secure")) { 110 | continue; 111 | } 112 | if (line.contains("asec")) { 113 | continue; 114 | } 115 | 116 | if (line.contains("fat")) { 117 | String columns[] = line.split(" "); 118 | if (columns.length > 1) { 119 | list.add("*" + columns[1]); 120 | } 121 | } else if (line.contains("fuse")) { 122 | String columns[] = line.split(" "); 123 | if (columns.length > 1) { 124 | list.add(columns[1]); 125 | } 126 | } 127 | } 128 | } catch (FileNotFoundException e) { 129 | e.printStackTrace(); 130 | } catch (IOException e) { 131 | e.printStackTrace(); 132 | } 133 | return list; 134 | } 135 | 136 | /** 137 | * Get available size of SD card. 138 | */ 139 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 140 | public static long getAvailableSize(String path) { 141 | try { 142 | File base = new File(path); 143 | StatFs stat = new StatFs(base.getPath()); 144 | return stat.getBlockSizeLong() * stat.getAvailableBlocksLong(); 145 | } catch (Exception e) { 146 | e.printStackTrace(); 147 | } 148 | return 0; 149 | } 150 | 151 | /** 152 | * Get SD card info detail. 153 | */ 154 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 155 | public static SDCardInfo getSDCardInfo() { 156 | SDCardInfo sd = new SDCardInfo(); 157 | String state = Environment.getExternalStorageState(); 158 | if (Environment.MEDIA_MOUNTED.equals(state)) { 159 | sd.isExist = true; 160 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { 161 | File sdcardDir = Environment.getExternalStorageDirectory(); 162 | StatFs sf = new StatFs(sdcardDir.getPath()); 163 | 164 | sd.totalBlocks = sf.getBlockCountLong(); 165 | sd.blockByteSize = sf.getBlockSizeLong(); 166 | 167 | sd.availableBlocks = sf.getAvailableBlocksLong(); 168 | sd.availableBytes = sf.getAvailableBytes(); 169 | 170 | sd.freeBlocks = sf.getFreeBlocksLong(); 171 | sd.freeBytes = sf.getFreeBytes(); 172 | 173 | sd.totalBytes = sf.getTotalBytes(); 174 | } 175 | } 176 | if (Log.isPrint) { 177 | Log.i(TAG, sd.toString()); 178 | } 179 | return sd; 180 | } 181 | 182 | 183 | /** 184 | * see more {@link android.os.StatFs} 185 | */ 186 | public static class SDCardInfo { 187 | public boolean isExist; 188 | public long totalBlocks; 189 | public long freeBlocks; 190 | public long availableBlocks; 191 | 192 | public long blockByteSize; 193 | 194 | public long totalBytes; 195 | public long freeBytes; 196 | public long availableBytes; 197 | 198 | @Override 199 | public String toString() { 200 | return "SDCardInfo{" + 201 | "isExist=" + isExist + 202 | ", totalBlocks=" + totalBlocks + 203 | ", freeBlocks=" + freeBlocks + 204 | ", availableBlocks=" + availableBlocks + 205 | ", blockByteSize=" + blockByteSize + 206 | ", totalBytes=" + totalBytes + 207 | ", freeBytes=" + freeBytes + 208 | ", availableBytes=" + availableBytes + 209 | '}'; 210 | } 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/ShellUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.DataOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStreamReader; 7 | import java.util.List; 8 | 9 | /** 10 | * modified form Trinea 11 | * @author trinea 12 | * @date 2014-12-10 13 | */ 14 | public class ShellUtil { 15 | 16 | /** 17 | * check whether has root permission 18 | */ 19 | public static boolean hasRootPermission() { 20 | return execCommand("echo root", true, false).result == 0; 21 | } 22 | 23 | public static CommandResult execCommand(String command, boolean isRoot) { 24 | return execCommand(new String[] {command}, isRoot, true); 25 | } 26 | 27 | public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) { 28 | return execCommand(new String[]{command}, isRoot, isNeedResultMsg); 29 | } 30 | 31 | public static CommandResult execCommand(List commands, boolean isRoot, boolean isNeedResultMsg) { 32 | return execCommand(commands == null ? null : commands.toArray(new String[]{}), isRoot, isNeedResultMsg); 33 | } 34 | 35 | /** 36 | * execute shell commands 37 | * {@link CommandResult#result} is -1, there maybe some excepiton. 38 | * 39 | * @param commands command array 40 | * @param isRoot whether need to run with root 41 | * @param needResponse whether need result msg 42 | */ 43 | public static CommandResult execCommand(String[] commands, boolean isRoot, boolean needResponse) { 44 | int result = -1; 45 | if (commands == null || commands.length == 0) { 46 | return new CommandResult(result, null, "空命令"); 47 | } 48 | 49 | Process process = null; 50 | BufferedReader successResult = null; 51 | BufferedReader errorResult = null; 52 | StringBuilder successMsg = null; 53 | StringBuilder errorMsg = null; 54 | 55 | DataOutputStream os = null; 56 | try { 57 | process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH); 58 | os = new DataOutputStream(process.getOutputStream()); 59 | for (String command : commands) { 60 | if (command == null) { 61 | continue; 62 | } 63 | 64 | // donnot use os.writeBytes(commmand), avoid chinese charset error 65 | os.write(command.getBytes()); 66 | os.writeBytes(COMMAND_LINE_END); 67 | os.flush(); 68 | } 69 | os.writeBytes(COMMAND_EXIT); 70 | os.flush(); 71 | 72 | result = process.waitFor(); 73 | if (needResponse) { 74 | successMsg = new StringBuilder(); 75 | errorMsg = new StringBuilder(); 76 | successResult = new BufferedReader(new InputStreamReader(process.getInputStream())); 77 | errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream())); 78 | String s; 79 | while ((s = successResult.readLine()) != null) { 80 | successMsg.append(s); 81 | } 82 | while ((s = errorResult.readLine()) != null) { 83 | errorMsg.append(s); 84 | } 85 | } 86 | } catch (IOException e) { 87 | e.printStackTrace(); 88 | } catch (Exception e) { 89 | e.printStackTrace(); 90 | } finally { 91 | try { 92 | if (errorResult != null) { 93 | errorResult.close(); 94 | } 95 | if (successResult != null) { 96 | successResult.close(); 97 | } 98 | if (os != null) { 99 | os.close(); 100 | } 101 | } catch (IOException e) { 102 | e.printStackTrace(); 103 | } finally { 104 | if (process != null) { 105 | process.destroy(); 106 | } 107 | } 108 | 109 | } 110 | return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null 111 | : errorMsg.toString()); 112 | } 113 | 114 | public static class CommandResult { 115 | 116 | public int result; 117 | public String responseMsg; 118 | public String errorMsg; 119 | 120 | public CommandResult(int result) { 121 | this.result = result; 122 | } 123 | 124 | public CommandResult(int result, String responseMsg, String errorMsg) { 125 | this.result = result; 126 | this.responseMsg = responseMsg; 127 | this.errorMsg = errorMsg; 128 | } 129 | } 130 | 131 | public static final String COMMAND_SU = "su"; 132 | public static final String COMMAND_SH = "sh"; 133 | public static final String COMMAND_EXIT = "exit\n"; 134 | public static final String COMMAND_LINE_END = "\n"; 135 | 136 | 137 | } 138 | -------------------------------------------------------------------------------- /app/src/main/java/com/litesuits/common/utils/VibrateUtil.java: -------------------------------------------------------------------------------- 1 | package com.litesuits.common.utils; 2 | 3 | import android.content.Context; 4 | import android.os.Vibrator; 5 | 6 | /** 7 | *

All methods requires the caller to hold the permission 8 | * {@link android.Manifest.permission#VIBRATE}. 9 | * 10 | * @author MaTianyu 11 | * @date 2014-11-21 12 | */ 13 | public class VibrateUtil { 14 | 15 | /** 16 | * Vibrate constantly for the specified period of time. 17 | *

This method requires the caller to hold the permission 18 | * {@link android.Manifest.permission#VIBRATE}. 19 | * 20 | * @param milliseconds The number of milliseconds to vibrate. 21 | */ 22 | public static void vibrate(Context context, long milliseconds) { 23 | Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); 24 | vibrator.vibrate(milliseconds); 25 | } 26 | 27 | /** 28 | * Vibrate with a given pattern. 29 | *

30 | *

31 | * Pass in an array of ints that are the durations for which to turn on or off 32 | * the vibrator in milliseconds. The first value indicates the number of milliseconds 33 | * to wait before turning the vibrator on. The next value indicates the number of milliseconds 34 | * for which to keep the vibrator on before turning it off. Subsequent values alternate 35 | * between durations in milliseconds to turn the vibrator off or to turn the vibrator on. 36 | *

37 | * To cause the pattern to repeat, pass the index into the pattern array at which 38 | * to start the repeat, or -1 to disable repeating. 39 | *

40 | *

This method requires the caller to hold the permission 41 | * {@link android.Manifest.permission#VIBRATE}. 42 | * 43 | * @param pattern an array of longs of times for which to turn the vibrator on or off. 44 | * @param repeat the index into pattern at which to repeat, or -1 if 45 | * you don't want to repeat. 46 | */ 47 | public static void vibrate(Context context, long[] pattern, int repeat) { 48 | Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); 49 | vibrator.vibrate(pattern, repeat); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | android-common 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | } 5 | dependencies { 6 | classpath 'com.android.tools.build:gradle:2.1.0' 7 | classpath 'com.novoda:bintray-release:0.3.4' 8 | } 9 | } 10 | 11 | allprojects { 12 | repositories { 13 | jcenter() 14 | } 15 | tasks.withType(Javadoc) { 16 | options.addStringOption('Xdoclint:none', '-quiet') 17 | options.addStringOption('encoding', 'UTF-8') 18 | } 19 | } 20 | 21 | task clean(type: Delete) { 22 | delete rootProject.buildDir 23 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/litesuits/android-common/4aa89fdf605c7f9d1f5a50f97212f1d4756450ad/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-2.10-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | --------------------------------------------------------------------------------