├── .gitignore ├── .idea ├── caches │ └── build_file_checksums.ser ├── codeStyles │ └── Project.xml ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── dictionaries │ └── wljde.xml ├── encodings.xml ├── gradle.xml ├── inspectionProfiles │ ├── Project_Default.xml │ └── profiles_settings.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── wanglijun │ │ └── vip │ │ └── androidutils │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── wanglijun │ │ │ └── vip │ │ │ └── androidutils │ │ │ ├── Application.java │ │ │ ├── MainActivity.java │ │ │ └── utils │ │ │ ├── AppUtils.java │ │ │ ├── AssetsUtils.java │ │ │ ├── BASE64Utils.java │ │ │ ├── BitmapUtils.java │ │ │ ├── CameraUtils.java │ │ │ ├── ClickUtil.java │ │ │ ├── CollectionUtils.java │ │ │ ├── ConstUtils.java │ │ │ ├── CpuUtils.java │ │ │ ├── DateToStringUtils.java │ │ │ ├── DeviceUtils.java │ │ │ ├── DisplayUtils.java │ │ │ ├── FileLog.java │ │ │ ├── FileSize.java │ │ │ ├── FileUtils.java │ │ │ ├── IOUtils.java │ │ │ ├── JsonUtils.java │ │ │ ├── KeyboardUtil.java │ │ │ ├── LogUtils.java │ │ │ ├── MD5Utils.java │ │ │ ├── MapUtils.java │ │ │ ├── NetWork.java │ │ │ ├── NetWorkUtils.java │ │ │ ├── NumberUtils.java │ │ │ ├── ObjectUtils.java │ │ │ ├── PackageManagerUtil.java │ │ │ ├── PackageUtils.java │ │ │ ├── RandomUtils.java │ │ │ ├── SHA1Utils.java │ │ │ ├── SPUtil.java │ │ │ ├── SerializableUtils.java │ │ │ ├── ServiceUtils.java │ │ │ ├── StringUtils.java │ │ │ ├── SystemUtils.java │ │ │ ├── TimeUtils.java │ │ │ ├── ToastUtil.java │ │ │ └── VerifyUtils.java │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── wanglijun │ └── vip │ └── androidutils │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.idea/caches/build_file_checksums.ser: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglijun93/AndroidUtils/4781e11c503ddecbd752f40bc8909d88f9ed110c/.idea/caches/build_file_checksums.ser -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | xmlns:android 14 | 15 | ^$ 16 | 17 | 18 | 19 |
20 |
21 | 22 | 23 | 24 | xmlns:.* 25 | 26 | ^$ 27 | 28 | 29 | BY_NAME 30 | 31 |
32 |
33 | 34 | 35 | 36 | .*:id 37 | 38 | http://schemas.android.com/apk/res/android 39 | 40 | 41 | 42 |
43 |
44 | 45 | 46 | 47 | .*:name 48 | 49 | http://schemas.android.com/apk/res/android 50 | 51 | 52 | 53 |
54 |
55 | 56 | 57 | 58 | name 59 | 60 | ^$ 61 | 62 | 63 | 64 |
65 |
66 | 67 | 68 | 69 | style 70 | 71 | ^$ 72 | 73 | 74 | 75 |
76 |
77 | 78 | 79 | 80 | .* 81 | 82 | ^$ 83 | 84 | 85 | BY_NAME 86 | 87 |
88 |
89 | 90 | 91 | 92 | .* 93 | 94 | http://schemas.android.com/apk/res/android 95 | 96 | 97 | ANDROID_ATTRIBUTE_ORDER 98 | 99 |
100 |
101 | 102 | 103 | 104 | .* 105 | 106 | .* 107 | 108 | 109 | BY_NAME 110 | 111 |
112 |
113 |
114 |
115 |
116 |
-------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/dictionaries/wljde.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 37 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 24 | 41 | 42 | 43 | 44 | 45 | 46 | 48 | 49 | 60 | 61 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AndroidUtils 2 | ## 我的CSDN博客地址:http://blog.csdn.net/mynamelijun 3 | 4 | 一个Android开发基础的工具类,是每一个新项目开启都需要的,以便于提高工作效率,减少不必要的重复书写代码(其实是我懒)。 5 | 6 | --- 7 | 8 | ## 目前本工具类涵盖的有一下内容 9 | ``` 10 | Application 全局上下文 11 | APPUtils App 相关信息,包括版本名称、版本号、包名等等 12 | AssetsUtils Assets获取的相关操作类 13 | BASE64Utils bese64的转换 14 | BitmapUtils bitmap图片的相互转换工具类 15 | CameraUtils 打开相机相关类 16 | CollectionUtils 集合操作 17 | CpuUtils 获取CPU信息 18 | DateToStringUtils 时间转换工具类 19 | DeviceUtils 获取设备信息 20 | DisplayUtils 屏幕相关 21 | FileUtils 文件工具类 22 | IOUtils io操作 23 | JsonUtils json的转换 24 | LogUtils log工具类 25 | MapUtils Map相关操作 26 | MD5Utils MD5相关操作 27 | NetWork 判断手机网络类型,是否连接 28 | NetWorkUtils 获取网络状态 29 | NumberUtils 数字格式化操作类 30 | ObjectUtils 对象操作 31 | PackageUtils 包的相关操作 32 | RandomUtils 获取随机数操作类 33 | SerializableUtils 序列化和反序列化操作类 34 | ServiceUtils 服务开启与关闭 35 | SHA1Utils SHA1 操作类 36 | SPUtils SharedPreferences统一管理类 37 | StringUtils 字符串操作 38 | SystemUtils 获取系统信息工具类 39 | ToastUtils Toast封装类 40 | VerifyUtils 验证数据合法性 41 | ``` 42 | --- 43 | ## 权限 Permission 44 | ``` 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | 5 | android { 6 | compileSdkVersion 29 7 | buildToolsVersion "29.0.3" 8 | defaultConfig { 9 | applicationId "wanglijun.vip.androidutils" 10 | minSdkVersion 19 11 | targetSdkVersion 29 12 | versionCode 2 13 | versionName "2.0" 14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | compile fileTree(include: ['*.jar'], dir: 'libs') 26 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.1', { 27 | exclude group: 'com.android.support', module: 'support-annotations' 28 | }) 29 | implementation 'com.google.code.gson:gson:2.2.4' 30 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 31 | implementation 'androidx.appcompat:appcompat:1.1.0' 32 | implementation 'androidx.core:core-ktx:1.2.0' 33 | } 34 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in E:\Android_Tools\Studio\sdk\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/wanglijun/vip/androidutils/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("wanglijun.vip.androidutils", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/Application.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils; 2 | 3 | 4 | import android.content.Context; 5 | import android.os.Handler; 6 | 7 | /** 8 | * @author wlj 9 | * @date 2017/3/28 10 | * @email wanglijundev@gmail.com 11 | * @packagename wanglijun.vip.androidutils 12 | * @description 全局上下文 13 | */ 14 | public class Application extends android.app.Application { 15 | /** 16 | * 这是一行没用代码 17 | */ 18 | public static Context context; 19 | public static Handler mainHandler; 20 | 21 | 22 | @Override 23 | public void onCreate() { 24 | super.onCreate(); 25 | context = this; 26 | mainHandler = new Handler(); 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/MainActivity.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | 6 | /** 7 | * @author wanglijun 8 | */ 9 | public class MainActivity extends Activity { 10 | 11 | 12 | @Override 13 | protected void onCreate(Bundle savedInstanceState) { 14 | super.onCreate(savedInstanceState); 15 | setContentView(R.layout.activity_main); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/AppUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.app.ActivityManager; 4 | import android.content.ComponentName; 5 | import android.content.Context; 6 | import android.content.pm.ApplicationInfo; 7 | import android.content.pm.PackageInfo; 8 | import android.content.pm.PackageManager; 9 | import android.graphics.drawable.Drawable; 10 | 11 | import java.util.List; 12 | 13 | import javax.security.auth.x500.X500Principal; 14 | 15 | /** 16 | * @author: wlj 17 | * @Date: 2017-03-28 18 | * @email: wanglijundev@gmail.com 19 | * @desc: App 相关信息,包括版本名称、版本号、包名等等 20 | */ 21 | 22 | public class AppUtils { 23 | private final static X500Principal DEBUG_DN = new X500Principal( 24 | "CN=Android Debug,O=Android,C=US"); 25 | 26 | /** 27 | * Get version name 28 | * 29 | * @param context 30 | * @return 31 | */ 32 | public static String getVersionName(Context context) { 33 | PackageInfo info; 34 | try { 35 | info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); 36 | return info.versionName; 37 | } catch (PackageManager.NameNotFoundException e) { 38 | e.printStackTrace(); 39 | } 40 | return ""; 41 | } 42 | 43 | /** 44 | * Get version code 45 | * 46 | * @param context 47 | * @return 48 | */ 49 | public static int getVersionCode(Context context) { 50 | PackageInfo info; 51 | try { 52 | info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); 53 | return info.versionCode; 54 | } catch (PackageManager.NameNotFoundException e) { 55 | e.printStackTrace(); 56 | } 57 | return 0; 58 | } 59 | 60 | /** 61 | * Get package name 62 | * 63 | * @param context 64 | * @return 65 | */ 66 | public static String getPackageName(Context context) { 67 | return context.getPackageName(); 68 | } 69 | 70 | /** 71 | * Get icon 72 | * 73 | * @param context 74 | * @return 75 | */ 76 | public static Drawable getIcon(Context context) { 77 | return getAppIcon(context, getPackageName(context)); 78 | } 79 | 80 | /** 81 | * Get app icon 82 | * 83 | * @param context 84 | * @param packageName 85 | * @return 86 | */ 87 | public static Drawable getAppIcon(Context context, String packageName) { 88 | try { 89 | PackageManager pm = context.getPackageManager(); 90 | ApplicationInfo info = pm.getApplicationInfo(packageName, 0); 91 | return info.loadIcon(pm); 92 | } catch (PackageManager.NameNotFoundException e) { 93 | e.printStackTrace(); 94 | } 95 | return null; 96 | } 97 | 98 | /** 99 | * Get app version name 100 | * 101 | * @param context 102 | * @param packageName 103 | * @return 104 | */ 105 | public static String getAppVersionName(Context context, String packageName) { 106 | try { 107 | PackageManager pm = context.getPackageManager(); 108 | PackageInfo packageInfo = pm.getPackageInfo(packageName, 0); 109 | return packageInfo.versionName; 110 | } catch (PackageManager.NameNotFoundException e) { 111 | e.printStackTrace(); 112 | } 113 | return null; 114 | } 115 | 116 | /** 117 | * Get app version code 118 | * 119 | * @param context 120 | * @param packageName 121 | * @return 122 | */ 123 | public static int getAppVersionCode(Context context, String packageName) { 124 | try { 125 | PackageManager pm = context.getPackageManager(); 126 | PackageInfo packageInfo = pm.getPackageInfo(packageName, 0); 127 | return packageInfo.versionCode; 128 | } catch (PackageManager.NameNotFoundException e) { 129 | e.printStackTrace(); 130 | } 131 | return -1; 132 | } 133 | 134 | /** 135 | * Get app name 136 | * 137 | * @param context 138 | * @param packageName 139 | * @return 140 | */ 141 | public static String getAppName(Context context, String packageName) { 142 | try { 143 | PackageManager pm = context.getPackageManager(); 144 | ApplicationInfo info = pm.getApplicationInfo(packageName, 0); 145 | return info.loadLabel(pm).toString(); 146 | } catch (PackageManager.NameNotFoundException e) { 147 | e.printStackTrace(); 148 | } 149 | return null; 150 | } 151 | 152 | /** 153 | * Get app permission 154 | * 155 | * @param context 156 | * @param packageName 157 | * @return 158 | */ 159 | public static String[] getAppPermission(Context context, String packageName) { 160 | try { 161 | PackageManager pm = context.getPackageManager(); 162 | PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); 163 | return packageInfo.requestedPermissions; 164 | } catch (PackageManager.NameNotFoundException e) { 165 | e.printStackTrace(); 166 | } 167 | return null; 168 | } 169 | 170 | /** 171 | * Get app signature 172 | * 173 | * @param context 174 | * @param packageName 175 | * @return 176 | */ 177 | public static String getAppSignature(Context context, String packageName) { 178 | try { 179 | PackageManager pm = context.getPackageManager(); 180 | PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); 181 | return packageInfo.signatures[0].toCharsString(); 182 | } catch (PackageManager.NameNotFoundException e) { 183 | e.printStackTrace(); 184 | } 185 | return null; 186 | } 187 | 188 | /** 189 | * Judge whether an app is dubuggable 190 | * 191 | * @param context 192 | * @return 193 | */ 194 | public static boolean isApkDebuggable(Context context) { 195 | try { 196 | ApplicationInfo info = context.getApplicationInfo(); 197 | return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 198 | } catch (Exception e) { 199 | 200 | } 201 | return false; 202 | } 203 | 204 | /** 205 | * Judge whether an app is debugAble by package name 206 | * 207 | * @param context 208 | * @param packageName 209 | * @return 210 | */ 211 | public static boolean isApkDebugAble(Context context, String packageName) { 212 | try { 213 | PackageInfo packageInfo = context.getPackageManager().getPackageInfo( 214 | packageName, PackageManager.GET_ACTIVITIES); 215 | if (packageInfo != null) { 216 | ApplicationInfo info = packageInfo.applicationInfo; 217 | return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 218 | } 219 | } catch (Exception e) { 220 | } 221 | return false; 222 | } 223 | 224 | /** 225 | * Judge whether an app is in background 226 | * 227 | * @param context 228 | * @return 229 | */ 230 | public static boolean isAppInBackground(Context context) { 231 | ActivityManager am = (ActivityManager) context 232 | .getSystemService(Context.ACTIVITY_SERVICE); 233 | List taskList = am.getRunningTasks(1); 234 | if (taskList != null && !taskList.isEmpty()) { 235 | ComponentName topActivity = taskList.get(0).topActivity; 236 | if (topActivity != null 237 | && !topActivity.getPackageName().equals( 238 | context.getPackageName())) { 239 | return true; 240 | } 241 | } 242 | return false; 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/AssetsUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.content.Context; 4 | import android.content.res.AssetManager; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.io.InputStreamReader; 10 | import java.nio.charset.Charset; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | * @author wlj 16 | * @date 2017/3/29 17 | * @email wanglijundev@gmail.com 18 | * @packagename wanglijun.vip.androidutils.utils 19 | * @desc: Assets获取的相关操作类 20 | */ 21 | 22 | public class AssetsUtils { 23 | private static final String ENCODING = "UTF-8"; 24 | /** 25 | * 从assets获取文件 26 | * 27 | * @param context 28 | * @param fileName 29 | * @return 30 | * @throws IOException 31 | */ 32 | public static InputStream getFileFromAssets(Context context, String fileName) throws IOException { 33 | AssetManager am = context.getAssets(); 34 | return am.open(fileName); 35 | } 36 | 37 | /** 38 | * 从assets获取文本文件 39 | * 40 | * @param context 41 | * @param fileName 42 | * @return 43 | */ 44 | public static String getTextFromAssets(Context context, String fileName) { 45 | String result = null; 46 | try { 47 | InputStream in = getFileFromAssets(context, fileName); 48 | int length = in.available(); 49 | byte[] buffer = new byte[length]; 50 | in.read(buffer); 51 | result = new String(buffer, Charset.forName(ENCODING)); 52 | } catch (IOException e) { 53 | e.printStackTrace(); 54 | } 55 | return result; 56 | } 57 | 58 | /** 59 | * 从assets获取文本文件 60 | * 61 | * @param context 62 | * @param fileName 63 | * @return 64 | */ 65 | public static String getTextFromAssets2(Context context, String fileName) { 66 | try { 67 | InputStreamReader inputReader = new InputStreamReader(getFileFromAssets(context, fileName)); 68 | BufferedReader bufReader = new BufferedReader(inputReader); 69 | String line = ""; 70 | StringBuilder result = new StringBuilder(); 71 | while ((line = bufReader.readLine()) != null) { 72 | result.append(line); 73 | } 74 | return result.toString(); 75 | } catch (IOException e) { 76 | e.printStackTrace(); 77 | } 78 | return null; 79 | } 80 | 81 | /** 82 | * Parse a json file in the assets to ArrayList 83 | * 解析json文件成ArrayList,在assets中 84 | * @param context 85 | * @param jsonName 86 | * @return 87 | */ 88 | public static ArrayList parseJsonToArrayList(Context context, String jsonName) { 89 | String json = getTextFromAssets(context, jsonName); 90 | return JsonUtils.jsonToArrayList(json); 91 | } 92 | 93 | /** 94 | * Parse a json file in the assets to List 95 | * 解析json文件成List,在assets中 96 | * @param context 97 | * @param jsonName 98 | * @return 99 | */ 100 | public static List parseJsonToList(Context context, String jsonName) { 101 | String json = getTextFromAssets(context, jsonName); 102 | return JsonUtils.jsonToList(json); 103 | } 104 | 105 | /** 106 | * Parse a json file in the assets to Bean 107 | * 解析assets中的json文件 108 | * @param context 109 | * @param jsonName 110 | * @param clazz 111 | * @return 112 | */ 113 | public static T parseJsonToObject(Context context, String jsonName, Class clazz) { 114 | String json = getTextFromAssets(context, jsonName); 115 | return JsonUtils.jsonToObject(json, clazz); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/BASE64Utils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.util.Base64; 4 | 5 | /** 6 | * @author wlj 7 | * @date 2017/3/29 8 | * @email wanglijundev@gmail.com 9 | * @packagename wanglijun.vip.androidutils.utils 10 | * @desc: bese64的转换 11 | */ 12 | 13 | public class BASE64Utils { 14 | /** 15 | * base64编码 16 | * 17 | * @param input 18 | * @return 19 | */ 20 | public static byte[] encodeBase64(byte[] input) { 21 | return Base64.encode(input, Base64.DEFAULT); 22 | } 23 | 24 | /** 25 | * base64编码 26 | * 27 | * @param s 28 | * @return 29 | */ 30 | public static String encodeBase64(String s) { 31 | return Base64.encodeToString(s.getBytes(), Base64.DEFAULT); 32 | } 33 | 34 | /** 35 | * base64解码 36 | * 37 | * @param input 38 | * @return 39 | */ 40 | public static byte[] decodeBase64(byte[] input) { 41 | return Base64.decode(input, Base64.DEFAULT); 42 | } 43 | 44 | /** 45 | * base64解码 46 | * 47 | * @param s 48 | * @return 49 | */ 50 | public static String decodeBase64(String s) { 51 | return new String(Base64.decode(s, Base64.DEFAULT)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/CameraUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.net.Uri; 6 | import android.provider.MediaStore; 7 | 8 | import java.io.File; 9 | 10 | /** 11 | * @author wlj 12 | * @date 2017/3/29 13 | * @email wanglijundev@gmail.com 14 | * @packagename wanglijun.vip.androidutils.utils 15 | * @desc: 打开相机相关类 16 | */ 17 | 18 | public class CameraUtils { 19 | public static final int CAMERA_REQ_CODE = 0x0011; 20 | 21 | /** 22 | * 打开相机 23 | * 24 | * @param activity 25 | * @param path 26 | */ 27 | public void openCamera(Activity activity, String path) { 28 | openCamera(activity, path, "IMG_" + System.currentTimeMillis() + ".jpg"); 29 | } 30 | 31 | /** 32 | * 打开相机 33 | * 34 | * @param activity 35 | * @param path 36 | * @param fileName 37 | */ 38 | public void openCamera(Activity activity, String path, String fileName) { 39 | FileUtils.makeDirs(path); 40 | File cameraFile = new File(path, fileName); 41 | Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 42 | intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)); 43 | activity.startActivityForResult(intent, CAMERA_REQ_CODE); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/ClickUtil.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | 4 | /** 5 | * @author wlj 6 | * @date 2017/3/28 7 | * @email wanglijundev@gmail.com 8 | * @packagename wanglijun.vip.androidutils 9 | * @description 点击处理方法,防止二次点击 10 | */ 11 | public class ClickUtil { 12 | /** 13 | * 上次点击时间 14 | */ 15 | private static long sLastTime; 16 | 17 | /** 18 | * 判断此次点击是否响应 19 | * 20 | * @return 响应则返回true,否则返回false 21 | */ 22 | public static boolean isClick() { 23 | 24 | long time = TimeUtils.getCurTimeMills(); 25 | if (sLastTime > time || time - sLastTime > 500) { 26 | synchronized (ClickUtil.class) { 27 | if (sLastTime > time || time - sLastTime > 500) { 28 | sLastTime = time; 29 | return true; 30 | } 31 | return false; 32 | } 33 | } 34 | return false; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/CollectionUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.text.TextUtils; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.Collection; 8 | import java.util.HashSet; 9 | import java.util.List; 10 | import java.util.Set; 11 | 12 | /** 13 | * @author wlj 14 | * @date 2017/3/29 15 | * @email wanglijundev@gmail.com 16 | * @packagename wanglijun.vip.androidutils.utils 17 | * @desc: 集合操作 18 | */ 19 | 20 | public class CollectionUtils { 21 | private static final String DELIMITER = ","; 22 | 23 | /** 24 | * 判断集合是否为空 25 | * 26 | * @param c 27 | * @param 28 | * @return 29 | */ 30 | public static boolean isEmpty(Collection c) { 31 | return (c == null || c.size() == 0); 32 | } 33 | 34 | /** 35 | * Join collection to string, separator is {@link #DELIMITER} 36 | * 37 | * @param tokens 38 | * @return 39 | */ 40 | public static String join(Iterable tokens) { 41 | return tokens == null ? "" : TextUtils.join(DELIMITER, tokens); 42 | } 43 | 44 | /** 45 | * 将数组转为list 46 | * 47 | * @param array 48 | * @param 49 | * @return 50 | */ 51 | public static List arrayToList(T... array) { 52 | return Arrays.asList(array); 53 | } 54 | 55 | /** 56 | * 将数组转为set集合 57 | * 58 | * @param array 59 | * @param 60 | * @return 61 | */ 62 | public static Set arrayToSet(T... array) { 63 | return new HashSet(arrayToList(array)); 64 | } 65 | 66 | /** 67 | * 集合转为数组 68 | * 69 | * @param c 70 | * @return 71 | */ 72 | public static Object[] listToArray(Collection c) { 73 | if (!isEmpty(c)) { 74 | return c.toArray(); 75 | } 76 | return null; 77 | } 78 | 79 | /** 80 | * list转为set 81 | * 82 | * @param list 83 | * @param 84 | * @return 85 | */ 86 | public static Set listToSet(List list) { 87 | return new HashSet(list); 88 | } 89 | 90 | /** 91 | * Convert set to list 92 | * set转为list 93 | * 94 | * @param set 95 | * @param 96 | * @return 97 | */ 98 | public static List setToList(Set set) { 99 | return new ArrayList(set); 100 | } 101 | 102 | /** 103 | * Traverse collection 104 | * 遍历集合 105 | * 106 | * @param c 107 | * @param 108 | * @return 109 | */ 110 | public static String traverseCollection(Collection c) { 111 | if (!isEmpty(c)) { 112 | int len = c.size(); 113 | StringBuilder builder = new StringBuilder(len); 114 | int i = 0; 115 | for (T t : c) { 116 | if (t == null) { 117 | continue; 118 | } 119 | builder.append(t.toString()); 120 | i++; 121 | if (i < len) { 122 | builder.append(DELIMITER); 123 | } 124 | } 125 | return builder.toString(); 126 | } 127 | return null; 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/ConstUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 北京博瑞彤芸文化传播股份有限公司 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wanglijun.vip.androidutils.utils; 18 | 19 | /** 20 | * 常量相关 21 | * 22 | * @author wlj 23 | */ 24 | public class ConstUtils { 25 | 26 | private ConstUtils() { 27 | throw new UnsupportedOperationException("u can't fuck me..."); 28 | } 29 | 30 | /******************** 存储相关常量 ********************/ 31 | /** 32 | * Byte与Byte的倍数 33 | */ 34 | public static final int BYTE = 1; 35 | /** 36 | * KB与Byte的倍数 37 | */ 38 | public static final int KB = 1024; 39 | /** 40 | * MB与Byte的倍数 41 | */ 42 | public static final int MB = 1048576; 43 | /** 44 | * GB与Byte的倍数 45 | */ 46 | public static final int GB = 1073741824; 47 | 48 | public enum MemoryUnit { 49 | BYTE, 50 | KB, 51 | MB, 52 | GB 53 | } 54 | 55 | /******************** 时间相关常量 ********************/ 56 | /** 57 | * 毫秒与毫秒的倍数 58 | */ 59 | public static final int MSEC = 1; 60 | /** 61 | * 秒与毫秒的倍数 62 | */ 63 | public static final int SEC = 1000; 64 | /** 65 | * 分与毫秒的倍数 66 | */ 67 | public static final int MIN = 60000; 68 | /** 69 | * 时与毫秒的倍数 70 | */ 71 | public static final int HOUR = 3600000; 72 | /** 73 | * 天与毫秒的倍数 74 | */ 75 | public static final int DAY = 86400000; 76 | 77 | public enum TimeUnit { 78 | MSEC, 79 | SEC, 80 | MIN, 81 | HOUR, 82 | DAY 83 | } 84 | 85 | /******************** 正则相关常量 ********************/ 86 | /** 87 | * 正则:手机号(简单) 88 | */ 89 | public static final String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$"; 90 | /** 91 | * 正则:手机号(精确) 92 | *

移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188

93 | *

联通:130、131、132、145、155、156、175、176、185、186

94 | *

电信:133、153、173、177、180、181、189

95 | *

全球星:1349

96 | *

虚拟运营商:170

97 | */ 98 | public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$"; 99 | /** 100 | * 正则:电话号码 101 | */ 102 | public static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}"; 103 | /** 104 | * 正则:身份证号码15位 105 | */ 106 | public static final String REGEX_IDCARD15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$"; 107 | /** 108 | * 正则:身份证号码18位 109 | */ 110 | public static final String REGEX_IDCARD18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$"; 111 | /** 112 | * 正则:邮箱 113 | */ 114 | public static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"; 115 | /** 116 | * 正则:URL 117 | */ 118 | public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?"; 119 | /** 120 | * 正则:汉字 121 | */ 122 | public static final String REGEX_CHZ = "^[\\u4e00-\\u9fa5]+$"; 123 | /** 124 | * 正则:用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位 125 | */ 126 | public static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(? 255) { 123 | brightness = screenBrightness % 255; 124 | if (brightness == 0) { 125 | brightness = 255; 126 | } 127 | } 128 | boolean result = Settings.System.putInt(context.getContentResolver(), 129 | Settings.System.SCREEN_BRIGHTNESS, brightness); 130 | return result; 131 | } 132 | 133 | /** 134 | * Set window brightness, cannot change system brightness. 135 | * 设置窗口亮度,不能改变系统亮度 136 | * 137 | * @param activity 138 | * @param screenBrightness 0-255 139 | */ 140 | public static void setWindowBrightness(Activity activity, 141 | float screenBrightness) { 142 | float brightness = screenBrightness; 143 | if (screenBrightness < 1) { 144 | brightness = 1; 145 | } else if (screenBrightness > 255) { 146 | brightness = screenBrightness % 255; 147 | if (brightness == 0) { 148 | brightness = 255; 149 | } 150 | } 151 | Window window = activity.getWindow(); 152 | WindowManager.LayoutParams localLayoutParams = window.getAttributes(); 153 | localLayoutParams.screenBrightness = brightness / 255.0f; 154 | window.setAttributes(localLayoutParams); 155 | } 156 | 157 | /** 158 | * Set screen brightness and change system brightness, must declare the 159 | * 设置屏幕亮度并改变系统亮度,必须声明 160 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest. 161 | * 162 | * @param activity 163 | * @param screenBrightness 0-255 164 | * @return 165 | */ 166 | public static boolean setScreenBrightnessAndApply(Activity activity, 167 | int screenBrightness) { 168 | boolean result = setScreenBrightness(activity, screenBrightness); 169 | if (result) { 170 | setWindowBrightness(activity, screenBrightness); 171 | } 172 | return result; 173 | } 174 | 175 | /** 176 | * Get screen dormant time, must declare the 177 | * 获得屏幕休眠时间,必须声明 178 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest. 179 | * 180 | * @param context 181 | * @return dormantTime:ms, default:30s 182 | */ 183 | public static int getScreenDormantTime(Context context) { 184 | return Settings.System.getInt(context.getContentResolver(), 185 | Settings.System.SCREEN_OFF_TIMEOUT, 30000); 186 | } 187 | 188 | /** 189 | * Set screen dormant time by millis, must declare the 190 | * 屏幕休眠时间等信息,必须申报 191 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest. 192 | * 193 | * @param context 194 | * @return 195 | */ 196 | public static boolean setScreenDormantTime(Context context, int millis) { 197 | return Settings.System.putInt(context.getContentResolver(), 198 | Settings.System.SCREEN_OFF_TIMEOUT, millis); 199 | } 200 | 201 | /** 202 | * Get airplane mode, must declare the 203 | * 获取飞行模式,必须申报 204 | * {@link Manifest.permission#WRITE_APN_SETTINGS} permission in its manifest. 205 | * 206 | * @param context 207 | * @return 1:open, 0:close, default:close 208 | */ 209 | public static int getAirplaneMode(Context context) { 210 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { 211 | return Settings.System.getInt(context.getContentResolver(), 212 | Settings.System.AIRPLANE_MODE_ON, 0); 213 | } else { 214 | return Settings.Global.getInt(context.getContentResolver(), 215 | Settings.Global.AIRPLANE_MODE_ON, 0); 216 | } 217 | } 218 | 219 | /** 220 | * Judge whether airplane is open, must declare the 221 | * 判断飞行模式是否打开,必须声明 222 | * {@link Manifest.permission#WRITE_APN_SETTINGS} permission in its manifest. 223 | * 224 | * @param context 225 | * @return true:open, false:close, default:close 226 | */ 227 | public static boolean isAirplaneModeOpen(Context context) { 228 | return getAirplaneMode(context) == 1; 229 | } 230 | 231 | /** 232 | * Set airplane mode, must declare the 233 | * 设置飞行模式,必须声明 234 | * {@link Manifest.permission#WRITE_APN_SETTINGS} permission in its manifest. 235 | * 236 | * @param context 237 | * @param enable 238 | * @return 239 | */ 240 | public static boolean setAirplaneMode(Context context, boolean enable) { 241 | boolean result = true; 242 | if (isAirplaneModeOpen(context) != enable) { 243 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { 244 | result = Settings.System.putInt(context.getContentResolver(), 245 | Settings.System.AIRPLANE_MODE_ON, enable ? 1 : 0); 246 | } else { 247 | result = Settings.Global.putInt(context.getContentResolver(), 248 | Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 249 | } 250 | context.sendBroadcast(new Intent( 251 | Intent.ACTION_AIRPLANE_MODE_CHANGED)); 252 | } 253 | return result; 254 | } 255 | 256 | /** 257 | * Get bluetooth state 258 | * 获取蓝牙状态 259 | * 260 | * @return STATE_OFF, STATE_TURNING_OFF, STATE_ON, STATE_TURNING_ON, NONE 261 | * @throws Exception 262 | */ 263 | @RequiresPermission(Manifest.permission.BLUETOOTH) 264 | public static Integer getBluetoothState() { 265 | BluetoothAdapter bluetoothAdapter = BluetoothAdapter 266 | .getDefaultAdapter(); 267 | if (bluetoothAdapter == null) { 268 | return null; 269 | } else { 270 | return bluetoothAdapter.getState(); 271 | } 272 | } 273 | 274 | /** 275 | * Judge bluetooth is open 276 | * 判断蓝牙是否打开 277 | * 278 | * @return true:open, false:close. 279 | */ 280 | public static boolean isBluetoothOpen() { 281 | @SuppressLint("MissingPermission") Integer bluetoothStateCode = getBluetoothState(); 282 | if (bluetoothStateCode == null) { 283 | return false; 284 | } 285 | return bluetoothStateCode == BluetoothAdapter.STATE_ON 286 | || bluetoothStateCode == BluetoothAdapter.STATE_TURNING_ON; 287 | } 288 | 289 | /** 290 | * Set bluetooth 291 | * 设置蓝牙 292 | * 293 | * @param enable 294 | */ 295 | @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN) 296 | public static void setBluetooth(boolean enable) throws Exception { 297 | if (isBluetoothOpen() != enable) { 298 | if (enable) { 299 | BluetoothAdapter.getDefaultAdapter().enable(); 300 | } else { 301 | BluetoothAdapter.getDefaultAdapter().disable(); 302 | } 303 | } 304 | } 305 | 306 | /** 307 | * Get media volume 308 | * 获取音量 309 | * 310 | * @param context 311 | * @return volume:0-15 312 | */ 313 | public static int getMediaVolume(Context context) { 314 | return ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).getStreamVolume(AudioManager 315 | .STREAM_MUSIC); 316 | } 317 | 318 | /** 319 | * Set media volume 320 | *设置音量 321 | * 322 | * @param context 323 | * @return volume:0-15 324 | */ 325 | public static void setMediaVolume(Context context, int mediaVloume) { 326 | if (mediaVloume < 0) { 327 | mediaVloume = 0; 328 | } else if (mediaVloume > 15) { 329 | mediaVloume = mediaVloume % 15; 330 | if (mediaVloume == 0) { 331 | mediaVloume = 15; 332 | } 333 | } 334 | ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).setStreamVolume(AudioManager.STREAM_MUSIC, 335 | mediaVloume, AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI); 336 | } 337 | 338 | /** 339 | * Get ring volume 340 | * 获取铃声音量 341 | * 342 | * @param context 343 | * @return volume:0-7 344 | */ 345 | public static int getRingVolume(Context context) { 346 | return ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).getStreamVolume(AudioManager 347 | .STREAM_RING); 348 | } 349 | 350 | /** 351 | * Set ring volume 352 | * 设置铃声音量 353 | * 354 | * @param context 355 | * @return volume:0-7 356 | */ 357 | public static void setRingVolume(Context context, int ringVloume) { 358 | if (ringVloume < 0) { 359 | ringVloume = 0; 360 | } else if (ringVloume > 7) { 361 | ringVloume = ringVloume % 7; 362 | if (ringVloume == 0) { 363 | ringVloume = 7; 364 | } 365 | } 366 | ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).setStreamVolume(AudioManager.STREAM_RING, 367 | ringVloume, AudioManager.FLAG_PLAY_SOUND); 368 | } 369 | } 370 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/DisplayUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.app.Activity; 5 | import android.content.Context; 6 | import android.content.res.Configuration; 7 | import android.graphics.Rect; 8 | import android.util.DisplayMetrics; 9 | import android.view.Window; 10 | 11 | /** 12 | * @author wlj 13 | * @date 2017/3/29 14 | * @email wanglijundev@gmail.com 15 | * @packagename wanglijun.vip.androidutils.utils 16 | * @desc: 屏幕相关 17 | */ 18 | 19 | public class DisplayUtils { 20 | /** 21 | * 是否横屏 22 | * 23 | * @param context 24 | * @return 25 | */ 26 | public static boolean isLandscape(Context context) { 27 | return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; 28 | } 29 | 30 | /** 31 | * 是否竖屏 32 | * 33 | * @param context 34 | * @return 35 | */ 36 | public static boolean isPortrait(Context context) { 37 | return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; 38 | } 39 | 40 | /** 41 | * Get screen width, in pixels 42 | * 43 | * @param context 44 | * @return 45 | */ 46 | public static int getScreenWidth(Context context) { 47 | DisplayMetrics dm = context.getResources().getDisplayMetrics(); 48 | return dm.widthPixels; 49 | } 50 | 51 | /** 52 | * Get screen height, in pixels 53 | * 54 | * @param context 55 | * @return 56 | */ 57 | public static int getScreenHeight(Context context) { 58 | DisplayMetrics dm = context.getResources().getDisplayMetrics(); 59 | return dm.heightPixels; 60 | } 61 | 62 | /** 63 | * Get screen density, the logical density of the display 64 | * 65 | * @param context 66 | * @return 67 | */ 68 | public static float getScreenDensity(Context context) { 69 | DisplayMetrics dm = context.getResources().getDisplayMetrics(); 70 | return dm.density; 71 | } 72 | 73 | /** 74 | * Get screen density dpi, the screen density expressed as dots-per-inch 75 | * 76 | * @param context 77 | * @return 78 | */ 79 | public static int getScreenDensityDPI(Context context) { 80 | DisplayMetrics dm = context.getResources().getDisplayMetrics(); 81 | return dm.densityDpi; 82 | } 83 | 84 | /** 85 | * Get titleBar height, this method cannot be used in onCreate(),onStart(),onResume(), unless it is called in the 86 | * post(Runnable). 87 | * 88 | * @param activity 89 | * @return 90 | */ 91 | public static int getTitleBarHeight(Activity activity) { 92 | int statusBarHeight = getStatusBarHeight(activity); 93 | int contentViewTop = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); 94 | int titleBarHeight = contentViewTop - statusBarHeight; 95 | return titleBarHeight < 0 ? 0 : titleBarHeight; 96 | } 97 | 98 | /** 99 | * Get statusbar height, this method cannot be used in onCreate(),onStart(),onResume(), unless it is called in the 100 | * post(Runnable). 101 | * 102 | * @param activity 103 | * @return 104 | */ 105 | public static int getStatusBarHeight(Activity activity) { 106 | Rect rect = new Rect(); 107 | activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); 108 | return rect.top; 109 | } 110 | 111 | /** 112 | * Get statusBar height 113 | * 114 | * @param activity 115 | * @return 116 | */ 117 | @SuppressLint("PrivateApi") 118 | public static int getStatusBarHeight2(Activity activity) { 119 | int statusBarHeight = getStatusBarHeight(activity); 120 | if (0 == statusBarHeight) { 121 | Class localClass; 122 | try { 123 | localClass = Class.forName("com.android.internal.R$dimen"); 124 | Object localObject = localClass.newInstance(); 125 | int id = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString()); 126 | statusBarHeight = activity.getResources().getDimensionPixelSize(id); 127 | } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | IllegalArgumentException | SecurityException | NoSuchFieldException e) { 128 | e.printStackTrace(); 129 | } 130 | } 131 | return statusBarHeight; 132 | } 133 | 134 | /** 135 | * Convert dp to px by the density of phone 136 | * 137 | * @param context 138 | * @param dp 139 | * @return 140 | */ 141 | public static int dip2px(Context context, float dp) { 142 | if (context == null) { 143 | return -1; 144 | } 145 | return (int) (dipToPx(context, dp) + 0.5f); 146 | } 147 | 148 | /** 149 | * Convert dp to px 150 | * 151 | * @param context 152 | * @param dp 153 | * @return 154 | */ 155 | private static float dipToPx(Context context, float dp) { 156 | if (context == null) { 157 | return -1; 158 | } 159 | float scale = context.getResources().getDisplayMetrics().density; 160 | return dp * scale; 161 | } 162 | 163 | /** 164 | * Convert px to dp by the density of phone 165 | * 166 | * @param context 167 | * @param px 168 | * @return 169 | */ 170 | public static int px2dip(Context context, float px) { 171 | if (context == null) { 172 | return -1; 173 | } 174 | return (int) (pxToDip(context, px) + 0.5f); 175 | } 176 | 177 | /** 178 | * Convert px to dp 179 | * 180 | * @param context 181 | * @param px 182 | * @return 183 | */ 184 | private static float pxToDip(Context context, float px) { 185 | if (context == null) { 186 | return -1; 187 | } 188 | float scale = context.getResources().getDisplayMetrics().density; 189 | return px / scale; 190 | } 191 | 192 | /** 193 | * Convert px to sp 194 | * 195 | * @param context 196 | * @param px 197 | * @return 198 | */ 199 | public static int px2sp(Context context, float px) { 200 | return (int) (pxToSp(context, px) + 0.5f); 201 | } 202 | 203 | /** 204 | * Convert px to sp 205 | * 206 | * @param context 207 | * @param px 208 | * @return 209 | */ 210 | private static float pxToSp(Context context, float px) { 211 | float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 212 | return px / fontScale; 213 | } 214 | 215 | /** 216 | * Convert sp to px 217 | * 218 | * @param context 219 | * @param sp 220 | * @return 221 | */ 222 | public static int sp2px(Context context, float sp) { 223 | return (int) (spToPx(context, sp) + 0.5f); 224 | } 225 | 226 | /** 227 | * Convert sp to px 228 | * 229 | * @param context 230 | * @param sp 231 | * @return 232 | */ 233 | private static float spToPx(Context context, float sp) { 234 | float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 235 | return sp * fontScale; 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/FileLog.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.util.Log; 4 | 5 | import java.io.BufferedWriter; 6 | import java.io.File; 7 | import java.io.FileWriter; 8 | import java.io.IOException; 9 | import java.text.SimpleDateFormat; 10 | import java.util.Calendar; 11 | import java.util.Date; 12 | 13 | 14 | /** 15 | * @author wlj 16 | * @date 2017/3/28 17 | * @email wanglijundev@gmail.com 18 | * @packagename wanglijun.vip.androidutils 19 | * @description 带日志文件输入的,又可控开关的日志调试 20 | */ 21 | public class FileLog { 22 | 23 | /** 24 | * 日志文件总开关 25 | */ 26 | private static Boolean MYLOG_SWITCH = false; 27 | /** 28 | * 日志写入文件开关 29 | */ 30 | private static Boolean MYLOG_WRITE_TO_FILE = false; 31 | /** 32 | * 输入日志类型,w代表只输出告警信息等,v代表输出所有信息 33 | */ 34 | private static char MYLOG_TYPE = 'v'; 35 | /** 36 | * sd卡中日志文件的最多保存天数 37 | */ 38 | private static int SDCARD_LOG_FILE_SAVE_DAYS = 0; 39 | /** 40 | * 目录 41 | */ 42 | private static String sDirs; 43 | /** 44 | * 本类输出的日志文件名称 45 | */ 46 | private static String MYLOGFILEName = "Log.txt"; 47 | /** 48 | * 日志的输出格式 49 | */ 50 | private static SimpleDateFormat myLogSdf = new SimpleDateFormat( 51 | "yyyy-MM-dd HH:mm:ss"); 52 | /** 53 | * 日志文件格式 54 | */ 55 | private static SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd"); 56 | 57 | public static void w(String tag, Object msg) { // 警告信息 58 | log(tag, msg.toString(), 'w'); 59 | } 60 | 61 | public static void e(String tag, Object msg) { // 错误信息 62 | log(tag, msg.toString(), 'e'); 63 | } 64 | 65 | public static void d(String tag, Object msg) {// 调试信息 66 | log(tag, msg.toString(), 'd'); 67 | } 68 | 69 | public static void i(String tag, Object msg) {// 70 | log(tag, msg.toString(), 'i'); 71 | } 72 | 73 | public static void v(String tag, Object msg) { 74 | log(tag, msg.toString(), 'v'); 75 | } 76 | 77 | public static void w(String tag, String text) { 78 | log(tag, text, 'w'); 79 | } 80 | 81 | public static void e(String tag, String text) { 82 | log(tag, text, 'e'); 83 | } 84 | 85 | public static void d(String tag, String text) { 86 | log(tag, text, 'd'); 87 | } 88 | 89 | public static void i(String tag, String text) { 90 | log(tag, text, 'i'); 91 | } 92 | 93 | public static void v(String tag, String text) { 94 | log(tag, text, 'v'); 95 | } 96 | 97 | /** 98 | * 配置文件log 99 | * 100 | * @param dirs 目录 101 | * @param isShowLog true表示写入 102 | */ 103 | public static void setConfig(String dirs, boolean isShowLog) { 104 | sDirs = dirs; 105 | MYLOG_SWITCH = isShowLog; 106 | MYLOG_WRITE_TO_FILE = isShowLog; 107 | } 108 | 109 | /** 110 | * 根据tag, msg和等级,输出日志 111 | * 112 | * @param tag 113 | * @param msg 114 | * @param level 115 | * @return void 116 | * @since v 1.0 117 | */ 118 | private static void log(String tag, String msg, char level) { 119 | if (MYLOG_SWITCH) { 120 | if ('e' == level && ('e' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { 121 | Log.e(tag, msg); 122 | } else if ('w' == level && ('w' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { 123 | Log.w(tag, msg); 124 | } else if ('d' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { 125 | Log.d(tag, msg); 126 | } else if ('i' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { 127 | Log.i(tag, msg); 128 | } else { 129 | Log.v(tag, msg); 130 | 131 | } 132 | if (MYLOG_WRITE_TO_FILE) { 133 | writeLogToFile(String.valueOf(level), tag, msg); 134 | } 135 | } 136 | } 137 | 138 | /** 139 | * 打开日志文件并写入日志 140 | * 新建或打开日志文件 141 | * @return 142 | **/ 143 | private static void writeLogToFile(String myLogType, String tag, String text) { 144 | Date newTime = new Date(); 145 | String needWriteFile = logfile.format(newTime); 146 | String needWriteMessage = myLogSdf.format(newTime) + " " + myLogType 147 | + " " + tag + " " + text; 148 | File dir = new File(sDirs); 149 | if (!dir.exists()) { 150 | dir.mkdirs(); 151 | } 152 | File file = new File(sDirs, needWriteFile 153 | + MYLOGFILEName); 154 | try { 155 | //后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖 156 | FileWriter filerWriter = new FileWriter(file, true); 157 | BufferedWriter bufWriter = new BufferedWriter(filerWriter); 158 | bufWriter.write(needWriteMessage); 159 | bufWriter.newLine(); 160 | bufWriter.close(); 161 | filerWriter.close(); 162 | } catch (IOException e) { 163 | e.printStackTrace(); 164 | } 165 | } 166 | 167 | /** 168 | * 删除制定的日志文件 169 | */ 170 | public static void delFile() {// 删除日志文件 171 | String needDelFile = logfile.format(getDateBefore()); 172 | File file = new File(sDirs, needDelFile + MYLOGFILEName); 173 | if (file.exists()) { 174 | file.delete(); 175 | } 176 | } 177 | 178 | /** 179 | * 得到现在时间前的几天日期,用来得到需要删除的日志文件名 180 | */ 181 | private static Date getDateBefore() { 182 | Date newTime = new Date(); 183 | Calendar now = Calendar.getInstance(); 184 | now.setTime(newTime); 185 | now.set(Calendar.DATE, now.get(Calendar.DATE) 186 | - SDCARD_LOG_FILE_SAVE_DAYS); 187 | return now.getTime(); 188 | } 189 | 190 | } -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/FileSize.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 北京博瑞彤芸文化传播股份有限公司 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package wanglijun.vip.androidutils.utils; 19 | 20 | import android.text.TextUtils; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.math.BigDecimal; 25 | 26 | 27 | /** 28 | * @author wlj 29 | * @date 2018/09/01 30 | * @email wanglijundev@gmail.com 31 | * @packagename wanglijun.vip.androidutils 32 | * @description 获取文件大小的类 33 | */ 34 | public class FileSize { 35 | 36 | public static final long SIZE_BT = 1024L; 37 | 38 | public static final long SIZE_KB = SIZE_BT * 1024L; 39 | 40 | public static final long SIZE_MB = SIZE_KB * 1024L; 41 | 42 | public static final long SIZE_GB = SIZE_MB * 1024L; 43 | 44 | public static final long SIZE_TB = SIZE_GB * 1024L; 45 | 46 | public static final int SACLE = 2; 47 | 48 | private File file; 49 | 50 | private long longSize; 51 | 52 | public FileSize(File file) { 53 | this.file = file; 54 | } 55 | 56 | private void getFileSize() throws RuntimeException, IOException { 57 | getFileSize(file); 58 | } 59 | 60 | private void getFileSize(File file) { 61 | 62 | if (file == null || !file.exists()) { 63 | return; 64 | } 65 | 66 | if (file.isFile()) { 67 | this.longSize += file.length(); 68 | return; 69 | } 70 | 71 | File[] childArray = file.listFiles(); 72 | if (childArray == null || childArray.length == 0) { 73 | return; 74 | } 75 | 76 | for (File child : childArray) { 77 | getFileSize(child); 78 | } 79 | 80 | } 81 | 82 | @Override 83 | public String toString() throws RuntimeException { 84 | try { 85 | try { 86 | getFileSize(); 87 | } catch (RuntimeException e) { 88 | return ""; 89 | } 90 | 91 | return convertSizeToString(this.longSize); 92 | 93 | } catch (IOException ex) { 94 | ex.printStackTrace(); 95 | throw new RuntimeException(ex.getMessage()); 96 | } 97 | } 98 | 99 | /** 100 | * 格式化输出文件大小 101 | * @param fileSize 102 | * @return 103 | */ 104 | public static String convertSizeToString(long fileSize) { 105 | if (fileSize >= 0 && fileSize < SIZE_BT) { 106 | return fileSize + "B"; 107 | } else if (fileSize >= SIZE_BT && fileSize < SIZE_KB) { 108 | return fileSize / SIZE_BT + "KB"; 109 | } else if (fileSize >= SIZE_KB && fileSize < SIZE_MB) { 110 | return fileSize / SIZE_KB + "MB"; 111 | } else if (fileSize >= SIZE_MB && fileSize < SIZE_GB) { 112 | BigDecimal longs = new BigDecimal(Double.valueOf(fileSize + "").toString()); 113 | BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_MB + "").toString()); 114 | String result = longs.divide(sizeMB, SACLE, BigDecimal.ROUND_HALF_UP).toString(); 115 | // double result=this.longSize/(double)SIZE_MB; 116 | return result + "GB"; 117 | } else { 118 | BigDecimal longs = new BigDecimal(Double.valueOf(fileSize + "").toString()); 119 | BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_GB + "").toString()); 120 | String result = longs.divide(sizeMB, SACLE, BigDecimal.ROUND_HALF_UP).toString(); 121 | return result + "TB"; 122 | } 123 | } 124 | 125 | /** 126 | * MB转KB 127 | * @param fileSize 128 | * @return 129 | */ 130 | public static double getKBSize(String fileSize) { 131 | if (TextUtils.isEmpty(fileSize)) { 132 | return 0; 133 | } 134 | fileSize = fileSize.toUpperCase(); 135 | int index; 136 | if ((index = fileSize.indexOf("MB")) > 0) { 137 | String str = fileSize.substring(0, index).trim(); 138 | return string2double(str) * 1024; 139 | } 140 | if ((index = fileSize.indexOf("KB")) > 0) { 141 | String str = fileSize.substring(0, index).trim(); 142 | return string2double(str); 143 | } 144 | return 0; 145 | } 146 | 147 | public static double string2double(String doubleStr) { 148 | try { 149 | return Double.parseDouble(doubleStr); 150 | } catch (Exception e) { 151 | } 152 | return 0; 153 | } 154 | 155 | /** 156 | * 获取文件的大小单位是byte 157 | * @return 返回文件的大小 158 | * @throws RuntimeException 159 | */ 160 | public long getLongSize() throws RuntimeException { 161 | try { 162 | 163 | getFileSize(); 164 | return longSize; 165 | } catch (IOException ex) { 166 | ex.printStackTrace(); 167 | throw new RuntimeException(ex.getMessage()); 168 | } 169 | } 170 | 171 | } 172 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/FileUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileOutputStream; 8 | import java.io.FileWriter; 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | import java.io.InputStreamReader; 12 | import java.io.OutputStream; 13 | 14 | /** 15 | * @author: wlj 16 | * @Date: 2017-03-28 17 | * @email: wanglijundev@gmail.com 18 | * @desc: 文件工具类 19 | */ 20 | public class FileUtils { 21 | 22 | public final static String FILE_SUFFIX_SEPARATOR = "."; 23 | 24 | /** 25 | * Read file 26 | * 27 | * @param filePath 28 | * @param charsetName 29 | * @return 30 | */ 31 | public static StringBuilder readFile(String filePath, String charsetName) { 32 | File file = new File(filePath); 33 | StringBuilder fileContent = new StringBuilder(""); 34 | if (!file.isFile()) { 35 | return null; 36 | } 37 | 38 | BufferedReader reader = null; 39 | try { 40 | InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName); 41 | reader = new BufferedReader(is); 42 | String line = null; 43 | while ((line = reader.readLine()) != null) { 44 | if (!"".equals(fileContent.toString())) { 45 | fileContent.append("\r\n"); 46 | } 47 | fileContent.append(line); 48 | } 49 | return fileContent; 50 | } catch (IOException e) { 51 | throw new RuntimeException("IOException", e); 52 | } finally { 53 | IOUtils.close(reader); 54 | } 55 | } 56 | 57 | /** 58 | * Write file 59 | * 60 | * @param filePath 61 | * @param content 62 | * @param append 63 | * @return 64 | */ 65 | public static boolean writeFile(String filePath, String content, boolean append) { 66 | if (StringUtils.isEmpty(content)) { 67 | return false; 68 | } 69 | FileWriter fileWriter = null; 70 | try { 71 | makeDirs(filePath); 72 | fileWriter = new FileWriter(filePath, append); 73 | fileWriter.write(content); 74 | return true; 75 | } catch (IOException e) { 76 | throw new RuntimeException("IOException occurred. ", e); 77 | } finally { 78 | IOUtils.close(fileWriter); 79 | } 80 | } 81 | 82 | /** 83 | * write file, the string will be written to the begin of the file 84 | * 85 | * @param filePath 86 | * @param content 87 | * @return 88 | */ 89 | public static boolean writeFile(String filePath, String content) { 90 | return writeFile(filePath, content, false); 91 | } 92 | 93 | /** 94 | * Write file 95 | * 96 | * @param filePath 97 | * @param is 98 | * @return 99 | */ 100 | public static boolean writeFile(String filePath, InputStream is) { 101 | return writeFile(filePath, is, false); 102 | } 103 | 104 | /** 105 | * Write file 106 | * 107 | * @param filePath 108 | * @param is 109 | * @param append 110 | * @return 111 | */ 112 | public static boolean writeFile(String filePath, InputStream is, boolean append) { 113 | return writeFile(filePath != null ? new File(filePath) : null, is, append); 114 | } 115 | 116 | /** 117 | * Write file 118 | * 119 | * @param file 120 | * @param is 121 | * @return 122 | */ 123 | public static boolean writeFile(File file, InputStream is) { 124 | return writeFile(file, is, false); 125 | } 126 | 127 | /** 128 | * Write file 129 | * 130 | * @param file 131 | * @param is 132 | * @param append 133 | * @return 134 | */ 135 | public static boolean writeFile(File file, InputStream is, boolean append) { 136 | OutputStream o = null; 137 | try { 138 | makeDirs(file.getAbsolutePath()); 139 | o = new FileOutputStream(file, append); 140 | byte[] data = new byte[1024]; 141 | int length = -1; 142 | while ((length = is.read(data)) != -1) { 143 | o.write(data, 0, length); 144 | } 145 | o.flush(); 146 | return true; 147 | } catch (FileNotFoundException e) { 148 | throw new RuntimeException("FileNotFoundException", e); 149 | } catch (IOException e) { 150 | throw new RuntimeException("IOException", e); 151 | } finally { 152 | IOUtils.close(o); 153 | IOUtils.close(is); 154 | } 155 | } 156 | 157 | /** 158 | * Move file 159 | * 160 | * @param srcFilePath 161 | * @param destFilePath 162 | */ 163 | public static void moveFile(String srcFilePath, String destFilePath) throws FileNotFoundException { 164 | if (StringUtils.isEmpty(srcFilePath) || StringUtils.isEmpty(destFilePath)) { 165 | throw new RuntimeException("Both srcFilePath and destFilePath cannot be null."); 166 | } 167 | moveFile(new File(srcFilePath), new File(destFilePath)); 168 | } 169 | 170 | /** 171 | * Move file 172 | * 173 | * @param srcFile 174 | * @param destFile 175 | */ 176 | public static void moveFile(File srcFile, File destFile) throws FileNotFoundException { 177 | boolean rename = srcFile.renameTo(destFile); 178 | if (!rename) { 179 | copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath()); 180 | deleteFile(srcFile.getAbsolutePath()); 181 | } 182 | } 183 | 184 | /** 185 | * Copy file 186 | * 187 | * @param srcFilePath 188 | * @param destFilePath 189 | * @return 190 | * @throws FileNotFoundException 191 | */ 192 | public static boolean copyFile(String srcFilePath, String destFilePath) throws FileNotFoundException { 193 | InputStream inputStream = new FileInputStream(srcFilePath); 194 | return writeFile(destFilePath, inputStream); 195 | } 196 | 197 | /** 198 | * rename file 199 | * 200 | * @param file 201 | * @param newFileName 202 | * @return 203 | */ 204 | public static boolean renameFile(File file, String newFileName) { 205 | File newFile = null; 206 | if (file.isDirectory()) { 207 | newFile = new File(file.getParentFile(), newFileName); 208 | } else { 209 | String temp = newFileName 210 | + file.getName().substring( 211 | file.getName().lastIndexOf('.')); 212 | newFile = new File(file.getParentFile(), temp); 213 | } 214 | if (file.renameTo(newFile)) { 215 | return true; 216 | } 217 | return false; 218 | } 219 | 220 | /** 221 | * Get file name without suffix 222 | * 223 | * @param filePath 224 | * @return 225 | */ 226 | public static String getFileNameWithoutSuffix(String filePath) { 227 | if (StringUtils.isEmpty(filePath)) { 228 | return filePath; 229 | } 230 | int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR); 231 | int fp = filePath.lastIndexOf(File.separator); 232 | if (fp == -1) { 233 | return (suffix == -1 ? filePath : filePath.substring(0, suffix)); 234 | } 235 | if (suffix == -1) { 236 | return filePath.substring(fp + 1); 237 | } 238 | return (fp < suffix ? filePath.substring(fp + 1, suffix) : filePath.substring(fp + 1)); 239 | } 240 | 241 | /** 242 | * Get file name 243 | * 244 | * @param filePath 245 | * @return 246 | */ 247 | public static String getFileName(String filePath) { 248 | if (StringUtils.isEmpty(filePath)) { 249 | return filePath; 250 | } 251 | int fp = filePath.lastIndexOf(File.separator); 252 | return (fp == -1) ? filePath : filePath.substring(fp + 1); 253 | } 254 | 255 | /** 256 | * Get folder name 257 | * 258 | * @param filePath 259 | * @return 260 | */ 261 | public static String getFolderName(String filePath) { 262 | if (StringUtils.isEmpty(filePath)) { 263 | return filePath; 264 | } 265 | int fp = filePath.lastIndexOf(File.separator); 266 | return (fp == -1) ? "" : filePath.substring(0, fp); 267 | } 268 | 269 | /** 270 | * Get suffix of file 271 | * 272 | * @param filePath 273 | * @return 274 | */ 275 | public static String getFileSuffix(String filePath) { 276 | if (StringUtils.isEmpty(filePath)) { 277 | return filePath; 278 | } 279 | int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR); 280 | int fp = filePath.lastIndexOf(File.separator); 281 | if (suffix == -1) { 282 | return ""; 283 | } 284 | return (fp >= suffix) ? "" : filePath.substring(suffix + 1); 285 | } 286 | 287 | /** 288 | * Create the directory 289 | * 290 | * @param filePath 291 | * @return 292 | */ 293 | public static boolean makeDirs(String filePath) { 294 | String folderName = getFolderName(filePath); 295 | if (StringUtils.isEmpty(folderName)) { 296 | return false; 297 | } 298 | File folder = new File(folderName); 299 | return (folder.exists() && folder.isDirectory()) || folder.mkdirs(); 300 | } 301 | 302 | /** 303 | * Judge whether a file is exist 304 | * 305 | * @param filePath 306 | * @return 307 | */ 308 | public static boolean isFileExist(String filePath) { 309 | if (StringUtils.isEmpty(filePath)) { 310 | return false; 311 | } 312 | File file = new File(filePath); 313 | return (file.exists() && file.isFile()); 314 | } 315 | 316 | /** 317 | * Judge whether a folder is exist 318 | * 319 | * @param directoryPath 320 | * @return 321 | */ 322 | public static boolean isFolderExist(String directoryPath) { 323 | if (StringUtils.isEmpty(directoryPath)) { 324 | return false; 325 | } 326 | File dire = new File(directoryPath); 327 | return (dire.exists() && dire.isDirectory()); 328 | } 329 | 330 | /** 331 | * Delete file or folder 332 | * 333 | * @param path 334 | * @return 335 | */ 336 | public static boolean deleteFile(String path) { 337 | if (StringUtils.isEmpty(path)) { 338 | return true; 339 | } 340 | 341 | File file = new File(path); 342 | if (!file.exists()) { 343 | return true; 344 | } 345 | if (file.isFile()) { 346 | return file.delete(); 347 | } 348 | if (!file.isDirectory()) { 349 | return false; 350 | } 351 | if (file.isDirectory()) { 352 | for (File f : file.listFiles()) { 353 | if (f.isFile()) { 354 | f.delete(); 355 | } else if (f.isDirectory()) { 356 | deleteFile(f.getAbsolutePath()); 357 | } 358 | } 359 | } 360 | return file.delete(); 361 | } 362 | 363 | /** 364 | * Delete file or folder 365 | * 366 | * @param file 367 | * @return 368 | */ 369 | public static boolean deleteFile(File file) { 370 | if (!file.exists()) { 371 | return true; 372 | } 373 | if (file.isFile()) { 374 | return file.delete(); 375 | } 376 | if (!file.isDirectory()) { 377 | return false; 378 | } 379 | file.isDirectory(); 380 | File[] childFile = file.listFiles(); 381 | if (childFile == null || childFile.length == 0) { 382 | return file.delete(); 383 | } 384 | for (File f : childFile) { 385 | deleteFile(f); 386 | } 387 | return file.delete(); 388 | } 389 | 390 | /** 391 | * Get file size 392 | * 393 | * @param path 394 | * @return 395 | */ 396 | public static long getFileSize(String path) { 397 | if (StringUtils.isEmpty(path)) { 398 | return -1; 399 | } 400 | File file = new File(path); 401 | return (file.exists() && file.isFile() ? file.length() : -1); 402 | } 403 | 404 | /** 405 | * Get folder size 406 | * 407 | * @param file 408 | * @return 409 | * @throws Exception 410 | */ 411 | public static long getFolderSize(File file) throws Exception { 412 | long size = 0; 413 | try { 414 | File[] fileList = file.listFiles(); 415 | for (int i = 0; i < fileList.length; i++) { 416 | if (fileList[i].isDirectory()) { 417 | size = size + getFolderSize(fileList[i]); 418 | } else { 419 | size = size + fileList[i].length(); 420 | } 421 | } 422 | } catch (Exception e) { 423 | e.printStackTrace(); 424 | } 425 | return size; 426 | } 427 | } 428 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/IOUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.io.Closeable; 4 | import java.io.IOException; 5 | 6 | /** 7 | * @author wlj 8 | * @date 2017/3/29 9 | * @email wanglijundev@gmail.com 10 | * @packagename wanglijun.vip.androidutils.utils 11 | * @desc: io操作 12 | */ 13 | 14 | public class IOUtils { 15 | /** 16 | * Close closeable object 17 | * 关闭可以关闭的对象 18 | * 19 | * @param closeable 20 | */ 21 | public static void close(Closeable closeable) { 22 | if (closeable != null) { 23 | try { 24 | closeable.close(); 25 | } catch (IOException e) { 26 | LogUtils.d("IOUtils",e.toString()); 27 | } 28 | } 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/JsonUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.reflect.TypeToken; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | /** 11 | * @author wlj 12 | * @date 2017/3/29 13 | * @email wanglijundev@gmail.com 14 | * @packagename wanglijun.vip.androidutils.utils 15 | * @desc: json的转换 16 | */ 17 | 18 | public class JsonUtils { 19 | /** 20 | * Convert object, list, ... to Json 21 | * 转为json格式输出 22 | * @param obj 23 | * @return 24 | */ 25 | public static String toJson(Object obj) { 26 | Gson gson = new Gson(); 27 | return gson.toJson(obj); 28 | } 29 | 30 | /** 31 | * Convert a json string to Object 32 | * 将json转为object对象 33 | * @param json 34 | * @param clazz 35 | * @return 36 | */ 37 | public static T jsonToObject(String json, Class clazz) { 38 | Gson gson = new Gson(); 39 | return gson.fromJson(json, clazz); 40 | } 41 | 42 | /** 43 | * Convert a json string to List 44 | * 将json转为list集合 45 | * @param json 46 | * @return 47 | */ 48 | public static List jsonToList(String json) { 49 | Gson gson = new Gson(); 50 | return gson.fromJson(json, new TypeToken>() { 51 | }.getType()); 52 | } 53 | 54 | /** 55 | * Convert a json string to ArrayList 56 | * 将json转为ArrayList 57 | * @param json 58 | * @return 59 | */ 60 | public static ArrayList jsonToArrayList(String json) { 61 | Gson gson = new Gson(); 62 | return gson.fromJson(json, new TypeToken>() { 63 | }.getType()); 64 | } 65 | 66 | /** 67 | * Convert a json string to Map 68 | * 将json转为map 69 | * @param json 70 | * @return 71 | */ 72 | public static Map jsonToMap(String json) { 73 | Gson gson = new Gson(); 74 | return gson.fromJson(json, new TypeToken>() { 75 | }.getType()); 76 | } 77 | 78 | /** 79 | * Convert a json string to Generic 80 | * 将json转为泛型 81 | * @param json 82 | * @param 83 | * @return 84 | */ 85 | public static T jsonToGeneric(String json, TypeToken token) { 86 | Gson gson = new Gson(); 87 | return gson.fromJson(json, token.getType()); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/KeyboardUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 北京博瑞彤芸文化传播股份有限公司 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 wanglijun.vip.androidutils.utils; 17 | 18 | import android.app.Activity; 19 | import android.content.Context; 20 | import android.view.inputmethod.InputMethodManager; 21 | import android.widget.EditText; 22 | 23 | 24 | /** 25 | * @author wlj 26 | * @date 2018/09/01 27 | * @email wanglijundev@gmail.com 28 | * @packagename wanglijun.vip.androidutils 29 | * @description 键盘工具类 30 | */ 31 | public class KeyboardUtil { 32 | 33 | /** 34 | * 隐藏键盘 35 | */ 36 | public static void hideSoftInput(Activity activity) { 37 | InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); 38 | imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 39 | } 40 | 41 | /** 42 | * 显示键盘 43 | */ 44 | public static void showSoftInput(EditText et) { 45 | et.requestFocus(); 46 | InputMethodManager imm = (InputMethodManager) et.getContext() 47 | .getSystemService(Context.INPUT_METHOD_SERVICE); 48 | imm.showSoftInput(et, InputMethodManager.RESULT_UNCHANGED_SHOWN); 49 | } 50 | 51 | /** 52 | * 展示键盘并选中最后一个 53 | */ 54 | public static void showSoftInputSelect(EditText et) { 55 | showSoftInputSelect(et, 300); 56 | } 57 | 58 | /** 59 | * 展示键盘并选中最后一个 60 | */ 61 | public static void showSoftInputSelect(final EditText et, long delayMillis) { 62 | et.postDelayed(new Runnable() { 63 | 64 | @Override 65 | public void run() { 66 | showSoftInput(et); 67 | et.setSelection(et.getText().length()); 68 | } 69 | }, delayMillis); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/LogUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.util.Log; 4 | 5 | /** 6 | * @author: wlj 7 | * @Date: 2017-03-28 8 | * @email: wanglijundev@gmail.com 9 | * @desc: log统一管理类 10 | */ 11 | 12 | public class LogUtils { 13 | private LogUtils() { 14 | /* cannot be instantiated */ 15 | throw new UnsupportedOperationException("cannot be instantiated"); 16 | } 17 | 18 | /** 19 | * 是否需要打印bug,可以在application的onCreate函数里面初始化 20 | */ 21 | public static boolean isDebug = true; 22 | private static final String TAG = "LogUtil"; 23 | 24 | /** 25 | * 下面四个是默认tag的函数 26 | * 27 | * @param msg 28 | */ 29 | public static void i(String msg) { 30 | if (isDebug) 31 | Log.i(TAG, msg); 32 | } 33 | 34 | public static void d(String msg) { 35 | if (isDebug) { 36 | Log.d(TAG, msg); 37 | } 38 | } 39 | 40 | public static void e(String msg) { 41 | if (isDebug) { 42 | Log.e(TAG, msg); 43 | } 44 | } 45 | 46 | public static void v(String msg) { 47 | if (isDebug) { 48 | Log.v(TAG, msg); 49 | } 50 | } 51 | 52 | /** 53 | * 下面是传入自定义tag的函数 54 | * 55 | * @param tag 56 | * @param msg 57 | */ 58 | public static void i(String tag, String msg) { 59 | if (isDebug) { 60 | Log.i(tag, msg); 61 | } 62 | } 63 | 64 | public static void d(String tag, String msg) { 65 | if (isDebug) { 66 | Log.i(tag, msg); 67 | } 68 | } 69 | 70 | public static void e(String tag, String msg) { 71 | if (isDebug) { 72 | Log.i(tag, msg); 73 | } 74 | } 75 | 76 | public static void v(String tag, String msg) { 77 | if (isDebug) { 78 | Log.i(tag, msg); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/MD5Utils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.math.BigInteger; 6 | import java.security.MessageDigest; 7 | import java.security.NoSuchAlgorithmException; 8 | 9 | /** 10 | * @author wlj 11 | * @date 2017/3/29 12 | * @email wanglijundev@gmail.com 13 | * @packagename wanglijun.vip.androidutils.utils 14 | * @desc: MD5相关操作 15 | */ 16 | 17 | public class MD5Utils { 18 | /** 19 | * Encode MD5 for a string 20 | * 21 | * @param s 22 | * @return 23 | */ 24 | public static String encodeMD5(String s) { 25 | try { 26 | MessageDigest digest = MessageDigest.getInstance("MD5"); 27 | digest.update(s.getBytes()); 28 | byte[] messageDigest = digest.digest(); 29 | return toHexString(messageDigest); 30 | } catch (NoSuchAlgorithmException e) { 31 | e.printStackTrace(); 32 | } 33 | return ""; 34 | } 35 | 36 | private static String toHexString(byte[] keyData) { 37 | if (keyData == null) { 38 | return null; 39 | } 40 | int expectedStringLen = keyData.length * 2; 41 | StringBuilder sb = new StringBuilder(expectedStringLen); 42 | for (int i = 0; i < keyData.length; i++) { 43 | String hexStr = Integer.toString(keyData[i] & 0x00FF, 16); 44 | if (hexStr.length() == 1) { 45 | hexStr = "0" + hexStr; 46 | } 47 | sb.append(hexStr); 48 | } 49 | return sb.toString(); 50 | } 51 | 52 | /** 53 | * Encode MD5 for a string 54 | * 55 | * @param s 56 | * @return 57 | */ 58 | public final static String encodeMD52(String s) { 59 | char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 60 | try { 61 | byte[] btInput = s.getBytes(); 62 | MessageDigest digest = MessageDigest.getInstance("MD5"); 63 | digest.update(btInput); 64 | byte[] md = digest.digest(); 65 | int j = md.length; 66 | char[] str = new char[j * 2]; 67 | int k = 0; 68 | for (int i = 0; i < j; i++) { 69 | byte byte0 = md[i]; 70 | str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 71 | str[k++] = hexDigits[byte0 & 0xf]; 72 | } 73 | return new String(str); 74 | } catch (Exception e) { 75 | e.printStackTrace(); 76 | return null; 77 | } 78 | } 79 | 80 | /** 81 | * Encode md5 for a single file 82 | * 83 | * @param f 84 | * @return 85 | */ 86 | public static String encodeMD5(File f) { 87 | if (!f.isFile()) { 88 | return null; 89 | } 90 | MessageDigest digest = null; 91 | byte[] buffer = new byte[1024]; 92 | int len; 93 | try { 94 | digest = MessageDigest.getInstance("MD5"); 95 | FileInputStream in = new FileInputStream(f); 96 | while ((len = in.read(buffer, 0, 1024)) != -1) { 97 | digest.update(buffer, 0, len); 98 | } 99 | in.close(); 100 | } catch (Exception e) { 101 | e.printStackTrace(); 102 | return null; 103 | } 104 | BigInteger bigInt = new BigInteger(1, digest.digest()); 105 | return bigInt.toString(16); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/MapUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * @author wlj 7 | * @date 2017/3/29 8 | * @email wanglijundev@gmail.com 9 | * @packagename wanglijun.vip.androidutils.utils 10 | * @desc: Map相关操作 11 | */ 12 | 13 | public class MapUtils { 14 | private static final String DELIMITER = ","; 15 | 16 | /** 17 | * Judge whether a map is null or size is 0 18 | * 判断是否为空或者为零 19 | * 20 | * @param map 21 | * @param 22 | * @param 23 | * @return 24 | */ 25 | public static boolean isEmpty(Map map) { 26 | return (map == null || map.size() == 0); 27 | } 28 | 29 | /** 30 | * Map遍历 31 | * 32 | * @param map 33 | * @param 34 | * @param 35 | * @return 36 | */ 37 | public static String traverseMap(Map map) { 38 | if (!isEmpty(map)) { 39 | int len = map.size(); 40 | StringBuilder builder = new StringBuilder(len); 41 | int i = 0; 42 | for (Map.Entry entry : map.entrySet()) { 43 | if (entry == null) { 44 | continue; 45 | } 46 | builder.append(entry.getKey().toString() + ":" + entry.getValue().toString()); 47 | i++; 48 | if (i < len) { 49 | builder.append(DELIMITER); 50 | } 51 | } 52 | return builder.toString(); 53 | } 54 | return null; 55 | } 56 | 57 | /** 58 | * 根据值获取键 59 | * 60 | * @param map 61 | * @param value 62 | * @param 63 | * @param 64 | * @return 65 | */ 66 | public static K getKeyByValue(Map map, V value) { 67 | if (isEmpty(map)) { 68 | return null; 69 | } 70 | for (Map.Entry entry : map.entrySet()) { 71 | if (ObjectUtils.equals(entry.getValue(), value)) { 72 | return entry.getKey(); 73 | } 74 | } 75 | return null; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/NetWork.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import wanglijun.vip.androidutils.Application; 4 | 5 | /** 6 | * @author wlj 7 | * @date 2017/3/29 8 | * @email wanglijundev@gmail.com 9 | * @packagename wanglijun.vip.androidutils.utils 10 | * @desc: 判断手机网络类型,是否连接 11 | */ 12 | 13 | public class NetWork { 14 | public static void internal() { 15 | int networkType = NetWorkUtils.getNetworkType(Application.context); 16 | String networkTypeName = NetWorkUtils.getNetworkTypeName(Application.context); 17 | LogUtils.d("-----网络名字-----", networkTypeName); 18 | LogUtils.d("----网络类型-----", networkType + ""); 19 | if (networkTypeName.equals(NetWorkUtils.NETWORK_TYPE_WIFI)) { 20 | ToastUtil.showToast("你目前处于wifi网络"); 21 | } else if (networkTypeName.equals(NetWorkUtils.NETWORK_TYPE_DISCONNECT)) { 22 | ToastUtil.showToast("你目前处于断网状态"); 23 | } else if (networkTypeName.equals(NetWorkUtils.NETWORK_TYPE_3G)) { 24 | ToastUtil.showToast("你目前处于3G状态"); 25 | } else if (networkTypeName.equals(NetWorkUtils.NETWORK_TYPE_2G)) { 26 | ToastUtil.showToast("你目前处于2G网络"); 27 | } else if (networkTypeName.equals(NetWorkUtils.NETWORK_TYPE_WAP)) { 28 | ToastUtil.showToast("你目前处于企业网"); 29 | } else if (networkTypeName.equals(NetWorkUtils.NETWORK_TYPE_UNKNOWN)) { 30 | ToastUtil.showToast("你目前网络类型不知道"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/NetWorkUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.content.Context; 4 | import android.net.ConnectivityManager; 5 | import android.net.NetworkInfo; 6 | import android.telephony.TelephonyManager; 7 | import android.text.TextUtils; 8 | 9 | /** 10 | * 注意 要添加网络权限 android.permission.ACCESS_NETWORK_STATE 11 | * @author wlj 12 | * @date 2017/3/29 13 | * @email wanglijundev@gmail.com 14 | * @packagename wanglijun.vip.androidutils.utils 15 | * @desc: 获取网络状态 16 | */ 17 | 18 | public class NetWorkUtils { 19 | public static final String NETWORK_TYPE_WIFI = "wifi"; 20 | public static final String NETWORK_TYPE_3G = "eg"; 21 | public static final String NETWORK_TYPE_2G = "2g"; 22 | public static final String NETWORK_TYPE_WAP = "wap"; 23 | public static final String NETWORK_TYPE_UNKNOWN = "unknown"; 24 | public static final String NETWORK_TYPE_DISCONNECT = "disconnect"; 25 | private static final String WIFI = "WIFI"; 26 | private static final String MOBILE = "MOBILE"; 27 | /** 28 | * Get network type 29 | * 30 | * @param context 31 | * @return 32 | */ 33 | public static int getNetworkType(Context context) { 34 | ConnectivityManager connectivityManager = (ConnectivityManager) context 35 | .getSystemService(Context.CONNECTIVITY_SERVICE); 36 | NetworkInfo networkInfo = connectivityManager == null ? null : connectivityManager.getActiveNetworkInfo(); 37 | return networkInfo == null ? -1 : networkInfo.getType(); 38 | } 39 | 40 | /** 41 | * Check network 42 | * 43 | * @param context 44 | * @return 45 | */ 46 | public static boolean checkNetwork(Context context) { 47 | ConnectivityManager connectivityManager = (ConnectivityManager) context 48 | .getSystemService(Context.CONNECTIVITY_SERVICE); 49 | NetworkInfo networkInfo = connectivityManager == null ? null : connectivityManager.getActiveNetworkInfo(); 50 | return networkInfo != null && networkInfo.isConnected(); 51 | } 52 | 53 | /** 54 | * Get network type name 55 | * 56 | * @param context 57 | * @return 58 | */ 59 | public static String getNetworkTypeName(Context context) { 60 | ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 61 | NetworkInfo networkInfo; 62 | String type = NETWORK_TYPE_DISCONNECT; 63 | if (manager == null || (networkInfo = manager.getActiveNetworkInfo()) == null) { 64 | return type; 65 | } 66 | ; 67 | 68 | if (networkInfo.isConnected()) { 69 | String typeName = networkInfo.getTypeName(); 70 | if (WIFI.equalsIgnoreCase(typeName)) { 71 | type = NETWORK_TYPE_WIFI; 72 | } else if (MOBILE.equalsIgnoreCase(typeName)) { 73 | String proxyHost = android.net.Proxy.getDefaultHost(); 74 | type = TextUtils.isEmpty(proxyHost) ? (isFastMobileNetwork(context) ? NETWORK_TYPE_3G : NETWORK_TYPE_2G) 75 | : NETWORK_TYPE_WAP; 76 | } else { 77 | type = NETWORK_TYPE_UNKNOWN; 78 | } 79 | } 80 | return type; 81 | } 82 | 83 | /** 84 | * Whether is fast mobile network 85 | * 86 | * @param context 87 | * @return 88 | */ 89 | private static boolean isFastMobileNetwork(Context context) { 90 | TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 91 | if (telephonyManager == null) { 92 | return false; 93 | } 94 | 95 | switch (telephonyManager.getNetworkType()) { 96 | case TelephonyManager.NETWORK_TYPE_EVDO_0: 97 | case TelephonyManager.NETWORK_TYPE_EVDO_A: 98 | case TelephonyManager.NETWORK_TYPE_HSDPA: 99 | case TelephonyManager.NETWORK_TYPE_HSPA: 100 | case TelephonyManager.NETWORK_TYPE_HSUPA: 101 | case TelephonyManager.NETWORK_TYPE_UMTS: 102 | case TelephonyManager.NETWORK_TYPE_EHRPD: 103 | case TelephonyManager.NETWORK_TYPE_EVDO_B: 104 | case TelephonyManager.NETWORK_TYPE_HSPAP: 105 | case TelephonyManager.NETWORK_TYPE_LTE: 106 | return true; 107 | case TelephonyManager.NETWORK_TYPE_1xRTT: 108 | case TelephonyManager.NETWORK_TYPE_CDMA: 109 | case TelephonyManager.NETWORK_TYPE_EDGE: 110 | case TelephonyManager.NETWORK_TYPE_GPRS: 111 | case TelephonyManager.NETWORK_TYPE_IDEN: 112 | case TelephonyManager.NETWORK_TYPE_UNKNOWN: 113 | default: 114 | return false; 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/NumberUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.RoundingMode; 5 | import java.text.DecimalFormat; 6 | 7 | /** 8 | * @author wlj 9 | * @date 2017/3/29 10 | * @email wanglijundev@gmail.com 11 | * @packagename wanglijun.vip.androidutils.utils 12 | * @desc: 数字格式化操作类 13 | */ 14 | 15 | public class NumberUtils { 16 | /** 17 | * 保留一位小数 18 | * 19 | * @param number 20 | * @return 21 | */ 22 | public static String formatOneDecimal(float number) { 23 | DecimalFormat oneDec = new DecimalFormat("##0.0"); 24 | return oneDec.format(number); 25 | } 26 | 27 | /** 28 | * 保留两位小数 29 | * 30 | * @param number 31 | * @return 32 | */ 33 | public static String formatTwoDecimal(float number) { 34 | DecimalFormat twoDec = new DecimalFormat("##0.00"); 35 | return twoDec.format(number); 36 | } 37 | 38 | /** 39 | * 保留两位小数百分比 40 | * 41 | * @param number 42 | * @return 43 | */ 44 | public static String formatTwoDecimalPercent(float number) { 45 | return formatTwoDecimal(number) + "%"; 46 | } 47 | 48 | /** 49 | * 四舍五入 50 | * 51 | * @param number 52 | * @param scale scale of the result returned. 53 | * @return 54 | */ 55 | public static double roundingNumber(float number, int scale) { 56 | return roundingNumber(number, scale, RoundingMode.HALF_UP); 57 | } 58 | 59 | /** 60 | * 四舍五入 61 | * 62 | * @param number 63 | * @param scale scale of the result returned. 64 | * @param roundingMode rounding mode to be used to round the result. 65 | * @return 66 | */ 67 | public static double roundingNumber(float number, int scale, RoundingMode roundingMode) { 68 | BigDecimal b = new BigDecimal(number); 69 | return b.setScale(scale, roundingMode).doubleValue(); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/ObjectUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * @author wlj 7 | * @date 2017/3/29 8 | * @email wanglijundev@gmail.com 9 | * @packagename wanglijun.vip.androidutils.utils 10 | * @desc: 对象操作 11 | */ 12 | 13 | public class ObjectUtils { 14 | /** 15 | * Returns true if a and b are equal. 16 | * 如果a和b相等,返回TRUE 17 | * 18 | * @param a 19 | * @param b 20 | * @return 21 | */ 22 | public static boolean equals(Object a, Object b) { 23 | return a == b || (Objects.equals(a, b)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/PackageManagerUtil.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.content.ComponentName; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.pm.ApplicationInfo; 7 | import android.content.pm.PackageInfo; 8 | import android.content.pm.PackageManager; 9 | import android.content.pm.ProviderInfo; 10 | import android.content.pm.ResolveInfo; 11 | import android.content.res.Resources; 12 | import java.util.List; 13 | 14 | 15 | 16 | /** 17 | * @author wlj 18 | * @date 2018/09/01 19 | * @email wanglijundev@gmail.com 20 | * @packagename wanglijun.vip.androidutils 21 | * @description PackageManager工具类 22 | */ 23 | public class PackageManagerUtil { 24 | 25 | 26 | public static List queryIntentActivities(Context context, Intent intent) { 27 | synchronized (PackageManagerUtil.class) { 28 | return context.getPackageManager().queryIntentActivities(intent, 0); 29 | } 30 | } 31 | 32 | public static PackageManager getPackageManager(Context context) { 33 | synchronized (PackageManagerUtil.class) { 34 | return context.getPackageManager(); 35 | } 36 | } 37 | 38 | public static PackageInfo getPackageInfo(Context context, String packageName, int flags) throws PackageManager.NameNotFoundException { 39 | synchronized (PackageManagerUtil.class) { 40 | return context.getPackageManager().getPackageInfo(packageName, flags); 41 | } 42 | } 43 | 44 | public static Resources getResourcesForApplication(Context context, String packageName) throws PackageManager.NameNotFoundException { 45 | synchronized (PackageManagerUtil.class) { 46 | return context.getPackageManager().getResourcesForApplication(packageName); 47 | } 48 | } 49 | 50 | public static List getInstalledPackages(Context context, int flags) { 51 | synchronized (PackageManagerUtil.class) { 52 | return context.getPackageManager().getInstalledPackages(flags); 53 | } 54 | } 55 | 56 | public static Intent getLaunchIntentForPackage(Context context, String packageName) { 57 | synchronized (PackageManagerUtil.class) { 58 | return context.getPackageManager().getLaunchIntentForPackage(packageName); 59 | } 60 | } 61 | 62 | public static PackageInfo getPackageArchiveInfo(Context context, String archiveFilePath, int flags) { 63 | synchronized (PackageManagerUtil.class) { 64 | return context.getPackageManager().getPackageArchiveInfo(archiveFilePath, flags); 65 | } 66 | } 67 | 68 | public static ApplicationInfo getApplicationInfo(Context context, String packageName, int flags) throws PackageManager.NameNotFoundException { 69 | synchronized (PackageManagerUtil.class) { 70 | return context.getPackageManager().getApplicationInfo(packageName, flags); 71 | } 72 | } 73 | 74 | public static ResolveInfo resolveActivity(Context context, Intent intent, int flags) { 75 | synchronized (PackageManagerUtil.class) { 76 | return context.getPackageManager().resolveActivity( 77 | intent, flags); 78 | } 79 | } 80 | 81 | public static boolean hasSystemFeature(Context context, String name) { 82 | synchronized (PackageManagerUtil.class) { 83 | return context.getPackageManager().hasSystemFeature(name); 84 | } 85 | } 86 | 87 | public static void clearPackagePreferredActivities(Context context, String packageName) { 88 | synchronized (PackageManagerUtil.class) { 89 | context.getPackageManager().clearPackagePreferredActivities(packageName); 90 | } 91 | } 92 | 93 | public static void setComponentEnabledSetting(Context context, ComponentName componentName, 94 | int newState, int flags) { 95 | synchronized (PackageManagerUtil.class) { 96 | context.getPackageManager().setComponentEnabledSetting(componentName, 97 | newState, 98 | flags 99 | ); 100 | } 101 | } 102 | 103 | public static List queryIntentServices(Context context, Intent intent, int flags) { 104 | synchronized (PackageManagerUtil.class) { 105 | return context.getPackageManager().queryIntentServices(intent, flags); 106 | } 107 | } 108 | 109 | public static CharSequence getApplicationLabel(Context context, ApplicationInfo info) { 110 | synchronized (PackageManagerUtil.class) { 111 | return context.getPackageManager().getApplicationLabel(info); 112 | } 113 | } 114 | 115 | public static List queryContentProviders(Context context, String processName, int uid, int flags) { 116 | synchronized (PackageManagerUtil.class) { 117 | return context.getPackageManager().queryContentProviders(processName, uid, flags); 118 | } 119 | } 120 | 121 | public static 122 | String[] getPackagesForUid(Context context, int uid) { 123 | synchronized (PackageManagerUtil.class) { 124 | return context.getPackageManager().getPackagesForUid(uid); 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/PackageUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.content.ComponentName; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.pm.ApplicationInfo; 7 | import android.content.pm.PackageInfo; 8 | import android.content.pm.PackageManager; 9 | import android.content.pm.ResolveInfo; 10 | import android.net.Uri; 11 | 12 | import java.io.File; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | /** 17 | * @author wlj 18 | * @date 2017/3/29 19 | * @email wanglijundev@gmail.com 20 | * @packagename wanglijun.vip.androidutils.utils 21 | * @desc: 包的相关操作 22 | */ 23 | 24 | public class PackageUtils { 25 | /** 26 | * Check whether a particular package has been granted a particular permission. 27 | * 检查包是否授予权限 28 | * 29 | * @param context 30 | * @param permName 31 | * @param pkgName 32 | * @return 33 | */ 34 | public static boolean checkPermission(Context context, String permName, String pkgName) { 35 | PackageManager pm = context.getPackageManager(); 36 | boolean permission = (PackageManager.PERMISSION_GRANTED == pm.checkPermission(permName, pkgName)); 37 | return permission; 38 | } 39 | 40 | /** 41 | * Check whether a particular package has been granted a particular permission. 42 | * 检查包是否授予权限 43 | * 44 | * @param context 45 | * @param permName 46 | * @return 47 | */ 48 | public static boolean checkPermission(Context context, String permName) { 49 | int perm = context.checkCallingOrSelfPermission(permName); 50 | return perm == PackageManager.PERMISSION_GRANTED; 51 | } 52 | 53 | /** 54 | * Install package 55 | * 安装apk 56 | * 57 | * @param context 58 | * @param filePath 59 | * @return 60 | */ 61 | public static boolean install(Context context, String filePath) { 62 | Intent i = new Intent(Intent.ACTION_VIEW); 63 | File file = new File(filePath); 64 | if (!file.exists() || !file.isFile() || file.length() <= 0) { 65 | return false; 66 | } 67 | 68 | i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive"); 69 | i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 70 | context.startActivity(i); 71 | return true; 72 | } 73 | 74 | /** 75 | * Uninstall package 76 | * 卸载apk 77 | * 78 | * @param context 79 | * @param packageName 80 | * @return 81 | */ 82 | public static boolean uninstall(Context context, String packageName) { 83 | if (packageName == null || packageName.length() == 0) { 84 | return false; 85 | } 86 | 87 | Intent i = new Intent(Intent.ACTION_DELETE, Uri.parse(new StringBuilder(32).append("package:") 88 | .append(packageName).toString())); 89 | i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 90 | context.startActivity(i); 91 | return true; 92 | } 93 | 94 | /** 95 | * Judge whether packageName is a system application 96 | * 判断是否是一个系统的应用软件 97 | * 98 | * @param context 99 | * @return 100 | */ 101 | public static boolean isSystemApplication(Context context) { 102 | if (context == null) { 103 | return false; 104 | } 105 | return isSystemApplication(context, context.getPackageName()); 106 | } 107 | 108 | /** 109 | * Judge whether packageName is a system application 110 | * 判断是否是一个系统的应用软件 111 | * 112 | * @param context 113 | * @param packageName 114 | * @return 115 | */ 116 | public static boolean isSystemApplication(Context context, String packageName) { 117 | if (context == null) { 118 | return false; 119 | } 120 | return isSystemApplication(context.getPackageManager(), packageName); 121 | } 122 | 123 | /** 124 | * Judge whether packageName is a system application 125 | * 判断是否是一个系统的应用软件 126 | * 127 | * @param packageManager 128 | * @param packageName 129 | * @return 130 | */ 131 | public static boolean isSystemApplication(PackageManager packageManager, String packageName) { 132 | if (packageManager == null || packageName == null || packageName.length() == 0) { 133 | return false; 134 | } 135 | try { 136 | ApplicationInfo app = packageManager.getApplicationInfo(packageName, 0); 137 | return (app.flags & ApplicationInfo.FLAG_SYSTEM) > 0; 138 | } catch (PackageManager.NameNotFoundException e) { 139 | e.printStackTrace(); 140 | } 141 | return false; 142 | } 143 | 144 | /** 145 | * Get installed package infos 146 | * 获取安装包信息 147 | * 148 | * @param context 149 | * @return 150 | */ 151 | public static List getInstalledPackageInfo(Context context) { 152 | return context.getPackageManager().getInstalledPackages(0); 153 | } 154 | 155 | /** 156 | * Judge whether the packageName is installed 157 | * 判断是否安装了软件 158 | * 159 | * @param context 160 | * @param packageName 161 | * @return 162 | */ 163 | public static boolean isInstalled(Context context, String packageName) { 164 | if (!StringUtils.isEmpty(packageName)) { 165 | List list = getInstalledPackageInfo(context); 166 | if (!CollectionUtils.isEmpty(list)) { 167 | for (PackageInfo pi : list) { 168 | if (packageName.equalsIgnoreCase(pi.packageName)) { 169 | return true; 170 | } 171 | } 172 | } 173 | } 174 | return false; 175 | } 176 | 177 | /** 178 | * Get all apps 179 | * 获取所有的APP 180 | * 181 | * @param context 182 | * @return 183 | */ 184 | public static List getAllApps(Context context) { 185 | List apps = new ArrayList(); 186 | PackageManager packageManager = context.getPackageManager(); 187 | List packageInfo = packageManager.getInstalledPackages(0); 188 | for (int i = 0; i < packageInfo.size(); i++) { 189 | PackageInfo pak = packageInfo.get(i); 190 | if ((pak.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) { 191 | apps.add(pak); 192 | } 193 | } 194 | return apps; 195 | } 196 | 197 | /** 198 | * Start app by packageName 199 | * 通过包名启动应用程序 200 | * 201 | * @param context 202 | * @param packageName 203 | */ 204 | public static void startApp(Context context, String packageName) { 205 | PackageInfo packageinfo = null; 206 | try { 207 | packageinfo = context.getPackageManager().getPackageInfo(packageName, 0); 208 | } catch (PackageManager.NameNotFoundException e) { 209 | e.printStackTrace(); 210 | } 211 | if (packageinfo == null) { 212 | return; 213 | } 214 | 215 | Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null); 216 | resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER); 217 | resolveIntent.setPackage(packageinfo.packageName); 218 | 219 | List resolveInfoList = context.getPackageManager() 220 | .queryIntentActivities(resolveIntent, 0); 221 | 222 | ResolveInfo resolveinfo = resolveInfoList.iterator().next(); 223 | if (resolveinfo != null) { 224 | String pkgName = resolveinfo.activityInfo.packageName; 225 | String className = resolveinfo.activityInfo.name; 226 | 227 | Intent intent = new Intent(Intent.ACTION_MAIN); 228 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 229 | intent.addCategory(Intent.CATEGORY_LAUNCHER); 230 | 231 | ComponentName cn = new ComponentName(pkgName, className); 232 | intent.setComponent(cn); 233 | context.startActivity(intent); 234 | } 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/RandomUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * @author wlj 7 | * @date 2017/3/29 8 | * @email wanglijundev@gmail.com 9 | * @packagename wanglijun.vip.androidutils.utils 10 | * @desc: 获取随机数操作类 11 | */ 12 | 13 | public class RandomUtils { 14 | /** 15 | * Returns a pseudo-random uniformly distributed {@code int}. 16 | * 返回伪随机均匀分布 17 | * 18 | * @return 19 | */ 20 | public static int randomInt() { 21 | Random random = new Random(); 22 | return random.nextInt(); 23 | } 24 | 25 | /** 26 | * Returns a pseudo-random uniformly distributed {@code int} in the half-open range [0, n). 27 | * 28 | * @param n 29 | * @return 30 | */ 31 | public static int randomInt(int n) { 32 | Random random = new Random(); 33 | return random.nextInt(n); 34 | } 35 | 36 | /** 37 | * Returns a pseudo-random uniformly distributed {@code int} in the half-open range [min, max]. 38 | * 39 | * @param min 40 | * @param max 41 | * @return 42 | */ 43 | public static int randomInt(int min, int max) { 44 | Random random = new Random(); 45 | return random.nextInt(max) % (max - min + 1) + min; 46 | } 47 | 48 | /** 49 | * Returns a pseudo-random uniformly distributed {@code int} in the half-open range [0, n). 50 | * 51 | * @param n 52 | * @return 53 | */ 54 | public static int randomInt2(int n) { 55 | return (int) (System.currentTimeMillis() % n); 56 | } 57 | 58 | /** 59 | * Returns a pseudo-random uniformly distributed {@code int} in the half-open range [0, n). 60 | * 61 | * @param n 62 | * @return 63 | */ 64 | public static int randomInt3(int n) { 65 | return (int) (Math.random() * 100); 66 | } 67 | 68 | /** 69 | * Returns a pseudo-random uniformly distributed {@code float} in the half-open range [0.0, 1.0). 70 | * 71 | * @return 72 | */ 73 | public static float randomFloat() { 74 | Random random = new Random(); 75 | return random.nextFloat(); 76 | } 77 | 78 | /** 79 | * Returns a pseudo-random uniformly distributed {@code double} in the half-open range [0.0, 1.0). 80 | * 81 | * @return 82 | */ 83 | public static double randomDouble() { 84 | Random random = new Random(); 85 | return random.nextDouble(); 86 | } 87 | 88 | /** 89 | * Returns a pseudo-random uniformly distributed {@code long}. 90 | * 91 | * @return 92 | */ 93 | public static long randomLong() { 94 | Random random = new Random(); 95 | return random.nextLong(); 96 | } 97 | 98 | /** 99 | * Returns a pseudo-random uniformly distributed {@code boolean}. 100 | * 101 | * @return 102 | */ 103 | public static boolean randomBoolean() { 104 | Random random = new Random(); 105 | return random.nextBoolean(); 106 | } 107 | 108 | /** 109 | * Returns a pseudo-random (approximately) normally distributed {@code double} with mean 0.0 and standard deviation 110 | * 1.0. This method uses the polar method of G. E. P. Box, M. E. Muller, and G. Marsaglia, as described by 111 | * Donald E. Knuth in The Art of Computer Programming, Volume 2: Seminumerical Algorithms, section 3.4.1, 112 | * subsection C, algorithm P. 113 | * 114 | * @return 115 | */ 116 | public static double randomGaussian() { 117 | Random random = new Random(); 118 | return random.nextGaussian(); 119 | } 120 | 121 | /** 122 | * Fills {@code buf} with random bytes. 123 | * 124 | * @param buf 125 | */ 126 | public static void randomBytes(byte[] buf) { 127 | Random random = new Random(); 128 | random.nextBytes(buf); 129 | } 130 | 131 | /** 132 | * Get a random string 133 | * 得到一个随机字符串 134 | * 135 | * @param source 136 | * @param length 137 | * @return 138 | */ 139 | public static String randomString(String source, int length) { 140 | return StringUtils.isEmpty(source) ? null : randomString(source.toCharArray(), length); 141 | } 142 | 143 | /** 144 | * Get a random string 145 | * 得到一个随机字符串 146 | * 147 | * @param sourceChar 148 | * @param length 149 | * @return 150 | */ 151 | public static String randomString(char[] sourceChar, int length) { 152 | if (sourceChar == null || sourceChar.length == 0 || length < 0) { 153 | return null; 154 | } 155 | StringBuilder builder = new StringBuilder(length); 156 | for (int i = 0; i < length; i++) { 157 | builder.append(sourceChar[randomInt(sourceChar.length)]); 158 | } 159 | return builder.toString(); 160 | } 161 | 162 | /** 163 | * Shuffling a int array 164 | * 重新排序数组 165 | * 166 | * @param intArray 167 | * @return 168 | */ 169 | public static int[] shuffle(int[] intArray) { 170 | if (intArray == null) { 171 | return null; 172 | } 173 | return shuffle(intArray, intArray.length); 174 | } 175 | 176 | /** 177 | * Shuffling a int array 178 | * 重新排序数组 179 | * 180 | * @param intArray 181 | * @param shuffleCount 182 | * @return 183 | */ 184 | public static int[] shuffle(int[] intArray, int shuffleCount) { 185 | int length; 186 | if (intArray == null || shuffleCount < 0 || (length = intArray.length) < shuffleCount) { 187 | return null; 188 | } 189 | 190 | int[] out = new int[shuffleCount]; 191 | for (int i = 1; i <= shuffleCount; i++) { 192 | int random = randomInt(length - i); 193 | out[i - 1] = intArray[random]; 194 | int temp = intArray[length - i]; 195 | intArray[length - i] = intArray[random]; 196 | intArray[random] = temp; 197 | } 198 | return out; 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/SHA1Utils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.security.MessageDigest; 4 | import java.security.NoSuchAlgorithmException; 5 | 6 | /** 7 | * @author wlj 8 | * @date 2017/3/29 9 | * @email wanglijundev@gmail.com 10 | * @packagename wanglijun.vip.androidutils.utils 11 | * @desc: SHA1 操作类 12 | */ 13 | 14 | public class SHA1Utils { 15 | /** 16 | * Encode SHA1 for a string 17 | * 18 | * @param s 19 | * @return 20 | */ 21 | public static String SHA1(String s) { 22 | try { 23 | MessageDigest digest = MessageDigest.getInstance("SHA-1"); 24 | digest.update(s.getBytes()); 25 | byte[] messageDigest = digest.digest(); 26 | return toHexString(messageDigest); 27 | } catch (NoSuchAlgorithmException e) { 28 | e.printStackTrace(); 29 | } 30 | return ""; 31 | } 32 | 33 | public static String toHexString(byte[] keyData) { 34 | if (keyData == null) { 35 | return null; 36 | } 37 | int expectedStringLen = keyData.length * 2; 38 | StringBuilder sb = new StringBuilder(expectedStringLen); 39 | for (int i = 0; i < keyData.length; i++) { 40 | String hexStr = Integer.toString(keyData[i] & 0x00FF, 16); 41 | if (hexStr.length() == 1) { 42 | hexStr = "0" + hexStr; 43 | } 44 | sb.append(hexStr); 45 | } 46 | return sb.toString(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/SPUtil.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | /** 4 | * @author: wlj 5 | * @Date: 2017-03-28 6 | * @email: wanglijundev@gmail.com 7 | * @desc: SharedPreferences统一管理类 8 | */ 9 | 10 | import android.content.Context; 11 | import android.content.SharedPreferences; 12 | 13 | import java.lang.reflect.InvocationTargetException; 14 | import java.lang.reflect.Method; 15 | import java.util.Map; 16 | 17 | 18 | public class SPUtil { 19 | /** 20 | * 保存在手机里面的文件名 21 | */ 22 | public static final String FILE_NAME = "share_data"; 23 | 24 | /** 25 | * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 26 | * 27 | * @param context 28 | * @param key 29 | * @param object 30 | */ 31 | public static void put(Context context, String key, Object object) { 32 | 33 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 34 | Context.MODE_PRIVATE); 35 | SharedPreferences.Editor editor = sp.edit(); 36 | 37 | if (object instanceof String) { 38 | editor.putString(key, (String) object); 39 | } else if (object instanceof Integer) { 40 | editor.putInt(key, (Integer) object); 41 | } else if (object instanceof Boolean) { 42 | editor.putBoolean(key, (Boolean) object); 43 | } else if (object instanceof Float) { 44 | editor.putFloat(key, (Float) object); 45 | } else if (object instanceof Long) { 46 | editor.putLong(key, (Long) object); 47 | } else { 48 | editor.putString(key, object.toString()); 49 | } 50 | SharedPreferencesCompat.apply(editor); 51 | } 52 | 53 | 54 | /** 55 | * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 56 | * 57 | * @param context 58 | * @param key 59 | * @param defaultObject 60 | * @return 61 | */ 62 | public static Object get(Context context, String key, Object defaultObject) 63 | { 64 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 65 | Context.MODE_PRIVATE); 66 | 67 | if (defaultObject instanceof String) { 68 | return sp.getString(key, (String) defaultObject); 69 | } else if (defaultObject instanceof Integer) { 70 | return sp.getInt(key, (Integer) defaultObject); 71 | } else if (defaultObject instanceof Boolean) { 72 | return sp.getBoolean(key, (Boolean) defaultObject); 73 | } else if (defaultObject instanceof Float) { 74 | return sp.getFloat(key, (Float) defaultObject); 75 | } else if (defaultObject instanceof Long) { 76 | return sp.getLong(key, (Long) defaultObject); 77 | } 78 | return null; 79 | } 80 | 81 | /** 82 | * 移除某个key值已经对应的值 83 | * @param context 84 | * @param key 85 | */ 86 | public static void remove(Context context, String key) { 87 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 88 | Context.MODE_PRIVATE); 89 | SharedPreferences.Editor editor = sp.edit(); 90 | editor.remove(key); 91 | SharedPreferencesCompat.apply(editor); 92 | } 93 | 94 | /** 95 | * 清除所有数据 96 | * @param context 97 | */ 98 | public static void clear(Context context) { 99 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 100 | Context.MODE_PRIVATE); 101 | SharedPreferences.Editor editor = sp.edit(); 102 | editor.clear(); 103 | SharedPreferencesCompat.apply(editor); 104 | } 105 | 106 | /** 107 | * 查询某个key是否已经存在 108 | * @param context 109 | * @param key 110 | * @return 111 | */ 112 | public static boolean contains(Context context, String key) { 113 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 114 | Context.MODE_PRIVATE); 115 | return sp.contains(key); 116 | } 117 | 118 | /** 119 | * 返回所有的键值对 120 | * 121 | * @param context 122 | * @return 123 | */ 124 | public static Map getAll(Context context) { 125 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 126 | Context.MODE_PRIVATE); 127 | return sp.getAll(); 128 | } 129 | 130 | /** 131 | * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 132 | * 133 | * @author zhy 134 | * 135 | */ 136 | private static class SharedPreferencesCompat { 137 | private static final Method sApplyMethod = findApplyMethod(); 138 | 139 | /** 140 | * 反射查找apply的方法 141 | * 142 | * @return 143 | */ 144 | @SuppressWarnings({ "unchecked", "rawtypes" }) 145 | private static Method findApplyMethod() { 146 | try { 147 | Class clz = SharedPreferences.Editor.class; 148 | return clz.getMethod("apply"); 149 | } catch (NoSuchMethodException e) { 150 | } 151 | return null; 152 | } 153 | 154 | /** 155 | * 如果找到则使用apply执行,否则使用commit 156 | * 157 | * @param editor 158 | */ 159 | public static void apply(SharedPreferences.Editor editor) { 160 | try { 161 | if (sApplyMethod != null) { 162 | sApplyMethod.invoke(editor); 163 | return; 164 | } 165 | } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { 166 | } 167 | editor.commit(); 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/SerializableUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.content.Context; 4 | 5 | import java.io.FileInputStream; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.io.InvalidClassException; 9 | import java.io.ObjectInputStream; 10 | import java.io.ObjectOutputStream; 11 | import java.io.Serializable; 12 | 13 | /** 14 | * @author wlj 15 | * @date 2017/3/29 16 | * @email wanglijundev@gmail.com 17 | * @packagename wanglijun.vip.androidutils.utils 18 | * @desc: 序列化和反序列化操作类 19 | */ 20 | 21 | public class SerializableUtils { 22 | /** 23 | * 序列化数据 24 | * 25 | * @param context 26 | * @param fileName 27 | * @param obj 28 | * @throws IOException 29 | */ 30 | public static void serializeData(Context context, String fileName, Object obj) throws IOException { 31 | if (!(obj instanceof Serializable)) { 32 | throw new InvalidClassException("Object must be serialized!"); 33 | } 34 | FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); 35 | ObjectOutputStream ostream = new ObjectOutputStream(fos); 36 | ostream.writeObject(obj); 37 | ostream.flush(); 38 | ostream.close(); 39 | fos.close(); 40 | } 41 | 42 | /** 43 | * 反序列化数据 44 | * 45 | * @param context 46 | * @param fileName 47 | * @return 48 | * @throws ClassNotFoundException 49 | * @throws IOException 50 | */ 51 | public static Object deserializeData(Context context, String fileName) throws ClassNotFoundException, IOException { 52 | FileInputStream fis = context.openFileInput(fileName); 53 | ObjectInputStream s = new ObjectInputStream(fis); 54 | Object obj = s.readObject(); 55 | s.close(); 56 | fis.close(); 57 | return obj; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/ServiceUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.app.ActivityManager; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * @author wlj 11 | * @date 2017/3/29 12 | * @email wanglijundev@gmail.com 13 | * @packagename wanglijun.vip.androidutils.utils 14 | * @desc: 服务开启与关闭 15 | */ 16 | 17 | public class ServiceUtils { 18 | /** 19 | * Judge whether a service is running 20 | * 21 | * @param context 22 | * @param className 23 | * @return 24 | */ 25 | public static boolean isServiceRunning(Context context, String className) { 26 | boolean isRunning = false; 27 | ActivityManager activityManager = (ActivityManager) context 28 | .getSystemService(Context.ACTIVITY_SERVICE); 29 | List serviceInfos = activityManager 30 | .getRunningServices(Integer.MAX_VALUE); 31 | for (ActivityManager.RunningServiceInfo si : serviceInfos) { 32 | if (className.equals(si.service.getClassName())) { 33 | isRunning = true; 34 | } 35 | } 36 | return isRunning; 37 | } 38 | 39 | /** 40 | * Stop running service 41 | * 42 | * @param context 43 | * @param className 44 | * @return 45 | */ 46 | public static boolean stopRunningService(Context context, String className) { 47 | Intent intentService = null; 48 | boolean ret = false; 49 | try { 50 | intentService = new Intent(context, Class.forName(className)); 51 | } catch (Exception e) { 52 | e.printStackTrace(); 53 | } 54 | if (intentService != null) { 55 | ret = context.stopService(intentService); 56 | } 57 | return ret; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/StringUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.text.TextUtils; 4 | 5 | import java.io.UnsupportedEncodingException; 6 | import java.net.URLDecoder; 7 | import java.net.URLEncoder; 8 | import java.util.Locale; 9 | 10 | /** 11 | * @author wlj 12 | * @date 2017/3/29 13 | * @email wanglijundev@gmail.com 14 | * @packagename wanglijun.vip.androidutils.utils 15 | * @desc: 字符串操作 16 | */ 17 | 18 | public class StringUtils { 19 | /** 20 | * Judge whether a string is whitespace, empty ("") or null. 21 | * 22 | * @param str 23 | * @return 24 | */ 25 | public static boolean isEmpty(String str) { 26 | int strLen; 27 | if (str == null || (strLen = str.length()) == 0 || "null".equalsIgnoreCase(str)) { 28 | return true; 29 | } 30 | for (int i = 0; i < strLen; i++) { 31 | if ((!Character.isWhitespace(str.charAt(i)))) { 32 | return false; 33 | } 34 | } 35 | return true; 36 | } 37 | 38 | /** 39 | * Returns true if a and b are equal, including if they are both null. 40 | * 41 | * @param a 42 | * @param b 43 | * @return 44 | */ 45 | public static boolean equals(CharSequence a, CharSequence b) { 46 | return TextUtils.equals(a, b); 47 | } 48 | 49 | /** 50 | * Judge whether a string is number. 51 | * 52 | * @param str 53 | * @return 54 | */ 55 | public static boolean isNumeric(String str) { 56 | for (int i = str.length(); --i >= 0; ) { 57 | if (!Character.isDigit(str.charAt(i))) { 58 | return false; 59 | } 60 | } 61 | return true; 62 | } 63 | 64 | /** 65 | * Encode a string 66 | * 67 | * @param str 68 | * @return 69 | */ 70 | public static String encodeString(String str) { 71 | try { 72 | return URLEncoder.encode(str, "UTF-8"); 73 | } catch (UnsupportedEncodingException e) { 74 | e.printStackTrace(); 75 | return str; 76 | } 77 | } 78 | 79 | /** 80 | * Decode a string 81 | * 82 | * @param str 83 | * @return 84 | */ 85 | public static String decodeString(String str) { 86 | try { 87 | return URLDecoder.decode(str, "UTF-8"); 88 | } catch (UnsupportedEncodingException e) { 89 | e.printStackTrace(); 90 | return str; 91 | } 92 | } 93 | 94 | /** 95 | * Converts this string to lower case, using the rules of {@code locale}. 96 | * 97 | * @param s 98 | * @return 99 | */ 100 | public static String toLowerCase(String s) { 101 | return s.toLowerCase(Locale.getDefault()); 102 | } 103 | 104 | /** 105 | * Converts this this string to upper case, using the rules of {@code locale}. 106 | * 107 | * @param s 108 | * @return 109 | */ 110 | public static String toUpperCase(String s) { 111 | return s.toUpperCase(Locale.getDefault()); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/SystemUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.os.Build; 4 | 5 | /** 6 | * @author wlj 7 | * @date 2017/3/29 8 | * @email wanglijundev@gmail.com 9 | * @packagename wanglijun.vip.androidutils.utils 10 | * @desc: 获取系统信息工具类 11 | */ 12 | 13 | public class SystemUtils { 14 | 15 | /** 16 | * ART 17 | * 18 | * @return 19 | */ 20 | public static boolean isART() { 21 | final String vmVersion = System.getProperty("java.vm.version"); 22 | return vmVersion != null && vmVersion.startsWith("2"); 23 | } 24 | 25 | /** 26 | * DALVIK 27 | * 28 | * @return 29 | */ 30 | public static boolean isDalvik() { 31 | final String vmVersion = System.getProperty("java.vm.version"); 32 | return vmVersion != null && vmVersion.startsWith("1"); 33 | } 34 | 35 | /** 36 | * The brand (e.g., Xiaomi) the software is customized for, if any. 37 | * 38 | * @return 39 | */ 40 | public static String getBrand() { 41 | return Build.BRAND; 42 | } 43 | 44 | /** 45 | * The name of the underlying board, like "MSM8660_SURF". 46 | * 47 | * @return 48 | */ 49 | public static String getBoard() { 50 | return Build.BOARD; 51 | } 52 | 53 | /** 54 | * The end-user-visible name for the end product, like "MI-ONE Plus". 55 | * 56 | * @return 57 | */ 58 | public static String getModel() { 59 | return Build.MODEL; 60 | } 61 | 62 | /** 63 | * Either a changelist number, or a label like "JZO54K". 64 | * 65 | * @return 66 | */ 67 | public static String getID() { 68 | return Build.ID; 69 | } 70 | 71 | /** 72 | * The user-visible version string, like "4.1.2". 73 | * 74 | * @return 75 | */ 76 | public static String getVersionRelease() { 77 | return Build.VERSION.RELEASE; 78 | } 79 | 80 | /** 81 | * The user-visible SDK version of the framework. 82 | * 83 | * @return 84 | */ 85 | public static int getVersionSDK() { 86 | return Build.VERSION.SDK_INT; 87 | } 88 | 89 | /** 90 | * A string that uniquely identifies this build. Do not attempt to parse this value. 91 | * 92 | * @return 93 | */ 94 | public static String getFingerPrint() { 95 | return Build.FINGERPRINT; 96 | } 97 | 98 | /** 99 | * The name of the overall product, like "mione_plus". 100 | * 101 | * @return 102 | */ 103 | public static String getProduct() { 104 | return Build.PRODUCT; 105 | } 106 | 107 | /** 108 | * The manufacturer of the product/hardware, like "Xiaomi". 109 | * 110 | * @return 111 | */ 112 | public static String getManufacturer() { 113 | return Build.MANUFACTURER; 114 | } 115 | 116 | /** 117 | * The name of the industrial design, like "mione_plus". 118 | * 119 | * @return 120 | */ 121 | public static String getDevice() { 122 | return Build.DEVICE; 123 | } 124 | 125 | /** 126 | * The name of the instruction set (CPU type + ABI convention) of native code, like "armeabi-v7a". 127 | * 128 | * @return 129 | */ 130 | public static String getCpuAbi() { 131 | return Build.CPU_ABI; 132 | } 133 | 134 | /** 135 | * The name of the second instruction set (CPU type + ABI convention) of native code, like "armeabi". 136 | * 137 | * @return 138 | */ 139 | public static String getCpuAbi2() { 140 | return Build.CPU_ABI2; 141 | } 142 | 143 | /** 144 | * A build ID string meant for displaying to the user, like "JZO54K". 145 | * 146 | * @return 147 | */ 148 | public static String getDisplay() { 149 | return Build.DISPLAY; 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/TimeUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Calendar; 6 | import java.util.Date; 7 | import java.util.Locale; 8 | import java.util.TimeZone; 9 | 10 | /** 11 | * 时间相关 12 | * 13 | * @author wlj 14 | */ 15 | public class TimeUtils { 16 | 17 | private TimeUtils() { 18 | throw new UnsupportedOperationException("u can't fuck me..."); 19 | } 20 | 21 | /** 22 | *

在工具类中经常使用到工具类的格式化描述,这个主要是一个日期的操作类,所以日志格式主要使用 SimpleDateFormat的定义格式.

23 | * 格式的意义如下: 日期和时间模式
24 | *

日期和时间格式由日期和时间模式字符串指定。在日期和时间模式字符串中,未加引号的字母 'A' 到 'Z' 和 'a' 到 'z' 25 | * 被解释为模式字母,用来表示日期或时间字符串元素。文本可以使用单引号 (') 引起来,以免进行解释。"''" 26 | * 表示单引号。所有其他字符均不解释;只是在格式化时将它们简单复制到输出字符串,或者在分析时与输入字符串进行匹配。 27 | *

28 | * 定义了以下模式字母(所有其他字符 'A' 到 'Z' 和 'a' 到 'z' 都被保留):
29 | * 31 | * 32 | * 33 | * 34 | * 35 | * 36 | * 37 | * 38 | * 39 | * 40 | * 41 | * 42 | * 43 | * 44 | * 45 | * 46 | * 47 | * 48 | * 49 | * 50 | * 51 | * 52 | * 53 | * 54 | * 55 | * 56 | * 57 | * 58 | * 59 | * 60 | * 61 | * 62 | * 63 | * 64 | * 65 | * 66 | * 67 | * 68 | * 69 | * 70 | * 71 | * 72 | * 73 | * 74 | * 75 | * 76 | * 77 | * 78 | * 79 | * 80 | * 81 | * 82 | * 83 | * 84 | * 85 | * 86 | * 87 | * 88 | * 89 | * 90 | * 91 | * 92 | * 93 | * 94 | * 95 | * 96 | * 97 | * 98 | * 99 | * 100 | * 101 | * 102 | * 103 | * 104 | * 105 | * 106 | * 107 | * 108 | * 109 | * 110 | * 111 | * 112 | * 113 | * 114 | * 115 | * 116 | * 117 | * 118 | * 119 | * 120 | * 121 | * 122 | * 123 | * 124 | * 125 | * 126 | * 127 | * 128 | * 129 | * 130 | * 131 | * 132 | * 133 | * 134 | * 135 | * 136 | * 137 | * 138 | * 139 | * 140 | * 141 | * 142 | * 143 | * 144 | * 145 | * 146 | * 147 | * 148 | * 149 | * 150 | * 151 | *
字母日期或时间元素表示示例
GEra 标志符TextAD
y Year 1996; 96
M 年中的月份 Month July; Jul; 07
w 年中的周数 Number 27
W 月份中的周数 Number 2
D 年中的天数 Number 189
d 月份中的天数 Number 10
F 月份中的星期 Number 2
E 星期中的天数 Text Tuesday; Tue
a Am/pm 标记 Text PM
H 一天中的小时数(0-23) Number 0
k 一天中的小时数(1-24) Number 24
K am/pm 中的小时数(0-11) Number 0
h am/pm 中的小时数(1-12) Number 12
m 小时中的分钟数 Number 30
s 分钟中的秒数 Number 55
S 毫秒数 Number 978
z 时区 General time zone Pacific Standard Time; PST; GMT-08:00
Z 时区 RFC 822 time zone -0800
152 | *
 153 |      *                          HH:mm    15:44
 154 |      *                         h:mm a    3:44 下午
 155 |      *                        HH:mm z    15:44 CST
 156 |      *                        HH:mm Z    15:44 +0800
 157 |      *                     HH:mm zzzz    15:44 中国标准时间
 158 |      *                       HH:mm:ss    15:44:40
 159 |      *                     yyyy-MM-dd    2016-08-12
 160 |      *               yyyy-MM-dd HH:mm    2016-08-12 15:44
 161 |      *            yyyy-MM-dd HH:mm:ss    2016-08-12 15:44:40
 162 |      *       yyyy-MM-dd HH:mm:ss zzzz    2016-08-12 15:44:40 中国标准时间
 163 |      *  EEEE yyyy-MM-dd HH:mm:ss zzzz    星期五 2016-08-12 15:44:40 中国标准时间
 164 |      *       yyyy-MM-dd HH:mm:ss.SSSZ    2016-08-12 15:44:40.461+0800
 165 |      *     yyyy-MM-dd'T'HH:mm:ss.SSSZ    2016-08-12T15:44:40.461+0800
 166 |      *   yyyy.MM.dd G 'at' HH:mm:ss z    2016.08.12 公元 at 15:44:40 CST
 167 |      *                         K:mm a    3:44 下午
 168 |      *               EEE, MMM d, ''yy    星期五, 八月 12, '16
 169 |      *          hh 'o''clock' a, zzzz    03 o'clock 下午, 中国标准时间
 170 |      *   yyyyy.MMMMM.dd GGG hh:mm aaa    02016.八月.12 公元 03:44 下午
 171 |      *     EEE, d MMM yyyy HH:mm:ss Z    星期五, 12 八月 2016 15:44:40 +0800
 172 |      *                  yyMMddHHmmssZ    160812154440+0800
 173 |      *     yyyy-MM-dd'T'HH:mm:ss.SSSZ    2016-08-12T15:44:40.461+0800
 174 |      * EEEE 'DATE('yyyy-MM-dd')' 'TIME('HH:mm:ss')' zzzz    星期五 DATE(2016-08-12) TIME(15:44:40) 中国标准时间
 175 |      * 
176 | */ 177 | public static ThreadLocal DEFAULT_SDF = new ThreadLocal() { 178 | @Override 179 | protected SimpleDateFormat initialValue() { 180 | return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); 181 | } 182 | }; 183 | public static ThreadLocal CN_MM_DD_SDF = new ThreadLocal() { 184 | @Override 185 | protected SimpleDateFormat initialValue() { 186 | return new SimpleDateFormat("MM月dd日", Locale.getDefault()); 187 | } 188 | }; 189 | public static ThreadLocal CN_M_D_SDF = new ThreadLocal() { 190 | @Override 191 | protected SimpleDateFormat initialValue() { 192 | return new SimpleDateFormat("MM月dd日", Locale.getDefault()); 193 | } 194 | }; 195 | public static ThreadLocal CN_MM_DD_HH_MM_SDF = new ThreadLocal() { 196 | @Override 197 | protected SimpleDateFormat initialValue() { 198 | return new SimpleDateFormat("MM月dd日 HH:mm", Locale.getDefault()); 199 | } 200 | }; 201 | public static ThreadLocal EN_YYYY_MM_DD_SDF = new ThreadLocal() { 202 | @Override 203 | protected SimpleDateFormat initialValue() { 204 | return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); 205 | } 206 | }; 207 | public static ThreadLocal EN_YYYY_MM_SDF = new ThreadLocal() { 208 | @Override 209 | protected SimpleDateFormat initialValue() { 210 | return new SimpleDateFormat("yyyy-MM", Locale.getDefault()); 211 | } 212 | }; 213 | public static ThreadLocal EN_YYYY_MM_DD_HH_MM_SDF = new ThreadLocal() { 214 | @Override 215 | protected SimpleDateFormat initialValue() { 216 | return new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()); 217 | } 218 | }; 219 | public static ThreadLocal EN_YYYY_M_D_HH_MM_SDF = new ThreadLocal() { 220 | @Override 221 | protected SimpleDateFormat initialValue() { 222 | return new SimpleDateFormat("yyyy-M-d HH:mm", Locale.getDefault()); 223 | } 224 | }; 225 | public static ThreadLocal CN_YYYY_MM_DD_SDF = new ThreadLocal() { 226 | @Override 227 | protected SimpleDateFormat initialValue() { 228 | return new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault()); 229 | } 230 | }; 231 | public static ThreadLocal CN_YYYY_MM_DD_HH_MM_SDF = new ThreadLocal() { 232 | @Override 233 | protected SimpleDateFormat initialValue() { 234 | return new SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.getDefault()); 235 | } 236 | }; 237 | public static ThreadLocal CN_YYYY_M_D_SDF = new ThreadLocal() { 238 | @Override 239 | protected SimpleDateFormat initialValue() { 240 | return new SimpleDateFormat("yyyy年M月d日", Locale.getDefault()); 241 | } 242 | }; 243 | public static ThreadLocal CN_YYYY_MM_DD_HH_MM_SS_SDF = new ThreadLocal() { 244 | @Override 245 | protected SimpleDateFormat initialValue() { 246 | return new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒", Locale.getDefault()); 247 | } 248 | }; 249 | public static ThreadLocal CN_YYYY_MM_DD_HH_MM_2_SDF = new ThreadLocal() { 250 | @Override 251 | protected SimpleDateFormat initialValue() { 252 | return new SimpleDateFormat("yyyy年MM月dd日HH时mm分", Locale.getDefault()); 253 | } 254 | }; 255 | public static ThreadLocal CN_YYYY_MM_DD_HH_MM_3_SDF = new ThreadLocal() { 256 | @Override 257 | protected SimpleDateFormat initialValue() { 258 | return new SimpleDateFormat("yyyy年M月d日H时m分", Locale.getDefault()); 259 | } 260 | }; 261 | public static ThreadLocal EN_M_D_SDF = new ThreadLocal() { 262 | @Override 263 | protected SimpleDateFormat initialValue() { 264 | return new SimpleDateFormat("M/d", Locale.getDefault()); 265 | } 266 | }; 267 | public static ThreadLocal EN_MM_DD_SDF = new ThreadLocal() { 268 | @Override 269 | protected SimpleDateFormat initialValue() { 270 | return new SimpleDateFormat("MM-dd", Locale.getDefault()); 271 | } 272 | }; 273 | public static ThreadLocal EN_YYYY_MM_DD_HH_SDF = new ThreadLocal() { 274 | @Override 275 | protected SimpleDateFormat initialValue() { 276 | return new SimpleDateFormat("yyyy-MM-dd HH", Locale.getDefault()); 277 | } 278 | }; 279 | public static ThreadLocal EN_YYYY_MM_DD_HH_SDFS = new ThreadLocal() { 280 | @Override 281 | protected SimpleDateFormat initialValue() { 282 | return new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault()); 283 | } 284 | }; 285 | public static ThreadLocal EN_BIAS_YYYY_MM_DD_SDF = new ThreadLocal() { 286 | @Override 287 | protected SimpleDateFormat initialValue() { 288 | return new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault()); 289 | } 290 | }; 291 | public static ThreadLocal EN_BIAS_YYYY_MM_DD_HH_MM_SDF = new ThreadLocal() { 292 | @Override 293 | protected SimpleDateFormat initialValue() { 294 | return new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.getDefault()); 295 | } 296 | }; 297 | public static ThreadLocal EN_H_MM_SDF = new ThreadLocal() { 298 | @Override 299 | protected SimpleDateFormat initialValue() { 300 | return new SimpleDateFormat("H:mm", Locale.getDefault()); 301 | } 302 | }; 303 | public static ThreadLocal EN_HH_mm = new ThreadLocal() { 304 | @Override 305 | protected SimpleDateFormat initialValue() { 306 | return new SimpleDateFormat("HH:mm", Locale.getDefault()); 307 | } 308 | }; 309 | public static ThreadLocal EN_YYYY_M_D_SDF = new ThreadLocal() { 310 | @Override 311 | protected SimpleDateFormat initialValue() { 312 | return new SimpleDateFormat("yyyy-M-d", Locale.getDefault()); 313 | } 314 | }; 315 | 316 | public static ThreadLocal EN_MM_DD_HH_MM_SDF = 317 | new ThreadLocal() { 318 | @Override 319 | protected SimpleDateFormat initialValue() { 320 | return new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault()); 321 | } 322 | }; 323 | 324 | /** 325 | * 将时间戳转为时间字符串 326 | *

格式为yyyy-MM-dd HH:mm:ss

327 | * 328 | * @param milliseconds 毫秒时间戳 329 | * @return 时间字符串 330 | */ 331 | public static String milliseconds2String(long milliseconds) { 332 | return milliseconds2String(milliseconds, DEFAULT_SDF.get()); 333 | } 334 | 335 | /** 336 | * 将时间戳转为时间字符串 337 | *

格式为用户自定义

338 | * 339 | * @param milliseconds 毫秒时间戳 340 | * @param format 时间格式 341 | * @return 时间字符串 342 | */ 343 | public static String milliseconds2String(long milliseconds, SimpleDateFormat format) { 344 | return format.format(new Date(milliseconds)); 345 | } 346 | 347 | /** 348 | * 将时间字符串转为时间戳 349 | *

格式为yyyy-MM-dd HH:mm:ss

350 | * 351 | * @param time 时间字符串 352 | * @return 毫秒时间戳 353 | */ 354 | public static long string2Milliseconds(String time) { 355 | return string2Milliseconds(time, DEFAULT_SDF.get()); 356 | } 357 | 358 | /** 359 | * 将时间字符串转为时间戳 360 | *

格式为用户自定义

361 | * 362 | * @param time 时间字符串 363 | * @param format 时间格式 364 | * @return 毫秒时间戳 365 | */ 366 | public static long string2Milliseconds(String time, SimpleDateFormat format) { 367 | try { 368 | return format.parse(time).getTime(); 369 | } catch (ParseException e) { 370 | e.printStackTrace(); 371 | } 372 | return -1; 373 | } 374 | 375 | /** 376 | * 将时间字符串转为Date类型 377 | *

格式为yyyy-MM-dd HH:mm:ss

378 | * 379 | * @param time 时间字符串 380 | * @return Date类型 381 | */ 382 | public static Date string2Date(String time) { 383 | return string2Date(time, DEFAULT_SDF.get()); 384 | } 385 | 386 | 387 | /** 388 | * 将时间字符串转为Date类型 389 | *

格式为用户自定义

390 | * 391 | * @param time 时间字符串 392 | * @param format 时间格式 393 | * @return Date类型 394 | */ 395 | public static Date string2Date(String time, SimpleDateFormat format) { 396 | return new Date(string2Milliseconds(time, format)); 397 | } 398 | 399 | /** 400 | * 将Date类型转为时间字符串 401 | *

格式为yyyy-MM-dd HH:mm:ss

402 | * 403 | * @param time Date类型时间 404 | * @return 时间字符串 405 | */ 406 | public static String date2String(Date time) { 407 | return date2String(time, DEFAULT_SDF.get()); 408 | } 409 | 410 | /** 411 | * 将Date类型转为时间字符串 412 | *

格式为用户自定义

413 | * 414 | * @param time Date类型时间 415 | * @param format 时间格式 416 | * @return 时间字符串 417 | */ 418 | public static String date2String(Date time, SimpleDateFormat format) { 419 | return format.format(time); 420 | } 421 | 422 | /** 423 | * 将Date类型转为时间戳 424 | * 425 | * @param time Date类型时间 426 | * @return 毫秒时间戳 427 | */ 428 | public static long date2Milliseconds(Date time) { 429 | return time.getTime(); 430 | } 431 | 432 | /** 433 | * 将时间戳转为Date类型 434 | * 435 | * @param milliseconds 毫秒时间戳 436 | * @return Date类型时间 437 | */ 438 | public static Date milliseconds2Date(long milliseconds) { 439 | return new Date(milliseconds); 440 | } 441 | 442 | /** 443 | * 毫秒时间戳单位转换(单位:unit) 444 | * 445 | * @param milliseconds 毫秒时间戳 446 | * @param unit
    447 | *
  • {@link ConstUtils.TimeUnit#MSEC}: 毫秒
  • 448 | *
  • {@link ConstUtils.TimeUnit#SEC }: 秒
  • 449 | *
  • {@link ConstUtils.TimeUnit#MIN }: 分
  • 450 | *
  • {@link ConstUtils.TimeUnit#HOUR}: 小时
  • 451 | *
  • {@link ConstUtils.TimeUnit#DAY }: 天
  • 452 | *
453 | * @return unit时间戳 454 | */ 455 | private static long milliseconds2Unit(long milliseconds, ConstUtils.TimeUnit unit) { 456 | switch (unit) { 457 | case MSEC: 458 | return milliseconds / ConstUtils.MSEC; 459 | case SEC: 460 | return milliseconds / ConstUtils.SEC; 461 | case MIN: 462 | return milliseconds / ConstUtils.MIN; 463 | case HOUR: 464 | return milliseconds / ConstUtils.HOUR; 465 | case DAY: 466 | return milliseconds / ConstUtils.DAY; 467 | 468 | } 469 | return -1; 470 | } 471 | 472 | /** 473 | * 获取两个时间差(单位:unit) 474 | *

time1和time2格式都为yyyy-MM-dd HH:mm:ss

475 | * 476 | * @param time0 时间字符串1 477 | * @param time1 时间字符串2 478 | * @param unit
    479 | *
  • {@link ConstUtils.TimeUnit#MSEC}: 毫秒
  • 480 | *
  • {@link ConstUtils.TimeUnit#SEC }: 秒
  • 481 | *
  • {@link ConstUtils.TimeUnit#MIN }: 分
  • 482 | *
  • {@link ConstUtils.TimeUnit#HOUR}: 小时
  • 483 | *
  • {@link ConstUtils.TimeUnit#DAY }: 天
  • 484 | *
485 | * @return unit时间戳 486 | */ 487 | public static long getIntervalTime(String time0, String time1, ConstUtils.TimeUnit unit) { 488 | return getIntervalTime(time0, time1, unit, DEFAULT_SDF.get()); 489 | } 490 | 491 | /** 492 | * 获取两个时间差(单位:unit) 493 | *

time1和time2格式都为format

494 | * 495 | * @param time0 时间字符串1 496 | * @param time1 时间字符串2 497 | * @param unit
    498 | *
  • {@link ConstUtils.TimeUnit#MSEC}: 毫秒
  • 499 | *
  • {@link ConstUtils.TimeUnit#SEC }: 秒
  • 500 | *
  • {@link ConstUtils.TimeUnit#MIN }: 分
  • 501 | *
  • {@link ConstUtils.TimeUnit#HOUR}: 小时
  • 502 | *
  • {@link ConstUtils.TimeUnit#DAY }: 天
  • 503 | *
504 | * @param format 时间格式 505 | * @return unit时间戳 506 | */ 507 | public static long getIntervalTime(String time0, String time1, ConstUtils.TimeUnit unit, SimpleDateFormat format) { 508 | return Math.abs(milliseconds2Unit(string2Milliseconds(time0, format) 509 | - string2Milliseconds(time1, format), unit)); 510 | } 511 | 512 | /** 513 | * 获取两个时间差(单位:unit) 514 | *

time1和time2都为Date类型

515 | * 516 | * @param time0 Date类型时间1 517 | * @param time1 Date类型时间2 518 | * @param unit
    519 | *
  • {@link ConstUtils.TimeUnit#MSEC}: 毫秒
  • 520 | *
  • {@link ConstUtils.TimeUnit#SEC }: 秒
  • 521 | *
  • {@link ConstUtils.TimeUnit#MIN }: 分
  • 522 | *
  • {@link ConstUtils.TimeUnit#HOUR}: 小时
  • 523 | *
  • {@link ConstUtils.TimeUnit#DAY }: 天
  • 524 | *
525 | * @return unit时间戳 526 | */ 527 | public static long getIntervalTime(Date time0, Date time1, ConstUtils.TimeUnit unit) { 528 | return Math.abs(milliseconds2Unit(date2Milliseconds(time1) 529 | - date2Milliseconds(time0), unit)); 530 | } 531 | 532 | /** 533 | * 获取两个毫秒值之间的时间差(天数) 534 | * 535 | * @param time1 536 | * @param time2 一般time2写较大的值 537 | * @return 538 | */ 539 | public static int getIntervalTime(long time1, long time2) { 540 | return (int) ((time2 - time1) / (1000 * 3600 * 24)); 541 | } 542 | 543 | /** 544 | * 获取当前时间 545 | * 546 | * @return 毫秒时间戳 547 | */ 548 | public static long getCurTimeMills() { 549 | return System.currentTimeMillis(); 550 | } 551 | 552 | /** 553 | * 获取当前时间 554 | *

格式为yyyy-MM-dd HH:mm:ss

555 | * 556 | * @return 时间字符串 557 | */ 558 | public static String getCurTimeString() { 559 | return date2String(new Date()); 560 | } 561 | 562 | /** 563 | * 获取当前时间 564 | *

格式为用户自定义

565 | * 566 | * @param format 时间格式 567 | * @return 时间字符串 568 | */ 569 | public static String getCurTimeString(SimpleDateFormat format) { 570 | return date2String(new Date(), format); 571 | } 572 | 573 | /** 574 | * 获取当前时间 575 | *

Date类型

576 | * 577 | * @return Date类型时间 578 | */ 579 | public static Date getCurTimeDate() { 580 | return new Date(); 581 | } 582 | 583 | /** 584 | * 获取与当前时间的差(单位:unit) 585 | *

time格式为yyyy-MM-dd HH:mm:ss

586 | * 587 | * @param time 时间字符串 588 | * @param unit
    589 | *
  • {@link ConstUtils.TimeUnit#MSEC}:毫秒
  • 590 | *
  • {@link ConstUtils.TimeUnit#SEC }:秒
  • 591 | *
  • {@link ConstUtils.TimeUnit#MIN }:分
  • 592 | *
  • {@link ConstUtils.TimeUnit#HOUR}:小时
  • 593 | *
  • {@link ConstUtils.TimeUnit#DAY }:天
  • 594 | *
595 | * @return unit时间戳 596 | */ 597 | public static long getIntervalByNow(String time, ConstUtils.TimeUnit unit) { 598 | return getIntervalByNow(time, unit, DEFAULT_SDF.get()); 599 | } 600 | 601 | /** 602 | * 获取与当前时间的差(单位:unit) 603 | *

time格式为format

604 | * 605 | * @param time 时间字符串 606 | * @param unit
    607 | *
  • {@link ConstUtils.TimeUnit#MSEC}: 毫秒
  • 608 | *
  • {@link ConstUtils.TimeUnit#SEC }: 秒
  • 609 | *
  • {@link ConstUtils.TimeUnit#MIN }: 分
  • 610 | *
  • {@link ConstUtils.TimeUnit#HOUR}: 小时
  • 611 | *
  • {@link ConstUtils.TimeUnit#DAY }: 天
  • 612 | *
613 | * @param format 时间格式 614 | * @return unit时间戳 615 | */ 616 | public static long getIntervalByNow(String time, ConstUtils.TimeUnit unit, SimpleDateFormat format) { 617 | return getIntervalTime(getCurTimeString(), time, unit, format); 618 | } 619 | 620 | /** 621 | * 获取与当前时间的差(单位:unit) 622 | *

time为Date类型

623 | * 624 | * @param time Date类型时间 625 | * @param unit
    626 | *
  • {@link ConstUtils.TimeUnit#MSEC}: 毫秒
  • 627 | *
  • {@link ConstUtils.TimeUnit#SEC }: 秒
  • 628 | *
  • {@link ConstUtils.TimeUnit#MIN }: 分
  • 629 | *
  • {@link ConstUtils.TimeUnit#HOUR}: 小时
  • 630 | *
  • {@link ConstUtils.TimeUnit#DAY }: 天
  • 631 | *
632 | * @return unit时间戳 633 | */ 634 | public static long getIntervalByNow(Date time, ConstUtils.TimeUnit unit) { 635 | return getIntervalTime(getCurTimeDate(), time, unit); 636 | } 637 | 638 | /** 639 | * 判断闰年 640 | * 641 | * @param year 年份 642 | * @return {@code true}: 闰年
{@code false}: 平年 643 | */ 644 | public static boolean isLeapYear(int year) { 645 | return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 646 | } 647 | 648 | /** 649 | * 获取当前日期是星期几
650 | * 651 | * @return 当前日期是星期几 652 | */ 653 | public static String getWeekOfDate() { 654 | String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"}; 655 | Calendar cal = Calendar.getInstance(); 656 | cal.setTime(new Date()); 657 | 658 | int w = cal.get(Calendar.DAY_OF_WEEK) - 1; 659 | if (w < 0) { 660 | w = 0; 661 | } 662 | 663 | return weekDays[w]; 664 | } 665 | 666 | /** 667 | * 获取当前日期是星期几
668 | * 669 | * @return 当前日期是星期几 670 | */ 671 | public static String getWeek() { 672 | String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; 673 | Calendar cal = Calendar.getInstance(); 674 | cal.setTime(new Date()); 675 | 676 | int w = cal.get(Calendar.DAY_OF_WEEK) - 1; 677 | if (w < 0) { 678 | w = 0; 679 | } 680 | 681 | return weekDays[w]; 682 | } 683 | 684 | /** 685 | * 获取当前日期的下一天是星期几
686 | * 687 | * @return 当前日期是星期几 688 | */ 689 | public static String getWeekOfNextDate() { 690 | String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"}; 691 | Calendar cal = Calendar.getInstance(); 692 | cal.setTime(new Date()); 693 | 694 | int w = cal.get(Calendar.DAY_OF_WEEK); 695 | if (w == 0) { 696 | w = 1; 697 | } 698 | if (w > 6) { 699 | w = 0; 700 | } 701 | return weekDays[w]; 702 | } 703 | 704 | /** 705 | * 获取当前是年内的第几周 706 | * 707 | * @return 708 | */ 709 | public static int getWeekOfYear() { 710 | int weekofyear = 0; 711 | try { 712 | Calendar c = Calendar.getInstance(); 713 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 714 | c.setFirstDayOfWeek(Calendar.MONDAY);/*设置周一为一周的第一天*/ 715 | weekofyear = c.get(Calendar.WEEK_OF_YEAR); 716 | } catch (Exception e) { 717 | e.printStackTrace(); 718 | } 719 | return weekofyear; 720 | } 721 | 722 | /** 723 | * 获取日历展示信息 724 | * 725 | * @return 返回日期+周几 726 | */ 727 | public static String getCalendar() { 728 | return TimeUtils.getCurTimeString(TimeUtils.CN_MM_DD_SDF.get()) + " " + TimeUtils.getWeek(); 729 | } 730 | 731 | /** 732 | * 获取桌面时钟的时间 733 | * 20180508 因该方法没被调用,且该方法需要 用到application的上下文,所以暂时注释掉 734 | */ 735 | // public static String getDeskClockTime() { 736 | // ContentResolver cv = ActApplication.getAppContext().getContentResolver(); 737 | // String strTimeFormat = android.provider.Settings.System.getString(cv, 738 | // android.provider.Settings.System.TIME_12_24); 739 | // int hour = "24".equals(strTimeFormat) ? Calendar.HOUR_OF_DAY : Calendar.HOUR; 740 | // Calendar c = Calendar.getInstance(); 741 | //// c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 742 | // c.setTimeZone(TimeZone.getDefault()); 743 | // String mHuor = String.valueOf(c.get(hour)); 744 | // if (hour == Calendar.HOUR && "0".equals(mHuor)) { 745 | // mHuor = "12"; 746 | // } 747 | // String imnute = String.valueOf(c.get(Calendar.MINUTE)); 748 | // if (imnute.length() < 2) { 749 | // imnute = "0" + imnute; 750 | // } 751 | // if (mHuor.length() < 2) { 752 | // mHuor = "0" + mHuor; 753 | // } 754 | // return mHuor + ":" + imnute; 755 | // } 756 | 757 | /** 758 | * 获取当前月份是几月 759 | */ 760 | public static String getCurMonthStr() { 761 | 762 | Calendar c = Calendar.getInstance(); 763 | 764 | int year = c.get(Calendar.YEAR); 765 | int month = c.get(Calendar.MONTH) + 1; 766 | String monthString = null; 767 | 768 | if (month < 10) { 769 | 770 | monthString = 0 + "" + month; 771 | } else { 772 | 773 | monthString = "" + month; 774 | } 775 | 776 | /** 777 | * 月份从0开始计算 778 | */ 779 | return year + "-" + monthString; 780 | } 781 | 782 | /** 783 | * 获取当前月份 784 | * 785 | * @return 786 | */ 787 | public static int getCurMonth() { 788 | int month = 0; 789 | try { 790 | Calendar c = Calendar.getInstance(); 791 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 792 | month = c.get(Calendar.MONTH) + 1; 793 | } catch (Exception e) { 794 | e.printStackTrace(); 795 | } 796 | return month; 797 | } 798 | 799 | /** 800 | * 获取上个月月份 801 | * 802 | * @return 803 | */ 804 | public static int getLastMonth() { 805 | 806 | int last = 1; 807 | int cur = getCurMonth(); 808 | last = cur - 1; 809 | if (last == 0) { 810 | last = 12; 811 | } 812 | return last; 813 | } 814 | 815 | /** 816 | * 获取两个月份差值 817 | * 818 | * @param month1 819 | * @param month2 820 | * @return 821 | */ 822 | public static int getDistanceOfTwoMonth(String month1, String month2) throws ParseException { 823 | 824 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); 825 | Calendar bef = Calendar.getInstance(); 826 | Calendar aft = Calendar.getInstance(); 827 | bef.setTime(sdf.parse(month1)); 828 | aft.setTime(sdf.parse(month2)); 829 | int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH); 830 | int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12; 831 | 832 | return Math.abs(month + result); 833 | } 834 | 835 | /** 836 | * 判断旧日期和新日期【新旧根据获取先后而定】的先后关系,如果新日期大于旧日期则返回true 837 | */ 838 | public static boolean compareDates(int oldYear, int oldMonth, int oldDay, 839 | int newYear, int newMonth, int newDay) { 840 | if (newYear != oldYear) { 841 | return !(newYear < oldYear); 842 | } 843 | 844 | if (newMonth != oldMonth) { 845 | return !(newMonth < oldMonth); 846 | } 847 | 848 | if (newDay != oldDay) { 849 | return !(newDay < oldDay); 850 | } 851 | 852 | return false; 853 | } 854 | 855 | /** 856 | * 获取当前时 857 | */ 858 | public static int getHour() { 859 | final Calendar c = Calendar.getInstance(); 860 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 861 | return c.get(Calendar.HOUR_OF_DAY); 862 | } 863 | 864 | /** 865 | * 获取指定时间的小时 866 | */ 867 | public static int getHour(long timeMills) { 868 | final Calendar c = Calendar.getInstance(); 869 | c.setTimeInMillis(timeMills); 870 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 871 | return c.get(Calendar.HOUR_OF_DAY); 872 | } 873 | 874 | 875 | /** 876 | * 获取当前月的天数 877 | * 878 | * @return 879 | */ 880 | public static int getCurMonthLength() { 881 | Calendar a = Calendar.getInstance(); 882 | a.set(Calendar.DATE, 1); 883 | a.roll(Calendar.DATE, -1); 884 | int maxDate = a.get(Calendar.DATE); 885 | return maxDate; 886 | } 887 | 888 | /** 889 | * 获取当前日期 890 | * 891 | * @return 892 | */ 893 | public static String getCurDayOFMonth() { 894 | Calendar c = Calendar.getInstance(); 895 | return String.valueOf(c.get(Calendar.DAY_OF_MONTH)); 896 | } 897 | 898 | /** 899 | * 获取当前日期 900 | * 901 | * @return 902 | */ 903 | public static int getCurDayOFMonthInt() { 904 | Calendar c = Calendar.getInstance(); 905 | return c.get(Calendar.DAY_OF_MONTH); 906 | } 907 | 908 | /** 909 | * 获取当前年份 910 | * 911 | * @return 912 | */ 913 | public static String getCurYear() { 914 | Calendar c = Calendar.getInstance(); 915 | int year = c.get(Calendar.YEAR); 916 | return year + ""; 917 | } 918 | 919 | /** 920 | * 获取当前是几号 921 | * 922 | * @return 923 | */ 924 | public static int getDay() { 925 | Calendar c = Calendar.getInstance(); 926 | int day = c.get(Calendar.DAY_OF_MONTH); 927 | return day; 928 | } 929 | 930 | /** 931 | * 获取年份 932 | * 933 | * @return 934 | */ 935 | public static String getYear(long time) { 936 | Calendar c = Calendar.getInstance(); 937 | c.setTimeInMillis(time); 938 | int year = c.get(Calendar.YEAR); 939 | return String.valueOf(year); 940 | } 941 | 942 | /** 943 | * 获取距离指定日期指定天数的日期 944 | * 945 | * @param current 946 | * @param diff 947 | * @return 948 | */ 949 | public static String getDayByDiff(String current, int diff) { 950 | Calendar calendar = Calendar.getInstance(); 951 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 952 | String result = null; 953 | try { 954 | calendar.setTime(format.parse(current)); 955 | calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + diff); 956 | result = format.format(calendar.getTime()); 957 | } catch (ParseException e) { 958 | e.printStackTrace(); 959 | } 960 | return result; 961 | } 962 | 963 | /** 964 | * 获取三天后的凌晨 965 | * 966 | * @return 967 | */ 968 | public static long getThreeDaysLater() { 969 | return getTodayZero() + 3 * 24 * 60 * 60 * 1000L; 970 | } 971 | 972 | /** 973 | * 今天零点 974 | */ 975 | public static long getTodayZero() { 976 | String timeStr = getCurTimeString(EN_YYYY_MM_DD_SDF.get()); 977 | return string2Date(timeStr, EN_YYYY_MM_DD_SDF.get()).getTime(); 978 | } 979 | 980 | /** 981 | * 明天零点 982 | * 983 | * @return 984 | */ 985 | public static long getTomorrowZero() { 986 | return getTodayZero() + 24 * 60 * 60 * 1000L; 987 | } 988 | 989 | 990 | /** 991 | * 获取最近一个周末的日期 992 | * 993 | * @param style 返回结果样式 0 day/month 1 month.day 994 | * @return 995 | */ 996 | private static String getLatestSunday(int style) { 997 | String result = ""; 998 | try { 999 | Calendar c = Calendar.getInstance(); 1000 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 1001 | int mDayOfWeek = c.get(Calendar.DAY_OF_WEEK); 1002 | int diff = 0 - (mDayOfWeek - 1); 1003 | if (diff == 0) { 1004 | diff = -7; 1005 | } 1006 | c.setTime(new Date(System.currentTimeMillis())); 1007 | c.add(Calendar.DAY_OF_MONTH, diff); 1008 | String mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH)); 1009 | int mMonth = c.get(Calendar.MONTH) + 1;// 获取mDay所在月份 1010 | if (style == 0) { 1011 | result = mDay + "/" + mMonth; 1012 | } else if (style == 1) { 1013 | result = mMonth + "." + mDay; 1014 | } 1015 | } catch (Exception e) { 1016 | e.printStackTrace(); 1017 | } 1018 | return result; 1019 | } 1020 | 1021 | /** 1022 | * 获取最近一个周末的日期 1023 | * 1024 | * @param diffWeek -1:上一周的周一 -2:上两周的周一 。。。 1025 | * @return 1026 | */ 1027 | public static String getLatestSundayDiff(int diffWeek) { 1028 | String result = ""; 1029 | try { 1030 | Calendar c = Calendar.getInstance(); 1031 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 1032 | int mDayOfWeek = c.get(Calendar.DAY_OF_WEEK); 1033 | int diff = 0 - (mDayOfWeek - 1); 1034 | if (diff == 0) { 1035 | diff = -7; 1036 | } 1037 | diff = diff + (diffWeek * 7 + 1); 1038 | c.setTime(new Date(System.currentTimeMillis())); 1039 | c.add(Calendar.DAY_OF_MONTH, diff); 1040 | String mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH)); 1041 | int mMonth = c.get(Calendar.MONTH) + 1;// 获取mDay所在月份 1042 | result = mMonth + "." + mDay; 1043 | } catch (Exception e) { 1044 | e.printStackTrace(); 1045 | } 1046 | return result; 1047 | } 1048 | 1049 | /** 1050 | * 获取最近一个周末的日期 1051 | * 1052 | * @return [20170605, 20170610] 1053 | */ 1054 | public static String[] getLatestWeekSpan(int diffWeek) { 1055 | String[] result = new String[2]; 1056 | try { 1057 | Calendar c = Calendar.getInstance(); 1058 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 1059 | int mDayOfWeek = c.get(Calendar.DAY_OF_WEEK); 1060 | int diff = 0 - (mDayOfWeek - 1); 1061 | if (diff == 0) { 1062 | diff = -7; 1063 | } 1064 | 1065 | for (int i = 0; i < 2; i++) { 1066 | if (i == 0) { 1067 | diff = diff + (diffWeek * 7 + 1); 1068 | } else { 1069 | diff = diff + 6; 1070 | } 1071 | c.setTime(new Date(System.currentTimeMillis())); 1072 | c.add(Calendar.DAY_OF_MONTH, diff); 1073 | int day = c.get(Calendar.DAY_OF_MONTH); 1074 | String mDay = day + ""; 1075 | if (day < 10) { 1076 | mDay = "0" + day; 1077 | } 1078 | // 获取mDay所在月份 1079 | int month = c.get(Calendar.MONTH) + 1; 1080 | String mMonth = month + ""; 1081 | if (month < 10) { 1082 | mMonth = "0" + month; 1083 | } 1084 | int mYear = c.get(Calendar.YEAR); 1085 | result[i] = mYear + "" + mMonth + "" + mDay; 1086 | } 1087 | } catch (Exception e) { 1088 | e.printStackTrace(); 1089 | } 1090 | return result; 1091 | } 1092 | 1093 | /** 1094 | * 获取最近一周的日期---点分式-周报页面 1095 | * 1096 | * @return 1097 | */ 1098 | public static String getLatestSundayDot() { 1099 | 1100 | String result = ""; 1101 | try { 1102 | Calendar c = Calendar.getInstance(); 1103 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 1104 | int mDayOfWeek = c.get(Calendar.DAY_OF_WEEK); 1105 | // 0 1 2 3 4 5 6 1106 | int diff = 0 - (mDayOfWeek - 1); 1107 | if (diff == 0) { 1108 | diff = -7; 1109 | } 1110 | c.setTime(new Date(System.currentTimeMillis())); 1111 | c.add(Calendar.DAY_OF_MONTH, diff); 1112 | String mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH)); 1113 | // 获取mDay所在月份 1114 | String mMonth = c.get(Calendar.MONTH) + 1 + ""; 1115 | if (mMonth.length() == 1) { 1116 | mMonth = 0 + "" + mMonth; 1117 | } 1118 | if (mDay.length() == 1) { 1119 | mDay = 0 + mDay; 1120 | } 1121 | result = mMonth + "." + mDay; 1122 | } catch (Exception e) { 1123 | e.printStackTrace(); 1124 | } 1125 | return result; 1126 | } 1127 | 1128 | /** 1129 | * 获取最近一月的日期---空格分式-月报页面 1130 | * 1131 | * @return 1132 | */ 1133 | public static String getLastMonthDot() { 1134 | String result = ""; 1135 | try { 1136 | Calendar c = Calendar.getInstance(); 1137 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 1138 | c.setTime(new Date(System.currentTimeMillis())); 1139 | c.add(Calendar.MONTH, -1); 1140 | // 获取mDay所在月份 1141 | String mMonth = c.get(Calendar.MONTH) + 1 + ""; 1142 | String mYear = c.get(Calendar.YEAR) + ""; 1143 | if (mMonth.length() == 1) { 1144 | mMonth = 0 + "" + mMonth; 1145 | } 1146 | result = mYear + "年" + mMonth + "月"; 1147 | } catch (Exception e) { 1148 | e.printStackTrace(); 1149 | } 1150 | return result; 1151 | } 1152 | 1153 | /** 1154 | * 获取上一月的日期---年、月[0-11] 1155 | * 1156 | * @param interval -1:之前1个月 -2之前两个月 -3:之前三个月。。。以此类推 1157 | * @return 1158 | */ 1159 | public static String[] getLastMonthYear(int interval) { 1160 | String[] result = new String[]{"2017", "1"}; 1161 | try { 1162 | Calendar c = Calendar.getInstance(); 1163 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 1164 | c.setTime(new Date(System.currentTimeMillis())); 1165 | c.add(Calendar.MONTH, interval); 1166 | String mMonth = c.get(Calendar.MONTH) + ""; 1167 | String mYear = c.get(Calendar.YEAR) + ""; 1168 | result[0] = mYear; 1169 | result[1] = mMonth; 1170 | } catch (Exception e) { 1171 | e.printStackTrace(); 1172 | } 1173 | return result; 1174 | } 1175 | 1176 | public static String[] getLastMonthRecord(int interval) { 1177 | String[] result = new String[]{"2017", "1"}; 1178 | try { 1179 | Calendar c = Calendar.getInstance(); 1180 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); 1181 | c.setTime(new Date(System.currentTimeMillis())); 1182 | c.add(Calendar.MONTH, interval); 1183 | String mMonth = (c.get(Calendar.MONTH) + 1) + ""; 1184 | String mYear = c.get(Calendar.YEAR) + ""; 1185 | result[0] = mYear; 1186 | result[1] = mMonth; 1187 | } catch (Exception e) { 1188 | e.printStackTrace(); 1189 | } 1190 | return result; 1191 | } 1192 | 1193 | /** 1194 | * 根据日期获取周几 1195 | * 1196 | * @param date:2017-06-04 1197 | */ 1198 | public static String getDayOfWeekByDate(String date) { 1199 | String[] dayOfWeek; 1200 | Calendar calendar; 1201 | String result; 1202 | try { 1203 | dayOfWeek = new String[]{"default", "周日", "周一", "周二", "周三", "周四", "周五", "周六"}; 1204 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 1205 | Date date1 = sdf.parse(date); 1206 | calendar = Calendar.getInstance(); 1207 | calendar.setTime(date1); 1208 | result = dayOfWeek[calendar.get(Calendar.DAY_OF_WEEK)]; 1209 | } catch (ParseException e) { 1210 | result = date; 1211 | e.printStackTrace(); 1212 | } 1213 | return result; 1214 | } 1215 | 1216 | /** 1217 | * 根据日期获取周几 1218 | * 1219 | * @param :geshi:2017-06-04 1220 | * @param date 预报中第一天的日期 1221 | * @param index 第几天 1222 | */ 1223 | public static String getDayOfWeekByDate(long date, int index) { 1224 | String[] dayOfWeek; 1225 | Calendar calendar; 1226 | String result; 1227 | try { 1228 | dayOfWeek = new String[]{"default", "周日", "周一", "周二", "周三", "周四", "周五", "周六"}; 1229 | Date date1 = new Date(date); 1230 | calendar = Calendar.getInstance(); 1231 | calendar.setTime(date1); 1232 | calendar.add(calendar.DATE, index); 1233 | result = dayOfWeek[calendar.get(Calendar.DAY_OF_WEEK)]; 1234 | } catch (Exception e) { 1235 | SimpleDateFormat sdf = new SimpleDateFormat("MM/dd"); 1236 | calendar = Calendar.getInstance(); 1237 | calendar.setTime(new Date(date)); 1238 | calendar.add(calendar.DATE, index); 1239 | result = sdf.format(calendar.getTime()); 1240 | e.printStackTrace(); 1241 | } 1242 | return result; 1243 | } 1244 | 1245 | /** 1246 | * 获取上周周几的日期,默认一周从周一开始 1247 | * 1248 | * @param dayOfWeek 1249 | * @param weekOffset 1250 | * @return 1251 | */ 1252 | public static Date getDayOfWeek(int dayOfWeek, int weekOffset) { 1253 | return getDayOfWeek(Calendar.MONDAY, dayOfWeek, weekOffset); 1254 | } 1255 | 1256 | /** 1257 | * 获取上(下)周周几的日期 1258 | * 1259 | * @param firstDayOfWeek {@link Calendar} 1260 | * 值范围 SUNDAY, 1261 | * MONDAY, TUESDAY, WEDNESDAY, 1262 | * THURSDAY, FRIDAY, and SATURDAY 1263 | * @param dayOfWeek {@link Calendar} 1264 | * @param weekOffset 周偏移,上周为-1,本周为0,下周为1,以此类推 1265 | * @return 1266 | */ 1267 | public static Date getDayOfWeek(int firstDayOfWeek, int dayOfWeek, int weekOffset) { 1268 | if (dayOfWeek > Calendar.SATURDAY || dayOfWeek < Calendar.SUNDAY) { 1269 | return null; 1270 | } 1271 | if (firstDayOfWeek > Calendar.SATURDAY || firstDayOfWeek < Calendar.SUNDAY) { 1272 | return null; 1273 | } 1274 | Calendar date = Calendar.getInstance(Locale.CHINA); 1275 | date.setFirstDayOfWeek(firstDayOfWeek); 1276 | //周数减一,即上周 1277 | date.add(Calendar.WEEK_OF_MONTH, weekOffset); 1278 | //日子设为周几 1279 | date.set(Calendar.DAY_OF_WEEK, dayOfWeek); 1280 | //时分秒全部置0 1281 | date.set(Calendar.HOUR_OF_DAY, 0); 1282 | date.set(Calendar.MINUTE, 0); 1283 | date.set(Calendar.SECOND, 0); 1284 | date.set(Calendar.MILLISECOND, 0); 1285 | return date.getTime(); 1286 | } 1287 | 1288 | /** 1289 | * 将毫秒值转化为友好的时间表达格式 1290 | * 今天 14:52 1291 | * 明天 14:52 1292 | * 昨天 14:52 1293 | * 年一样,日期非今天昨天明天,返回08-12 14:52 1294 | * 年不一样,返回2018-08-12 14:52 1295 | */ 1296 | public static String milliseconds2FriendlyString(long milliseconds) { 1297 | return date2FriendlyString(new Date(milliseconds)); 1298 | } 1299 | 1300 | /** 1301 | * 将Date类型转化为友好的时间表达格式 1302 | * 今天 14:52 1303 | * 明天 14:52 1304 | * 昨天 14:52 1305 | * 年一样,日期非今天昨天明天,返回08-12 14:52 1306 | * 年不一样,返回2018-08-12 14:52 1307 | */ 1308 | public static String date2FriendlyString(Date date) { 1309 | Calendar targetCalendar = Calendar.getInstance(); 1310 | targetCalendar.setTime(date); 1311 | Calendar currentCalendar = Calendar.getInstance(); 1312 | if (currentCalendar.get(Calendar.YEAR) != targetCalendar.get(Calendar.YEAR)) { 1313 | return EN_YYYY_MM_DD_HH_MM_SDF.get().format(date); 1314 | } else { 1315 | int diffDay = currentCalendar.get(Calendar.DAY_OF_YEAR) - targetCalendar.get( 1316 | Calendar.DAY_OF_YEAR); 1317 | if (diffDay == 1) { 1318 | return "昨天 " + EN_HH_mm.get().format(date); 1319 | } else if (diffDay == 0) { 1320 | return "今天 " + EN_HH_mm.get().format(date); 1321 | } else if (diffDay == -1) { 1322 | return "明天 " + EN_HH_mm.get().format(date); 1323 | } else { 1324 | return EN_MM_DD_HH_MM_SDF.get().format(date); 1325 | } 1326 | } 1327 | } 1328 | 1329 | /** 1330 | * 将毫秒值转化为友好的时间表达格式 1331 | * 今天 14:52 1332 | * 明天 14:52 1333 | * 昨天 14:52 1334 | * 年一样,日期非今天昨天明天,返回08-12 14:52 1335 | * 年不一样,返回2018-08-12 14:52 1336 | */ 1337 | public static String milliseconds2FriendlyStringCN(long milliseconds) { 1338 | return date2FriendlyStringCN(new Date(milliseconds)); 1339 | } 1340 | 1341 | /** 1342 | * 将Date类型转化为友好的时间表达格式 1343 | * 今天 14:52 1344 | * 明天 14:52 1345 | * 昨天 14:52 1346 | * 年一样,日期非今天昨天明天,返回08-12 14:52 1347 | * 年不一样,返回2018-08-12 14:52 1348 | */ 1349 | public static String date2FriendlyStringCN(Date date) { 1350 | Calendar targetCalendar = Calendar.getInstance(); 1351 | targetCalendar.setTime(date); 1352 | Calendar currentCalendar = Calendar.getInstance(); 1353 | if (currentCalendar.get(Calendar.YEAR) != targetCalendar.get(Calendar.YEAR)) { 1354 | return EN_YYYY_MM_DD_HH_MM_SDF.get().format(date); 1355 | } else { 1356 | int diffDay = currentCalendar.get(Calendar.DAY_OF_YEAR) - 1357 | targetCalendar.get(Calendar.DAY_OF_YEAR); 1358 | if (diffDay == 1) { 1359 | return "昨天 " + EN_HH_mm.get().format(date); 1360 | } else if (diffDay == 0) { 1361 | return "今天 " + EN_HH_mm.get().format(date); 1362 | } else if (diffDay == -1) { 1363 | return "明天 " + EN_HH_mm.get().format(date); 1364 | } else { 1365 | return CN_MM_DD_HH_MM_SDF.get().format(date); 1366 | } 1367 | } 1368 | } 1369 | 1370 | } -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/ToastUtil.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.widget.Toast; 4 | 5 | import wanglijun.vip.androidutils.Application; 6 | 7 | /** 8 | * @author wlj 9 | * @date 2017/3/28 10 | * @email wanglijundev@gmail.com 11 | * @packagename wanglijun.vip.androidutils 12 | * @description Toast封装类 13 | */ 14 | public class ToastUtil { 15 | private static Toast toast; 16 | /** 17 | * 强大的吐司,能够连续弹的吐司 18 | * @param text 19 | */ 20 | public static void showToast(String text){ 21 | if(toast==null){ 22 | toast = Toast.makeText(Application.context, text,Toast.LENGTH_SHORT); 23 | }else { 24 | toast.setText(text);//如果不为空,则直接改变当前toast的文本 25 | } 26 | toast.show(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/VerifyUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | /** 7 | * @author wlj 8 | * @date 2017/3/29 9 | * @email wanglijundev@gmail.com 10 | * @packagename wanglijun.vip.androidutils.utils 11 | * @desc: 验证数据合法性 12 | */ 13 | 14 | public class VerifyUtils { 15 | /** 16 | * verify whether email is valid 17 | * 18 | * @param email 19 | * @return 20 | */ 21 | public static boolean isEmail(String email) { 22 | Pattern pattern = Pattern 23 | .compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)" + 24 | "+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"); 25 | Matcher matcher = pattern.matcher(email); 26 | return matcher.matches(); 27 | } 28 | 29 | /** 30 | * verify whether email is valid 31 | * 32 | * @param email 33 | * @return 34 | */ 35 | public static boolean isEmail2(String email) { 36 | String expr = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; 37 | return email.matches(expr); 38 | } 39 | 40 | /** 41 | * verify whether mobile number is valid 42 | * 43 | * @param number 44 | * @return 45 | */ 46 | public static boolean isMobileNumber(String number) { 47 | String expr = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$"; 48 | return number.matches(expr); 49 | } 50 | 51 | /** 52 | * verify whether url is valid 53 | * 54 | * @param url 55 | * @return 56 | */ 57 | public static boolean isUrl(String url) { 58 | String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; 59 | Pattern patt = Pattern.compile(regex); 60 | Matcher matcher = patt.matcher(url); 61 | return matcher.matches(); 62 | } 63 | 64 | /** 65 | * verify whether number and letter are only contained 66 | * 67 | * @param data 68 | * @return 69 | */ 70 | public static boolean isNumberAndLetter(String data) { 71 | String expr = "^[A-Za-z0-9]+$"; 72 | return data.matches(expr); 73 | } 74 | 75 | /** 76 | * verify whether number is only contained 77 | * 78 | * @param data 79 | * @return 80 | */ 81 | public static boolean isNumber(String data) { 82 | String expr = "^[0-9]+$"; 83 | return data.matches(expr); 84 | } 85 | 86 | /** 87 | * verify whether letter is only contained 88 | * 89 | * @param data 90 | * @return 91 | */ 92 | public static boolean isLetter(String data) { 93 | String expr = "^[A-Za-z]+$"; 94 | return data.matches(expr); 95 | } 96 | 97 | /** 98 | * verify whether Chinese is only contained 99 | * 100 | * @param data 101 | * @return 102 | */ 103 | public static boolean isChinese(String data) { 104 | String expr = "^[\u0391-\uFFE5]+$"; 105 | return data.matches(expr); 106 | } 107 | 108 | /** 109 | * verify whether Chinese is contained 110 | * 111 | * @param data 112 | * @return 113 | */ 114 | public static boolean isContainsChinese(String data) { 115 | String chinese = "[\u0391-\uFFE5]"; 116 | if (!StringUtils.isEmpty(data)) { 117 | for (int i = 0; i < data.length(); i++) { 118 | String temp = data.substring(i, i + 1); 119 | boolean flag = temp.matches(chinese); 120 | if (flag) { 121 | return true; 122 | } 123 | } 124 | } 125 | return false; 126 | } 127 | 128 | /** 129 | * verify whether chinese identity card is valid 130 | * 131 | * @param data 132 | * @return 133 | */ 134 | public static boolean isChineseCard(String data) { 135 | String expr = "^[0-9]{17}[0-9xX]$"; 136 | return data.matches(expr); 137 | } 138 | 139 | /** 140 | * verify whether post code is valid 141 | * 142 | * @param data 143 | * @return 144 | */ 145 | public static boolean isPostCode(String data) { 146 | String expr = "^[0-9]{6,10}"; 147 | return data.matches(expr); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglijun93/AndroidUtils/4781e11c503ddecbd752f40bc8909d88f9ed110c/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglijun93/AndroidUtils/4781e11c503ddecbd752f40bc8909d88f9ed110c/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglijun93/AndroidUtils/4781e11c503ddecbd752f40bc8909d88f9ed110c/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglijun93/AndroidUtils/4781e11c503ddecbd752f40bc8909d88f9ed110c/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglijun93/AndroidUtils/4781e11c503ddecbd752f40bc8909d88f9ed110c/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AndroidUtils 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/wanglijun/vip/androidutils/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.3.50' 5 | repositories { 6 | jcenter() 7 | maven { 8 | url 'https://maven.google.com/' 9 | name 'Google' 10 | } 11 | } 12 | dependencies { 13 | classpath 'com.android.tools.build:gradle:3.5.3' 14 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 15 | // NOTE: Do not place your application dependencies here; they belong 16 | // in the individual module build.gradle files 17 | } 18 | } 19 | 20 | allprojects { 21 | repositories { 22 | jcenter() 23 | maven { 24 | url 'https://maven.google.com/' 25 | name 'Google' 26 | } 27 | } 28 | } 29 | 30 | task clean(type: Delete) { 31 | delete rootProject.buildDir 32 | } -------------------------------------------------------------------------------- /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 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglijun93/AndroidUtils/4781e11c503ddecbd752f40bc8909d88f9ed110c/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-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | --------------------------------------------------------------------------------