diff --git a/README.md b/README.md index a35fdb8..9fe8633 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ ... -##USE +##Use About Context: 1.Call 'Easy.getDefault().init(this);' on your Application.onCreate(); 2.Call DensityTool.dp2px(...) ... diff --git a/app/build.gradle b/app/build.gradle index 6175998..91126e9 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -5,7 +5,7 @@ android { buildToolsVersion "25.0.2" defaultConfig { applicationId "com.ayvytr.androideasydeveloper" - minSdkVersion 9 + minSdkVersion 11 targetSdkVersion 25 versionCode 1 versionName "1.0" @@ -26,5 +26,5 @@ dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:25.2.0' testCompile 'junit:junit:4.12' - compile project(':easydeveloper') + compile project(':easyAndroidLibrary') } diff --git a/app/src/androidTest/java/com/ayvytr/androideasydeveloper/ExampleInstrumentedTest.java b/app/src/androidTest/java/com/ayvytr/easyandroid/ExampleInstrumentedTest.java similarity index 94% rename from app/src/androidTest/java/com/ayvytr/androideasydeveloper/ExampleInstrumentedTest.java rename to app/src/androidTest/java/com/ayvytr/easyandroid/ExampleInstrumentedTest.java index 0314911..00ee56d 100644 --- a/app/src/androidTest/java/com/ayvytr/androideasydeveloper/ExampleInstrumentedTest.java +++ b/app/src/androidTest/java/com/ayvytr/easyandroid/ExampleInstrumentedTest.java @@ -1,4 +1,4 @@ -package com.ayvytr.androideasydeveloper; +package com.ayvytr.easyandroid; import android.content.Context; import android.support.test.InstrumentationRegistry; diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 164f91f..3cc0422 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,5 +1,5 @@ - - + diff --git a/app/src/main/java/com/ayvytr/androideasydeveloper/MainActivity.java b/app/src/main/java/com/ayvytr/easyandroid/MainActivity.java similarity index 67% rename from app/src/main/java/com/ayvytr/androideasydeveloper/MainActivity.java rename to app/src/main/java/com/ayvytr/easyandroid/MainActivity.java index fa34b73..8e37191 100644 --- a/app/src/main/java/com/ayvytr/androideasydeveloper/MainActivity.java +++ b/app/src/main/java/com/ayvytr/easyandroid/MainActivity.java @@ -1,13 +1,12 @@ -package com.ayvytr.androideasydeveloper; +package com.ayvytr.easyandroid; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; -import com.ayvytr.easydeveloper.Easy; -import com.ayvytr.easydeveloper.tools.withcontext.ClipboardTool; -import com.ayvytr.easydeveloper.tools.withcontext.ResTool; -import com.ayvytr.easydeveloper.tools.withcontext.ToastTool; +import com.ayvytr.easyandroid.tools.withcontext.ClipboardTool; +import com.ayvytr.easyandroid.tools.withcontext.ResTool; +import com.ayvytr.easyandroid.tools.withcontext.ToastTool; public class MainActivity extends AppCompatActivity { @@ -16,7 +15,7 @@ public class MainActivity extends AppCompatActivity protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); + setContentView(com.ayvytr.easyandroidLibrary.R.layout.activity_main); Easy.getDefault().init(getApplicationContext()); init(); } @@ -39,7 +38,7 @@ public void onSetClipboard(View view) public void onGetAppName(View view) { - String string = ResTool.getString(R.string.app_name); + String string = ResTool.getString(com.ayvytr.easyandroidLibrary.R.string.app_name); ToastTool.show("获取到Res中APP名称:" + string); } } diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 9f5ecec..d4acb56 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -11,7 +11,7 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" - tools:context="com.ayvytr.androideasydeveloper.MainActivity"> + tools:context="com.ayvytr.easyandroid.MainActivity"> - - - diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7f47097..768523e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,3 +1,3 @@ - AndroidEasyDeveloper + EasyAndroid diff --git a/easydeveloper/src/test/java/com/ayvytr/easydeveloper/ExampleUnitTest.java b/app/src/test/java/com/ayvytr/easyandroid/ExampleUnitTest.java similarity index 91% rename from easydeveloper/src/test/java/com/ayvytr/easydeveloper/ExampleUnitTest.java rename to app/src/test/java/com/ayvytr/easyandroid/ExampleUnitTest.java index da3233b..e137fe1 100644 --- a/easydeveloper/src/test/java/com/ayvytr/easydeveloper/ExampleUnitTest.java +++ b/app/src/test/java/com/ayvytr/easyandroid/ExampleUnitTest.java @@ -1,4 +1,4 @@ -package com.ayvytr.easydeveloper; +package com.ayvytr.easyandroid; import org.junit.Test; diff --git a/easydeveloper/.gitignore b/easyAndroidLibrary/.gitignore similarity index 100% rename from easydeveloper/.gitignore rename to easyAndroidLibrary/.gitignore diff --git a/easydeveloper/build.gradle b/easyAndroidLibrary/build.gradle similarity index 96% rename from easydeveloper/build.gradle rename to easyAndroidLibrary/build.gradle index 31b97fa..c335eea 100644 --- a/easydeveloper/build.gradle +++ b/easyAndroidLibrary/build.gradle @@ -5,7 +5,7 @@ android { buildToolsVersion "25.0.2" defaultConfig { - minSdkVersion 9 + minSdkVersion 11 targetSdkVersion 25 versionCode 1 versionName "1.0" diff --git a/easydeveloper/proguard-rules.pro b/easyAndroidLibrary/proguard-rules.pro similarity index 100% rename from easydeveloper/proguard-rules.pro rename to easyAndroidLibrary/proguard-rules.pro diff --git a/easydeveloper/src/androidTest/java/com/ayvytr/easydeveloper/DensityToolTest.java b/easyAndroidLibrary/src/androidTest/java/com/ayvytr/easyandroidlibrary/DensityToolTest.java similarity index 96% rename from easydeveloper/src/androidTest/java/com/ayvytr/easydeveloper/DensityToolTest.java rename to easyAndroidLibrary/src/androidTest/java/com/ayvytr/easyandroidlibrary/DensityToolTest.java index 408687c..0ea3c7b 100644 --- a/easydeveloper/src/androidTest/java/com/ayvytr/easydeveloper/DensityToolTest.java +++ b/easyAndroidLibrary/src/androidTest/java/com/ayvytr/easyandroidlibrary/DensityToolTest.java @@ -1,10 +1,10 @@ -package com.ayvytr.easydeveloper; +package com.ayvytr.easyandroidlibrary; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; -import com.ayvytr.easydeveloper.tools.withcontext.DensityTool; +import com.ayvytr.easyandroidlibrary.tools.withcontext.DensityTool; import org.junit.Before; import org.junit.Test; @@ -15,6 +15,7 @@ /** * Instrumentation test, which will execute on an Android device. * 测试 DensityTool 的工具类,对比类:DensityUtils + * * @see DensityTool * @see DensityUtils */ @@ -154,7 +155,7 @@ public static int px2dp(Context context, int pxValue) { final float density = context.getResources().getDisplayMetrics().density; - return (int) ((float)pxValue / density + 0.5f); + return (int) ((float) pxValue / density + 0.5f); } /** diff --git a/easydeveloper/src/androidTest/java/com/ayvytr/easydeveloper/ExampleInstrumentedTest.java b/easyAndroidLibrary/src/androidTest/java/com/ayvytr/easyandroidlibrary/ExampleInstrumentedTest.java similarity index 94% rename from easydeveloper/src/androidTest/java/com/ayvytr/easydeveloper/ExampleInstrumentedTest.java rename to easyAndroidLibrary/src/androidTest/java/com/ayvytr/easyandroidlibrary/ExampleInstrumentedTest.java index 11f0b96..76a8b89 100644 --- a/easydeveloper/src/androidTest/java/com/ayvytr/easydeveloper/ExampleInstrumentedTest.java +++ b/easyAndroidLibrary/src/androidTest/java/com/ayvytr/easyandroidlibrary/ExampleInstrumentedTest.java @@ -1,4 +1,4 @@ -package com.ayvytr.easydeveloper; +package com.ayvytr.easyandroidlibrary; import android.content.Context; import android.support.test.InstrumentationRegistry; diff --git a/easyAndroidLibrary/src/main/AndroidManifest.xml b/easyAndroidLibrary/src/main/AndroidManifest.xml new file mode 100644 index 0000000..a7efdc5 --- /dev/null +++ b/easyAndroidLibrary/src/main/AndroidManifest.xml @@ -0,0 +1,14 @@ + + + + + + + diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/Easy.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/Easy.java similarity index 91% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/Easy.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/Easy.java index 3f22fec..1848eea 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/Easy.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/Easy.java @@ -1,98 +1,99 @@ -package com.ayvytr.easydeveloper; - -import android.app.KeyguardManager; -import android.content.ClipboardManager; -import android.content.Context; -import android.view.WindowManager; - -import com.ayvytr.easydeveloper.exception.UnInitLibraryException; - -import java.lang.ref.SoftReference; - -/** - * Created by davidwang on 2017/3/15. - * Easy:入口类,单例模式。Tools包中或者其他需要用到Context的类在使用之前, - * 需要初始化这个类 - * - * 提供了获取Context,常用SystemService等方法 - */ - -public class Easy -{ - private static Easy easy = new Easy(); - private static SoftReference contextRef; - - public static Context getContext() - { - checkInitState(); - return contextRef.get(); - } - - /** - * 检测初始化状态。Easy类暂时定为静态初始化,所以直接检测contextRef是否已初始化, - * 未初始化,直接抛出自定义异常 - */ - private static void checkInitState() - { - if(contextRef == null) - { - throw new UnInitLibraryException(); - } - } - - private Easy() - { - } - - public static Easy getDefault() - { - return easy; - } - - /** - * 初始化Context - * @param context context - */ - public void init(Context context) - { - if(context == null) - { - throw new NullPointerException("Context is null on 'init'."); - } - - this.contextRef = new SoftReference<>(context); - } - - /** - * 释放资源(可能用不到,但还是提供吧) - */ - public void release() - { - contextRef = null; - easy = null; - } - - /** - * 获取 ClipboardManager - */ - public ClipboardManager getClipboardManager() - { - return (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); - } - - /** - * 获取WindowManager - */ - public WindowManager getWindowManager() - { - return (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); - } - - /** - * 获取KeyguardManager - */ - public KeyguardManager getKeyguardManager() - { - return (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE); - } -} +package com.ayvytr.easyandroidlibrary; + +import android.app.KeyguardManager; +import android.content.ClipboardManager; +import android.content.Context; +import android.view.WindowManager; + +import com.ayvytr.easyandroidlibrary.exception.UnInitLibraryException; + +import java.lang.ref.SoftReference; + +/** + * Created by davidwang on 2017/3/15. + * Easy:入口类,单例模式。Tools包中或者其他需要用到Context的类在使用之前, + * 需要初始化这个类 + *

+ * 提供了获取Context,常用SystemService等方法 + */ + +public class Easy +{ + private static Easy easy = new Easy(); + private static SoftReference contextRef; + + public static Context getContext() + { + checkInitState(); + return contextRef.get(); + } + + /** + * 检测初始化状态。Easy类暂时定为静态初始化,所以直接检测contextRef是否已初始化, + * 未初始化,直接抛出自定义异常 + */ + private static void checkInitState() + { + if(contextRef == null) + { + throw new UnInitLibraryException(); + } + } + + private Easy() + { + } + + public static Easy getDefault() + { + return easy; + } + + /** + * 初始化Context + * + * @param context context + */ + public void init(Context context) + { + if(context == null) + { + throw new NullPointerException("Context is null on 'init'."); + } + + this.contextRef = new SoftReference<>(context); + } + + /** + * 释放资源(可能用不到,但还是提供吧) + */ + public void release() + { + contextRef = null; + easy = null; + } + + /** + * 获取 ClipboardManager + */ + public ClipboardManager getClipboardManager() + { + return (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); + } + + /** + * 获取WindowManager + */ + public WindowManager getWindowManager() + { + return (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); + } + + /** + * 获取KeyguardManager + */ + public KeyguardManager getKeyguardManager() + { + return (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE); + } +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/EasyConst.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/EasyConst.java similarity index 80% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/EasyConst.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/EasyConst.java index ba921b2..d6406d4 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/EasyConst.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/EasyConst.java @@ -1,12 +1,12 @@ -package com.ayvytr.easydeveloper.consts; - -/** - * Created by davidwang on 2017/3/15. - */ - -public class EasyConst -{ - public static final String TEXT = "text"; - public static final String Uri = "uri"; - public static final String Intent = "intent"; -} +package com.ayvytr.easyandroidlibrary.consts; + +/** + * Created by davidwang on 2017/3/15. + */ + +public class EasyConst +{ + public static final String TEXT = "text"; + public static final String Uri = "uri"; + public static final String Intent = "intent"; +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/MemoryConstant.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/MemoryConstant.java similarity index 86% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/MemoryConstant.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/MemoryConstant.java index 6715a0b..b131f63 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/MemoryConstant.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/MemoryConstant.java @@ -1,4 +1,4 @@ -package com.ayvytr.easydeveloper.consts; +package com.ayvytr.easyandroidlibrary.consts; import android.support.annotation.IntDef; @@ -13,7 +13,8 @@ * desc : 存储相关常量 * */ -public class MemoryConstant { +public class MemoryConstant +{ /** * Byte与Byte的倍数 @@ -34,6 +35,7 @@ public class MemoryConstant { @IntDef({BYTE, KB, MB, GB}) @Retention(RetentionPolicy.SOURCE) - public @interface Unit { + public @interface Unit + { } } diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/RegexConstant.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/RegexConstant.java similarity index 98% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/RegexConstant.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/RegexConstant.java index 42caaf7..853902a 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/RegexConstant.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/RegexConstant.java @@ -1,4 +1,4 @@ -package com.ayvytr.easydeveloper.consts; +package com.ayvytr.easyandroidlibrary.consts; /** *

@@ -8,7 +8,8 @@
  *     desc  : 正则相关常量
  * 
*/ -public class RegexConstant { +public class RegexConstant +{ /** * 正则:手机号(简单) diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/TimeConstant.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/TimeConstant.java similarity index 88% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/TimeConstant.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/TimeConstant.java index 9e207fd..29f0c8d 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/consts/TimeConstant.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/consts/TimeConstant.java @@ -1,4 +1,4 @@ -package com.ayvytr.easydeveloper.consts; +package com.ayvytr.easyandroidlibrary.consts; import android.support.annotation.IntDef; @@ -13,7 +13,8 @@ * desc : 时间相关常量 * */ -public class TimeConstant { +public class TimeConstant +{ /** * 秒与毫秒的倍数 @@ -39,6 +40,7 @@ public class TimeConstant { @IntDef({MSEC, SEC, MIN, HOUR, DAY}) @Retention(RetentionPolicy.SOURCE) - public @interface Unit { + public @interface Unit + { } } diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/exception/UnInitLibraryException.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/exception/UnInitLibraryException.java similarity index 83% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/exception/UnInitLibraryException.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/exception/UnInitLibraryException.java index 1fe8ab5..5ea4dc0 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/exception/UnInitLibraryException.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/exception/UnInitLibraryException.java @@ -1,19 +1,21 @@ -package com.ayvytr.easydeveloper.exception; - -/** - * Created by davidwang on 2017/3/15. - */ - -public class UnInitLibraryException extends RuntimeException -{ - public UnInitLibraryException() - { - super(UnInitLibraryException.class.getSimpleName() + - ".Before you use, " + - "you need call 'Easy.getDefault.init(Context)' " + - "on your method 'Application.onCreate()'" + - "(or any other location) to init.\n" + - "未初始化库异常,在使用之前,你需要在'Application.onCreate()'" + - "(或者其他位置)中调用'Easy.getDefault().init(Context)初始化。"); - } -} +package com.ayvytr.easyandroidlibrary.exception; + +/** + * Created by davidwang on 2017/3/15. + *

+ * 使用withcontext库中的类时,未调用 Easy类的初始化过程 + */ + +public class UnInitLibraryException extends RuntimeException +{ + public UnInitLibraryException() + { + super(UnInitLibraryException.class.getSimpleName() + + ".Before you use, " + + "you need call 'Easy.getDefault.init(Context)' " + + "on your method 'Application.onCreate()'" + + "(or any other location) to init.\n" + + "未初始化库异常,在使用之前,你需要在'Application.onCreate()'" + + "(或者其他位置)中调用'Easy.getDefault().init(Context)初始化。"); + } +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/exception/UnsupportedInitializationException.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/exception/UnsupportedInitializationException.java similarity index 51% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/exception/UnsupportedInitializationException.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/exception/UnsupportedInitializationException.java index bddd5c7..7995b7e 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/exception/UnsupportedInitializationException.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/exception/UnsupportedInitializationException.java @@ -1,14 +1,16 @@ -package com.ayvytr.easydeveloper.exception; - -/** - * Created by davidwang on 2017/3/15. - */ - -public class UnsupportedInitializationException extends RuntimeException -{ - public UnsupportedInitializationException() - { - super(UnsupportedInitializationException.class.getSimpleName() + - ".You can't initialize this class. 你不能初始化这个类"); - } -} +package com.ayvytr.easyandroidlibrary.exception; + +/** + * Created by davidwang on 2017/3/15. + *

+ * 不支持构造函数初始化操作。在不需要创建类实例的类的私有无参构造中使用 + */ + +public class UnsupportedInitializationException extends RuntimeException +{ + public UnsupportedInitializationException() + { + super(UnsupportedInitializationException.class.getSimpleName() + + ".You can't initialize this class. 你不能初始化这个类"); + } +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/ConvertTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/ConvertTool.java similarity index 95% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/ConvertTool.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/ConvertTool.java index 78f3f1d..a8b3664 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/ConvertTool.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/ConvertTool.java @@ -1,455 +1,455 @@ -package com.ayvytr.easydeveloper.tools; - -import android.annotation.SuppressLint; -import android.content.res.Resources; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.view.View; - -import com.ayvytr.easydeveloper.consts.MemoryConstant; -import com.ayvytr.easydeveloper.consts.TimeConstant; - -import java.io.ByteArrayOutputStream; - -/** - *

- *     author: Blankj
- *     blog  : http://blankj.com
- *     time  : 2016/8/13
- *     desc  : 转换相关工具类
- * 
- */ -public class ConvertTool -{ - - private ConvertTool() - { - throw new UnsupportedOperationException("u can't instantiate me..."); - } - - private static final char hexDigits[] = {'0', - '1', - '2', - '3', - '4', - '5', - '6', - '7', - '8', - '9', - 'A', - 'B', - 'C', - 'D', - 'E', - 'F'}; - - /** - * byteArr转hexString - *

例如:

- * bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns 00A8 - * - * @param bytes 字节数组 - * @return 16进制大写字符串 - */ - public static String bytes2HexString(byte[] bytes) - { - if(bytes == null) return null; - int len = bytes.length; - if(len <= 0) return null; - char[] ret = new char[len << 1]; - for(int i = 0, j = 0; i < len; i++) - { - ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f]; - ret[j++] = hexDigits[bytes[i] & 0x0f]; - } - return new String(ret); - } - - /** - * hexString转byteArr - *

例如:

- * hexString2Bytes("00A8") returns { 0, (byte) 0xA8 } - * - * @param hexString 十六进制字符串 - * @return 字节数组 - */ - public static byte[] hexString2Bytes(String hexString) - { - if(TextTool.isEmpty(hexString)) - { - return null; - } - - int len = hexString.length(); - if(len % 2 != 0) - { - hexString = "0" + hexString; - len = len + 1; - } - char[] hexBytes = hexString.toUpperCase().toCharArray(); - byte[] ret = new byte[len >> 1]; - for(int i = 0; i < len; i += 2) - { - ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1])); - } - return ret; - } - - /** - * hexChar转int - * - * @param hexChar hex单个字节 - * @return 0..15 - */ - private static int hex2Dec(char hexChar) - { - if(hexChar >= '0' && hexChar <= '9') - { - return hexChar - '0'; - } - else if(hexChar >= 'A' && hexChar <= 'F') - { - return hexChar - 'A' + 10; - } - else - { - throw new IllegalArgumentException(); - } - } - - /** - * charArr转byteArr - * - * @param chars 字符数组 - * @return 字节数组 - */ - public static byte[] chars2Bytes(char[] chars) - { - if(chars == null || chars.length <= 0) return null; - int len = chars.length; - byte[] bytes = new byte[len]; - for(int i = 0; i < len; i++) - { - bytes[i] = (byte) (chars[i]); - } - return bytes; - } - - /** - * byteArr转charArr - * - * @param bytes 字节数组 - * @return 字符数组 - */ - public static char[] bytes2Chars(byte[] bytes) - { - if(bytes == null) return null; - int len = bytes.length; - if(len <= 0) return null; - char[] chars = new char[len]; - for(int i = 0; i < len; i++) - { - chars[i] = (char) (bytes[i] & 0xff); - } - return chars; - } - - /** - * 以unit为单位的内存大小转字节数 - * - * @param memorySize 大小 - * @param unit 单位类型 - *
    - *
  • {@link MemoryConstant#BYTE}: 字节
  • - *
  • {@link MemoryConstant#KB} : 千字节
  • - *
  • {@link MemoryConstant#MB} : 兆
  • - *
  • {@link MemoryConstant#GB} : GB
  • - *
- * @return 字节数 - */ - public static long memorySize2Byte(long memorySize, @MemoryConstant.Unit int unit) - { - if(memorySize < 0) return -1; - return memorySize * unit; - } - - /** - * 字节数转以unit为单位的内存大小 - * - * @param byteNum 字节数 - * @param unit 单位类型 - *
    - *
  • {@link MemoryConstant#BYTE}: 字节
  • - *
  • {@link MemoryConstant#KB} : 千字节
  • - *
  • {@link MemoryConstant#MB} : 兆
  • - *
  • {@link MemoryConstant#GB} : GB
  • - *
- * @return 以unit为单位的size - */ - public static double byte2MemorySize(long byteNum, @MemoryConstant.Unit int unit) - { - if(byteNum < 0) return -1; - return (double) byteNum / unit; - } - - /** - * 字节数转合适内存大小 - *

保留3位小数

- * - * @param byteNum 字节数 - * @return 合适内存大小 - */ - @SuppressLint("DefaultLocale") - public static String byte2FitMemorySize(long byteNum) - { - if(byteNum < 0) - { - return "shouldn't be less than zero!"; - } - else if(byteNum < MemoryConstant.KB) - { - return String.format("%.3fB", (double) byteNum + 0.0005); - } - else if(byteNum < MemoryConstant.MB) - { - return String.format("%.3fKB", (double) byteNum / MemoryConstant.KB + 0.0005); - } - else if(byteNum < MemoryConstant.GB) - { - return String.format("%.3fMB", (double) byteNum / MemoryConstant.MB + 0.0005); - } - else - { - return String.format("%.3fGB", (double) byteNum / MemoryConstant.GB + 0.0005); - } - } - - /** - * 以unit为单位的时间长度转毫秒时间戳 - * - * @param timeSpan 毫秒时间戳 - * @param unit 单位类型 - *
    - *
  • {@link TimeConstant#MSEC}: 毫秒
  • - *
  • {@link TimeConstant#SEC }: 秒
  • - *
  • {@link TimeConstant#MIN }: 分
  • - *
  • {@link TimeConstant#HOUR}: 小时
  • - *
  • {@link TimeConstant#DAY }: 天
  • - *
- * @return 毫秒时间戳 - */ - public static long timeSpan2Millis(long timeSpan, @TimeConstant.Unit int unit) - { - return timeSpan * unit; - } - - /** - * 毫秒时间戳转以unit为单位的时间长度 - * - * @param millis 毫秒时间戳 - * @param unit 单位类型 - *
    - *
  • {@link TimeConstant#MSEC}: 毫秒
  • - *
  • {@link TimeConstant#SEC }: 秒
  • - *
  • {@link TimeConstant#MIN }: 分
  • - *
  • {@link TimeConstant#HOUR}: 小时
  • - *
  • {@link TimeConstant#DAY }: 天
  • - *
- * @return 以unit为单位的时间长度 - */ - public static long millis2TimeSpan(long millis, @TimeConstant.Unit int unit) - { - return millis / unit; - } - - /** - * 毫秒时间戳转合适时间长度 - * - * @param millis 毫秒时间戳 - *

小于等于0,返回null

- * @param precision 精度 - *
    - *
  • precision = 0,返回null
  • - *
  • precision = 1,返回天
  • - *
  • precision = 2,返回天和小时
  • - *
  • precision = 3,返回天、小时和分钟
  • - *
  • precision = 4,返回天、小时、分钟和秒
  • - *
  • precision >= 5,返回天、小时、分钟、秒和毫秒
  • - *
- * @return 合适时间长度 - */ - @SuppressLint("DefaultLocale") - public static String millis2FitTimeSpan(long millis, int precision) - { - if(millis <= 0 || precision <= 0) return null; - StringBuilder sb = new StringBuilder(); - String[] units = {"天", "小时", "分钟", "秒", "毫秒"}; - int[] unitLen = {86400000, 3600000, 60000, 1000, 1}; - precision = Math.min(precision, 5); - for(int i = 0; i < precision; i++) - { - if(millis >= unitLen[i]) - { - long mode = millis / unitLen[i]; - millis -= mode * unitLen[i]; - sb.append(mode).append(units[i]); - } - } - return sb.toString(); - } - - /** - * bytes转bits - * - * @param bytes 字节数组 - * @return bits - */ - public static String bytes2Bits(byte[] bytes) - { - StringBuilder sb = new StringBuilder(); - for(byte aByte : bytes) - { - for(int j = 7; j >= 0; --j) - { - sb.append(((aByte >> j) & 0x01) == 0 ? '0' : '1'); - } - } - return sb.toString(); - } - - /** - * bits转bytes - * - * @param bits 二进制 - * @return bytes - */ - public static byte[] bits2Bytes(String bits) - { - int lenMod = bits.length() % 8; - int byteLen = bits.length() / 8; - // 不是8的倍数前面补0 - if(lenMod != 0) - { - for(int i = lenMod; i < 8; i++) - { - bits = "0" + bits; - } - byteLen++; - } - byte[] bytes = new byte[byteLen]; - for(int i = 0; i < byteLen; ++i) - { - for(int j = 0; j < 8; ++j) - { - bytes[i] <<= 1; - bytes[i] |= bits.charAt(i * 8 + j) - '0'; - } - } - return bytes; - } - - /** - * bitmap转byteArr - * - * @param bitmap bitmap对象 - * @param format 格式 - * @return 字节数组 - */ - public static byte[] bitmap2Bytes(Bitmap bitmap, Bitmap.CompressFormat format) - { - if(bitmap == null) return null; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - bitmap.compress(format, 100, baos); - return baos.toByteArray(); - } - - /** - * byteArr转bitmap - * - * @param bytes 字节数组 - * @return bitmap - */ - public static Bitmap bytes2Bitmap(byte[] bytes) - { - return (bytes == null || bytes.length == 0) ? null : BitmapFactory - .decodeByteArray(bytes, 0, bytes.length); - } - - /** - * drawable转bitmap - * - * @param drawable drawable对象 - * @return bitmap - */ - public static Bitmap drawable2Bitmap(Drawable drawable) - { - return drawable == null ? null : ((BitmapDrawable) drawable).getBitmap(); - } - - /** - * bitmap转drawable - * - * @param res resources对象 - * @param bitmap bitmap对象 - * @return drawable - */ - public static Drawable bitmap2Drawable(Resources res, Bitmap bitmap) - { - return bitmap == null ? null : new BitmapDrawable(res, bitmap); - } - - /** - * drawable转byteArr - * - * @param drawable drawable对象 - * @param format 格式 - * @return 字节数组 - */ - public static byte[] drawable2Bytes(Drawable drawable, Bitmap.CompressFormat format) - { - return drawable == null ? null : bitmap2Bytes(drawable2Bitmap(drawable), format); - } - - /** - * byteArr转drawable - * - * @param res resources对象 - * @param bytes 字节数组 - * @return drawable - */ - public static Drawable bytes2Drawable(Resources res, byte[] bytes) - { - return res == null ? null : bitmap2Drawable(res, bytes2Bitmap(bytes)); - } - - /** - * view转Bitmap - * - * @param view 视图 - * @return bitmap - */ - public static Bitmap view2Bitmap(View view) - { - if(view == null) return null; - Bitmap ret = Bitmap - .createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(ret); - Drawable bgDrawable = view.getBackground(); - if(bgDrawable != null) - { - bgDrawable.draw(canvas); - } - else - { - canvas.drawColor(Color.WHITE); - } - view.draw(canvas); - return ret; - } - -} +package com.ayvytr.easyandroidlibrary.tools; + +import android.annotation.SuppressLint; +import android.content.res.Resources; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.view.View; + +import com.ayvytr.easyandroidlibrary.consts.MemoryConstant; +import com.ayvytr.easyandroidlibrary.consts.TimeConstant; + +import java.io.ByteArrayOutputStream; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2016/8/13
+ *     desc  : 转换相关工具类
+ * 
+ */ +public class ConvertTool +{ + + private ConvertTool() + { + throw new UnsupportedOperationException("u can't instantiate me..."); + } + + private static final char hexDigits[] = {'0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F'}; + + /** + * byteArr转hexString + *

例如:

+ * bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns 00A8 + * + * @param bytes 字节数组 + * @return 16进制大写字符串 + */ + public static String bytes2HexString(byte[] bytes) + { + if(bytes == null) return null; + int len = bytes.length; + if(len <= 0) return null; + char[] ret = new char[len << 1]; + for(int i = 0, j = 0; i < len; i++) + { + ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f]; + ret[j++] = hexDigits[bytes[i] & 0x0f]; + } + return new String(ret); + } + + /** + * hexString转byteArr + *

例如:

+ * hexString2Bytes("00A8") returns { 0, (byte) 0xA8 } + * + * @param hexString 十六进制字符串 + * @return 字节数组 + */ + public static byte[] hexString2Bytes(String hexString) + { + if(TextTool.isEmpty(hexString)) + { + return null; + } + + int len = hexString.length(); + if(len % 2 != 0) + { + hexString = "0" + hexString; + len = len + 1; + } + char[] hexBytes = hexString.toUpperCase().toCharArray(); + byte[] ret = new byte[len >> 1]; + for(int i = 0; i < len; i += 2) + { + ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1])); + } + return ret; + } + + /** + * hexChar转int + * + * @param hexChar hex单个字节 + * @return 0..15 + */ + private static int hex2Dec(char hexChar) + { + if(hexChar >= '0' && hexChar <= '9') + { + return hexChar - '0'; + } + else if(hexChar >= 'A' && hexChar <= 'F') + { + return hexChar - 'A' + 10; + } + else + { + throw new IllegalArgumentException(); + } + } + + /** + * charArr转byteArr + * + * @param chars 字符数组 + * @return 字节数组 + */ + public static byte[] chars2Bytes(char[] chars) + { + if(chars == null || chars.length <= 0) return null; + int len = chars.length; + byte[] bytes = new byte[len]; + for(int i = 0; i < len; i++) + { + bytes[i] = (byte) (chars[i]); + } + return bytes; + } + + /** + * byteArr转charArr + * + * @param bytes 字节数组 + * @return 字符数组 + */ + public static char[] bytes2Chars(byte[] bytes) + { + if(bytes == null) return null; + int len = bytes.length; + if(len <= 0) return null; + char[] chars = new char[len]; + for(int i = 0; i < len; i++) + { + chars[i] = (char) (bytes[i] & 0xff); + } + return chars; + } + + /** + * 以unit为单位的内存大小转字节数 + * + * @param memorySize 大小 + * @param unit 单位类型 + *
    + *
  • {@link MemoryConstant#BYTE}: 字节
  • + *
  • {@link MemoryConstant#KB} : 千字节
  • + *
  • {@link MemoryConstant#MB} : 兆
  • + *
  • {@link MemoryConstant#GB} : GB
  • + *
+ * @return 字节数 + */ + public static long memorySize2Byte(long memorySize, @MemoryConstant.Unit int unit) + { + if(memorySize < 0) return -1; + return memorySize * unit; + } + + /** + * 字节数转以unit为单位的内存大小 + * + * @param byteNum 字节数 + * @param unit 单位类型 + *
    + *
  • {@link MemoryConstant#BYTE}: 字节
  • + *
  • {@link MemoryConstant#KB} : 千字节
  • + *
  • {@link MemoryConstant#MB} : 兆
  • + *
  • {@link MemoryConstant#GB} : GB
  • + *
+ * @return 以unit为单位的size + */ + public static double byte2MemorySize(long byteNum, @MemoryConstant.Unit int unit) + { + if(byteNum < 0) return -1; + return (double) byteNum / unit; + } + + /** + * 字节数转合适内存大小 + *

保留3位小数

+ * + * @param byteNum 字节数 + * @return 合适内存大小 + */ + @SuppressLint("DefaultLocale") + public static String byte2FitMemorySize(long byteNum) + { + if(byteNum < 0) + { + return "shouldn't be less than zero!"; + } + else if(byteNum < MemoryConstant.KB) + { + return String.format("%.3fB", (double) byteNum + 0.0005); + } + else if(byteNum < MemoryConstant.MB) + { + return String.format("%.3fKB", (double) byteNum / MemoryConstant.KB + 0.0005); + } + else if(byteNum < MemoryConstant.GB) + { + return String.format("%.3fMB", (double) byteNum / MemoryConstant.MB + 0.0005); + } + else + { + return String.format("%.3fGB", (double) byteNum / MemoryConstant.GB + 0.0005); + } + } + + /** + * 以unit为单位的时间长度转毫秒时间戳 + * + * @param timeSpan 毫秒时间戳 + * @param unit 单位类型 + *
    + *
  • {@link TimeConstant#MSEC}: 毫秒
  • + *
  • {@link TimeConstant#SEC }: 秒
  • + *
  • {@link TimeConstant#MIN }: 分
  • + *
  • {@link TimeConstant#HOUR}: 小时
  • + *
  • {@link TimeConstant#DAY }: 天
  • + *
+ * @return 毫秒时间戳 + */ + public static long timeSpan2Millis(long timeSpan, @TimeConstant.Unit int unit) + { + return timeSpan * unit; + } + + /** + * 毫秒时间戳转以unit为单位的时间长度 + * + * @param millis 毫秒时间戳 + * @param unit 单位类型 + *
    + *
  • {@link TimeConstant#MSEC}: 毫秒
  • + *
  • {@link TimeConstant#SEC }: 秒
  • + *
  • {@link TimeConstant#MIN }: 分
  • + *
  • {@link TimeConstant#HOUR}: 小时
  • + *
  • {@link TimeConstant#DAY }: 天
  • + *
+ * @return 以unit为单位的时间长度 + */ + public static long millis2TimeSpan(long millis, @TimeConstant.Unit int unit) + { + return millis / unit; + } + + /** + * 毫秒时间戳转合适时间长度 + * + * @param millis 毫秒时间戳 + *

小于等于0,返回null

+ * @param precision 精度 + *
    + *
  • precision = 0,返回null
  • + *
  • precision = 1,返回天
  • + *
  • precision = 2,返回天和小时
  • + *
  • precision = 3,返回天、小时和分钟
  • + *
  • precision = 4,返回天、小时、分钟和秒
  • + *
  • precision >= 5,返回天、小时、分钟、秒和毫秒
  • + *
+ * @return 合适时间长度 + */ + @SuppressLint("DefaultLocale") + public static String millis2FitTimeSpan(long millis, int precision) + { + if(millis <= 0 || precision <= 0) return null; + StringBuilder sb = new StringBuilder(); + String[] units = {"天", "小时", "分钟", "秒", "毫秒"}; + int[] unitLen = {86400000, 3600000, 60000, 1000, 1}; + precision = Math.min(precision, 5); + for(int i = 0; i < precision; i++) + { + if(millis >= unitLen[i]) + { + long mode = millis / unitLen[i]; + millis -= mode * unitLen[i]; + sb.append(mode).append(units[i]); + } + } + return sb.toString(); + } + + /** + * bytes转bits + * + * @param bytes 字节数组 + * @return bits + */ + public static String bytes2Bits(byte[] bytes) + { + StringBuilder sb = new StringBuilder(); + for(byte aByte : bytes) + { + for(int j = 7; j >= 0; --j) + { + sb.append(((aByte >> j) & 0x01) == 0 ? '0' : '1'); + } + } + return sb.toString(); + } + + /** + * bits转bytes + * + * @param bits 二进制 + * @return bytes + */ + public static byte[] bits2Bytes(String bits) + { + int lenMod = bits.length() % 8; + int byteLen = bits.length() / 8; + // 不是8的倍数前面补0 + if(lenMod != 0) + { + for(int i = lenMod; i < 8; i++) + { + bits = "0" + bits; + } + byteLen++; + } + byte[] bytes = new byte[byteLen]; + for(int i = 0; i < byteLen; ++i) + { + for(int j = 0; j < 8; ++j) + { + bytes[i] <<= 1; + bytes[i] |= bits.charAt(i * 8 + j) - '0'; + } + } + return bytes; + } + + /** + * bitmap转byteArr + * + * @param bitmap bitmap对象 + * @param format 格式 + * @return 字节数组 + */ + public static byte[] bitmap2Bytes(Bitmap bitmap, Bitmap.CompressFormat format) + { + if(bitmap == null) return null; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + bitmap.compress(format, 100, baos); + return baos.toByteArray(); + } + + /** + * byteArr转bitmap + * + * @param bytes 字节数组 + * @return bitmap + */ + public static Bitmap bytes2Bitmap(byte[] bytes) + { + return (bytes == null || bytes.length == 0) ? null : BitmapFactory + .decodeByteArray(bytes, 0, bytes.length); + } + + /** + * drawable转bitmap + * + * @param drawable drawable对象 + * @return bitmap + */ + public static Bitmap drawable2Bitmap(Drawable drawable) + { + return drawable == null ? null : ((BitmapDrawable) drawable).getBitmap(); + } + + /** + * bitmap转drawable + * + * @param res resources对象 + * @param bitmap bitmap对象 + * @return drawable + */ + public static Drawable bitmap2Drawable(Resources res, Bitmap bitmap) + { + return bitmap == null ? null : new BitmapDrawable(res, bitmap); + } + + /** + * drawable转byteArr + * + * @param drawable drawable对象 + * @param format 格式 + * @return 字节数组 + */ + public static byte[] drawable2Bytes(Drawable drawable, Bitmap.CompressFormat format) + { + return drawable == null ? null : bitmap2Bytes(drawable2Bitmap(drawable), format); + } + + /** + * byteArr转drawable + * + * @param res resources对象 + * @param bytes 字节数组 + * @return drawable + */ + public static Drawable bytes2Drawable(Resources res, byte[] bytes) + { + return res == null ? null : bitmap2Drawable(res, bytes2Bitmap(bytes)); + } + + /** + * view转Bitmap + * + * @param view 视图 + * @return bitmap + */ + public static Bitmap view2Bitmap(View view) + { + if(view == null) return null; + Bitmap ret = Bitmap + .createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(ret); + Drawable bgDrawable = view.getBackground(); + if(bgDrawable != null) + { + bgDrawable.draw(canvas); + } + else + { + canvas.drawColor(Color.WHITE); + } + view.draw(canvas); + return ret; + } + +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/EncodeUtils.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/EncodeTool.java similarity index 70% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/EncodeUtils.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/EncodeTool.java index 9ffbef4..6f7c815 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/EncodeUtils.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/EncodeTool.java @@ -1,199 +1,240 @@ -package com.ayvytr.easydeveloper.tools; - -import android.os.Build; -import android.text.Html; -import android.util.Base64; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; - -/** - *
- *     author: Blankj
- *     blog  : http://blankj.com
- *     time  : 2016/8/7
- *     desc  : 编码解码相关工具类
- * 
- */ -public class EncodeUtils { - - private EncodeUtils() { - throw new UnsupportedOperationException("u can't instantiate me..."); - } - - /** - * URL编码 - *

若想自己指定字符集,可以使用{@link #urlEncode(String input, String charset)}方法

- * - * @param input 要编码的字符 - * @return 编码为UTF-8的字符串 - */ - public static String urlEncode(String input) { - return urlEncode(input, "UTF-8"); - } - - /** - * URL编码 - *

若系统不支持指定的编码字符集,则直接将input原样返回

- * - * @param input 要编码的字符 - * @param charset 字符集 - * @return 编码为字符集的字符串 - */ - public static String urlEncode(String input, String charset) { - try { - return URLEncoder.encode(input, charset); - } catch (UnsupportedEncodingException e) { - return input; - } - } - - /** - * URL解码 - *

若想自己指定字符集,可以使用 {@link #urlDecode(String input, String charset)}方法

- * - * @param input 要解码的字符串 - * @return URL解码后的字符串 - */ - public static String urlDecode(String input) { - return urlDecode(input, "UTF-8"); - } - - /** - * URL解码 - *

若系统不支持指定的解码字符集,则直接将input原样返回

- * - * @param input 要解码的字符串 - * @param charset 字符集 - * @return URL解码为指定字符集的字符串 - */ - public static String urlDecode(String input, String charset) { - try { - return URLDecoder.decode(input, charset); - } catch (UnsupportedEncodingException e) { - return input; - } - } - - /** - * Base64编码 - * - * @param input 要编码的字符串 - * @return Base64编码后的字符串 - */ - public static byte[] base64Encode(String input) { - return base64Encode(input.getBytes()); - } - - /** - * Base64编码 - * - * @param input 要编码的字节数组 - * @return Base64编码后的字符串 - */ - public static byte[] base64Encode(byte[] input) { - return Base64.encode(input, Base64.NO_WRAP); - } - - /** - * Base64编码 - * - * @param input 要编码的字节数组 - * @return Base64编码后的字符串 - */ - public static String base64Encode2String(byte[] input) { - return Base64.encodeToString(input, Base64.NO_WRAP); - } - - /** - * Base64解码 - * - * @param input 要解码的字符串 - * @return Base64解码后的字符串 - */ - public static byte[] base64Decode(String input) { - return Base64.decode(input, Base64.NO_WRAP); - } - - /** - * Base64解码 - * - * @param input 要解码的字符串 - * @return Base64解码后的字符串 - */ - public static byte[] base64Decode(byte[] input) { - return Base64.decode(input, Base64.NO_WRAP); - } - - /** - * Base64URL安全编码 - *

将Base64中的URL非法字符�?,/=转为其他字符, 见RFC3548

- * - * @param input 要Base64URL安全编码的字符串 - * @return Base64URL安全编码后的字符串 - */ - public static byte[] base64UrlSafeEncode(String input) { - return Base64.encode(input.getBytes(), Base64.URL_SAFE); - } - - /** - * Html编码 - * - * @param input 要Html编码的字符串 - * @return Html编码后的字符串 - */ - public static String htmlEncode(CharSequence input) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - return Html.escapeHtml(input); - } else { - // 参照Html.escapeHtml()中代码 - StringBuilder out = new StringBuilder(); - for (int i = 0, len = input.length(); i < len; i++) { - char c = input.charAt(i); - if (c == '<') { - out.append("<"); - } else if (c == '>') { - out.append(">"); - } else if (c == '&') { - out.append("&"); - } else if (c >= 0xD800 && c <= 0xDFFF) { - if (c < 0xDC00 && i + 1 < len) { - char d = input.charAt(i + 1); - if (d >= 0xDC00 && d <= 0xDFFF) { - i++; - int codepoint = 0x010000 | (int) c - 0xD800 << 10 | (int) d - 0xDC00; - out.append("&#").append(codepoint).append(";"); - } - } - } else if (c > 0x7E || c < ' ') { - out.append("&#").append((int) c).append(";"); - } else if (c == ' ') { - while (i + 1 < len && input.charAt(i + 1) == ' ') { - out.append(" "); - i++; - } - out.append(' '); - } else { - out.append(c); - } - } - return out.toString(); - } - } - - /** - * Html解码 - * - * @param input 待解码的字符串 - * @return Html解码后的字符串 - */ - @SuppressWarnings("deprecation") - public static CharSequence htmlDecode(String input) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - return Html.fromHtml(input, Html.FROM_HTML_MODE_LEGACY); - } else { - return Html.fromHtml(input); - } - } -} +package com.ayvytr.easyandroidlibrary.tools; + +import android.os.Build; +import android.text.Html; +import android.util.Base64; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2016/8/7
+ *     desc  : 编码解码相关工具类
+ * 
+ */ +public class EncodeTool +{ + + private EncodeTool() + { + throw new UnsupportedOperationException("u can't instantiate me..."); + } + + /** + * URL编码 + *

若想自己指定字符集,可以使用{@link #urlEncode(String input, String charset)}方法

+ * + * @param input 要编码的字符 + * @return 编码为UTF-8的字符串 + */ + public static String urlEncode(String input) + { + return urlEncode(input, "UTF-8"); + } + + /** + * URL编码 + *

若系统不支持指定的编码字符集,则直接将input原样返回

+ * + * @param input 要编码的字符 + * @param charset 字符集 + * @return 编码为字符集的字符串 + */ + public static String urlEncode(String input, String charset) + { + try + { + return URLEncoder.encode(input, charset); + } catch(UnsupportedEncodingException e) + { + return input; + } + } + + /** + * URL解码 + *

若想自己指定字符集,可以使用 {@link #urlDecode(String input, String charset)}方法

+ * + * @param input 要解码的字符串 + * @return URL解码后的字符串 + */ + public static String urlDecode(String input) + { + return urlDecode(input, "UTF-8"); + } + + /** + * URL解码 + *

若系统不支持指定的解码字符集,则直接将input原样返回

+ * + * @param input 要解码的字符串 + * @param charset 字符集 + * @return URL解码为指定字符集的字符串 + */ + public static String urlDecode(String input, String charset) + { + try + { + return URLDecoder.decode(input, charset); + } catch(UnsupportedEncodingException e) + { + return input; + } + } + + /** + * Base64编码 + * + * @param input 要编码的字符串 + * @return Base64编码后的字符串 + */ + public static byte[] base64Encode(String input) + { + return base64Encode(input.getBytes()); + } + + /** + * Base64编码 + * + * @param input 要编码的字节数组 + * @return Base64编码后的字符串 + */ + public static byte[] base64Encode(byte[] input) + { + return Base64.encode(input, Base64.NO_WRAP); + } + + /** + * Base64编码 + * + * @param input 要编码的字节数组 + * @return Base64编码后的字符串 + */ + public static String base64Encode2String(byte[] input) + { + return Base64.encodeToString(input, Base64.NO_WRAP); + } + + /** + * Base64解码 + * + * @param input 要解码的字符串 + * @return Base64解码后的字符串 + */ + public static byte[] base64Decode(String input) + { + return Base64.decode(input, Base64.NO_WRAP); + } + + /** + * Base64解码 + * + * @param input 要解码的字符串 + * @return Base64解码后的字符串 + */ + public static byte[] base64Decode(byte[] input) + { + return Base64.decode(input, Base64.NO_WRAP); + } + + /** + * Base64URL安全编码 + *

将Base64中的URL非法字符�?,/=转为其他字符, 见RFC3548

+ * + * @param input 要Base64URL安全编码的字符串 + * @return Base64URL安全编码后的字符串 + */ + public static byte[] base64UrlSafeEncode(String input) + { + return Base64.encode(input.getBytes(), Base64.URL_SAFE); + } + + /** + * Html编码 + * + * @param input 要Html编码的字符串 + * @return Html编码后的字符串 + */ + public static String htmlEncode(CharSequence input) + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) + { + return Html.escapeHtml(input); + } + else + { + // 参照Html.escapeHtml()中代码 + StringBuilder out = new StringBuilder(); + for(int i = 0, len = input.length(); i < len; i++) + { + char c = input.charAt(i); + if(c == '<') + { + out.append("<"); + } + else if(c == '>') + { + out.append(">"); + } + else if(c == '&') + { + out.append("&"); + } + else if(c >= 0xD800 && c <= 0xDFFF) + { + if(c < 0xDC00 && i + 1 < len) + { + char d = input.charAt(i + 1); + if(d >= 0xDC00 && d <= 0xDFFF) + { + i++; + int codepoint = 0x010000 | (int) c - 0xD800 << 10 | (int) d - 0xDC00; + out.append("&#").append(codepoint).append(";"); + } + } + } + else if(c > 0x7E || c < ' ') + { + out.append("&#").append((int) c).append(";"); + } + else if(c == ' ') + { + while(i + 1 < len && input.charAt(i + 1) == ' ') + { + out.append(" "); + i++; + } + out.append(' '); + } + else + { + out.append(c); + } + } + return out.toString(); + } + } + + /** + * Html解码 + * + * @param input 待解码的字符串 + * @return Html解码后的字符串 + */ + @SuppressWarnings("deprecation") + public static CharSequence htmlDecode(String input) + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) + { + return Html.fromHtml(input, Html.FROM_HTML_MODE_LEGACY); + } + else + { + return Html.fromHtml(input); + } + } +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/EncryptUtils.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/EncryptTool.java similarity index 95% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/EncryptUtils.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/EncryptTool.java index 5a75d7f..971c41e 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/EncryptUtils.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/EncryptTool.java @@ -1,941 +1,941 @@ -package com.ayvytr.easydeveloper.tools; - -import android.util.Base64; - -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; - -import javax.crypto.Cipher; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -/** - *
- *     author: Blankj
- *     blog  : http://blankj.com
- *     time  : 2016/8/2
- *     desc  : 加密解密相关的工具类
- * 
- */ -public class EncryptUtils -{ - - private EncryptUtils() - { - throw new UnsupportedOperationException("u can't instantiate me..."); - } - - /*********************** 哈希加密相关 ***********************/ - /** - * MD2加密 - * - * @param data 明文字符串 - * @return 16进制密文 - */ - public static String encryptMD2ToString(String data) - { - return encryptMD2ToString(data.getBytes()); - } - - /** - * MD2加密 - * - * @param data 明文字节数组 - * @return 16进制密文 - */ - public static String encryptMD2ToString(byte[] data) - { - return bytes2HexString(encryptMD2(data)); - } - - /** - * MD2加密 - * - * @param data 明文字节数组 - * @return 密文字节数组 - */ - public static byte[] encryptMD2(byte[] data) - { - return hashTemplate(data, "MD2"); - } - - /** - * MD5加密 - * - * @param data 明文字符串 - * @return 16进制密文 - */ - public static String encryptMD5ToString(String data) - { - return encryptMD5ToString(data.getBytes()); - } - - /** - * MD5加密 - * - * @param data 明文字符串 - * @param salt 盐 - * @return 16进制加盐密文 - */ - public static String encryptMD5ToString(String data, String salt) - { - return bytes2HexString(encryptMD5((data + salt).getBytes())); - } - - /** - * MD5加密 - * - * @param data 明文字节数组 - * @return 16进制密文 - */ - public static String encryptMD5ToString(byte[] data) - { - return bytes2HexString(encryptMD5(data)); - } - - /** - * MD5加密 - * - * @param data 明文字节数组 - * @param salt 盐字节数组 - * @return 16进制加盐密文 - */ - public static String encryptMD5ToString(byte[] data, byte[] salt) - { - if(data == null || salt == null) return null; - byte[] dataSalt = new byte[data.length + salt.length]; - System.arraycopy(data, 0, dataSalt, 0, data.length); - System.arraycopy(salt, 0, dataSalt, data.length, salt.length); - return bytes2HexString(encryptMD5(dataSalt)); - } - - /** - * MD5加密 - * - * @param data 明文字节数组 - * @return 密文字节数组 - */ - public static byte[] encryptMD5(byte[] data) - { - return hashTemplate(data, "MD5"); - } - - /** - * SHA1加密 - * - * @param data 明文字符串 - * @return 16进制密文 - */ - public static String encryptSHA1ToString(String data) - { - return encryptSHA1ToString(data.getBytes()); - } - - /** - * SHA1加密 - * - * @param data 明文字节数组 - * @return 16进制密文 - */ - public static String encryptSHA1ToString(byte[] data) - { - return bytes2HexString(encryptSHA1(data)); - } - - /** - * SHA1加密 - * - * @param data 明文字节数组 - * @return 密文字节数组 - */ - public static byte[] encryptSHA1(byte[] data) - { - return hashTemplate(data, "SHA1"); - } - - /** - * SHA224加密 - * - * @param data 明文字符串 - * @return 16进制密文 - */ - public static String encryptSHA224ToString(String data) - { - return encryptSHA224ToString(data.getBytes()); - } - - /** - * SHA224加密 - * - * @param data 明文字节数组 - * @return 16进制密文 - */ - public static String encryptSHA224ToString(byte[] data) - { - return bytes2HexString(encryptSHA224(data)); - } - - /** - * SHA224加密 - * - * @param data 明文字节数组 - * @return 密文字节数组 - */ - public static byte[] encryptSHA224(byte[] data) - { - return hashTemplate(data, "SHA224"); - } - - /** - * SHA256加密 - * - * @param data 明文字符串 - * @return 16进制密文 - */ - public static String encryptSHA256ToString(String data) - { - return encryptSHA256ToString(data.getBytes()); - } - - /** - * SHA256加密 - * - * @param data 明文字节数组 - * @return 16进制密文 - */ - public static String encryptSHA256ToString(byte[] data) - { - return bytes2HexString(encryptSHA256(data)); - } - - /** - * SHA256加密 - * - * @param data 明文字节数组 - * @return 密文字节数组 - */ - public static byte[] encryptSHA256(byte[] data) - { - return hashTemplate(data, "SHA256"); - } - - /** - * SHA384加密 - * - * @param data 明文字符串 - * @return 16进制密文 - */ - public static String encryptSHA384ToString(String data) - { - return encryptSHA384ToString(data.getBytes()); - } - - /** - * SHA384加密 - * - * @param data 明文字节数组 - * @return 16进制密文 - */ - public static String encryptSHA384ToString(byte[] data) - { - return bytes2HexString(encryptSHA384(data)); - } - - /** - * SHA384加密 - * - * @param data 明文字节数组 - * @return 密文字节数组 - */ - public static byte[] encryptSHA384(byte[] data) - { - return hashTemplate(data, "SHA384"); - } - - /** - * SHA512加密 - * - * @param data 明文字符串 - * @return 16进制密文 - */ - public static String encryptSHA512ToString(String data) - { - return encryptSHA512ToString(data.getBytes()); - } - - /** - * SHA512加密 - * - * @param data 明文字节数组 - * @return 16进制密文 - */ - public static String encryptSHA512ToString(byte[] data) - { - return bytes2HexString(encryptSHA512(data)); - } - - /** - * SHA512加密 - * - * @param data 明文字节数组 - * @return 密文字节数组 - */ - public static byte[] encryptSHA512(byte[] data) - { - return hashTemplate(data, "SHA512"); - } - - /** - * hash加密模板 - * - * @param data 数据 - * @param algorithm 加密算法 - * @return 密文字节数组 - */ - private static byte[] hashTemplate(byte[] data, String algorithm) - { - if(data == null || data.length <= 0) return null; - try - { - MessageDigest md = MessageDigest.getInstance(algorithm); - md.update(data); - return md.digest(); - } catch(NoSuchAlgorithmException e) - { - e.printStackTrace(); - return null; - } - } - - /** - * HmacMD5加密 - * - * @param data 明文字符串 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacMD5ToString(String data, String key) - { - return encryptHmacMD5ToString(data.getBytes(), key.getBytes()); - } - - /** - * HmacMD5加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacMD5ToString(byte[] data, byte[] key) - { - return bytes2HexString(encryptHmacMD5(data, key)); - } - - /** - * HmacMD5加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 密文字节数组 - */ - public static byte[] encryptHmacMD5(byte[] data, byte[] key) - { - return hmacTemplate(data, key, "HmacMD5"); - } - - /** - * HmacSHA1加密 - * - * @param data 明文字符串 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacSHA1ToString(String data, String key) - { - return encryptHmacSHA1ToString(data.getBytes(), key.getBytes()); - } - - /** - * HmacSHA1加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacSHA1ToString(byte[] data, byte[] key) - { - return bytes2HexString(encryptHmacSHA1(data, key)); - } - - /** - * HmacSHA1加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 密文字节数组 - */ - public static byte[] encryptHmacSHA1(byte[] data, byte[] key) - { - return hmacTemplate(data, key, "HmacSHA1"); - } - - /** - * HmacSHA224加密 - * - * @param data 明文字符串 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacSHA224ToString(String data, String key) - { - return encryptHmacSHA224ToString(data.getBytes(), key.getBytes()); - } - - /** - * HmacSHA224加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacSHA224ToString(byte[] data, byte[] key) - { - return bytes2HexString(encryptHmacSHA224(data, key)); - } - - /** - * HmacSHA224加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 密文字节数组 - */ - public static byte[] encryptHmacSHA224(byte[] data, byte[] key) - { - return hmacTemplate(data, key, "HmacSHA224"); - } - - /** - * HmacSHA256加密 - * - * @param data 明文字符串 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacSHA256ToString(String data, String key) - { - return encryptHmacSHA256ToString(data.getBytes(), key.getBytes()); - } - - /** - * HmacSHA256加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacSHA256ToString(byte[] data, byte[] key) - { - return bytes2HexString(encryptHmacSHA256(data, key)); - } - - /** - * HmacSHA256加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 密文字节数组 - */ - public static byte[] encryptHmacSHA256(byte[] data, byte[] key) - { - return hmacTemplate(data, key, "HmacSHA256"); - } - - /** - * HmacSHA384加密 - * - * @param data 明文字符串 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacSHA384ToString(String data, String key) - { - return encryptHmacSHA384ToString(data.getBytes(), key.getBytes()); - } - - /** - * HmacSHA384加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacSHA384ToString(byte[] data, byte[] key) - { - return bytes2HexString(encryptHmacSHA384(data, key)); - } - - /** - * HmacSHA384加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 密文字节数组 - */ - public static byte[] encryptHmacSHA384(byte[] data, byte[] key) - { - return hmacTemplate(data, key, "HmacSHA384"); - } - - /** - * HmacSHA512加密 - * - * @param data 明文字符串 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacSHA512ToString(String data, String key) - { - return encryptHmacSHA512ToString(data.getBytes(), key.getBytes()); - } - - /** - * HmacSHA512加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 16进制密文 - */ - public static String encryptHmacSHA512ToString(byte[] data, byte[] key) - { - return bytes2HexString(encryptHmacSHA512(data, key)); - } - - /** - * HmacSHA512加密 - * - * @param data 明文字节数组 - * @param key 秘钥 - * @return 密文字节数组 - */ - public static byte[] encryptHmacSHA512(byte[] data, byte[] key) - { - return hmacTemplate(data, key, "HmacSHA512"); - } - - /** - * Hmac加密模板 - * - * @param data 数据 - * @param key 秘钥 - * @param algorithm 加密算法 - * @return 密文字节数组 - */ - private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) - { - if(data == null || data.length == 0 || key == null || key.length == 0) return null; - try - { - SecretKeySpec secretKey = new SecretKeySpec(key, algorithm); - Mac mac = Mac.getInstance(algorithm); - mac.init(secretKey); - return mac.doFinal(data); - } catch(InvalidKeyException | NoSuchAlgorithmException e) - { - e.printStackTrace(); - return null; - } - } - - /************************ DES加密相关 ***********************/ - /** - * DES转变 - *

法算法名称/加密模式/填充方式

- *

加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB

- *

填充方式有:NoPadding、ZerosPadding、PKCS5Padding

- */ - public static String DES_Transformation = "DES/ECB/NoPadding"; - private static final String DES_Algorithm = "DES"; - - /** - * DES加密后转为Base64编码 - * - * @param data 明文 - * @param key 8字节秘钥 - * @return Base64密文 - */ - public static byte[] encryptDES2Base64(byte[] data, byte[] key) - { - return base64Encode(encryptDES(data, key)); - } - - /** - * DES加密后转为16进制 - * - * @param data 明文 - * @param key 8字节秘钥 - * @return 16进制密文 - */ - public static String encryptDES2HexString(byte[] data, byte[] key) - { - return bytes2HexString(encryptDES(data, key)); - } - - /** - * DES加密 - * - * @param data 明文 - * @param key 8字节秘钥 - * @return 密文 - */ - public static byte[] encryptDES(byte[] data, byte[] key) - { - return desTemplate(data, key, DES_Algorithm, DES_Transformation, true); - } - - /** - * DES解密Base64编码密文 - * - * @param data Base64编码密文 - * @param key 8字节秘钥 - * @return 明文 - */ - public static byte[] decryptBase64DES(byte[] data, byte[] key) - { - return decryptDES(base64Decode(data), key); - } - - /** - * DES解密16进制密文 - * - * @param data 16进制密文 - * @param key 8字节秘钥 - * @return 明文 - */ - public static byte[] decryptHexStringDES(String data, byte[] key) - { - return decryptDES(hexString2Bytes(data), key); - } - - /** - * DES解密 - * - * @param data 密文 - * @param key 8字节秘钥 - * @return 明文 - */ - public static byte[] decryptDES(byte[] data, byte[] key) - { - return desTemplate(data, key, DES_Algorithm, DES_Transformation, false); - } - - /************************ 3DES加密相关 ***********************/ - /** - * 3DES转变 - *

法算法名称/加密模式/填充方式

- *

加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB

- *

填充方式有:NoPadding、ZerosPadding、PKCS5Padding

- */ - public static String TripleDES_Transformation = "DESede/ECB/NoPadding"; - private static final String TripleDES_Algorithm = "DESede"; - - - /** - * 3DES加密后转为Base64编码 - * - * @param data 明文 - * @param key 24字节秘钥 - * @return Base64密文 - */ - public static byte[] encrypt3DES2Base64(byte[] data, byte[] key) - { - return base64Encode(encrypt3DES(data, key)); - } - - /** - * 3DES加密后转为16进制 - * - * @param data 明文 - * @param key 24字节秘钥 - * @return 16进制密文 - */ - public static String encrypt3DES2HexString(byte[] data, byte[] key) - { - return bytes2HexString(encrypt3DES(data, key)); - } - - /** - * 3DES加密 - * - * @param data 明文 - * @param key 24字节密钥 - * @return 密文 - */ - public static byte[] encrypt3DES(byte[] data, byte[] key) - { - return desTemplate(data, key, TripleDES_Algorithm, TripleDES_Transformation, true); - } - - /** - * 3DES解密Base64编码密文 - * - * @param data Base64编码密文 - * @param key 24字节秘钥 - * @return 明文 - */ - public static byte[] decryptBase64_3DES(byte[] data, byte[] key) - { - return decrypt3DES(base64Decode(data), key); - } - - /** - * 3DES解密16进制密文 - * - * @param data 16进制密文 - * @param key 24字节秘钥 - * @return 明文 - */ - public static byte[] decryptHexString3DES(String data, byte[] key) - { - return decrypt3DES(hexString2Bytes(data), key); - } - - /** - * 3DES解密 - * - * @param data 密文 - * @param key 24字节密钥 - * @return 明文 - */ - public static byte[] decrypt3DES(byte[] data, byte[] key) - { - return desTemplate(data, key, TripleDES_Algorithm, TripleDES_Transformation, false); - } - - /************************ AES加密相关 ***********************/ - /** - * AES转变 - *

法算法名称/加密模式/填充方式

- *

加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB

- *

填充方式有:NoPadding、ZerosPadding、PKCS5Padding

- */ - public static String AES_Transformation = "AES/ECB/NoPadding"; - private static final String AES_Algorithm = "AES"; - - - /** - * AES加密后转为Base64编码 - * - * @param data 明文 - * @param key 16、24、32字节秘钥 - * @return Base64密文 - */ - public static byte[] encryptAES2Base64(byte[] data, byte[] key) - { - return base64Encode(encryptAES(data, key)); - } - - /** - * AES加密后转为16进制 - * - * @param data 明文 - * @param key 16、24、32字节秘钥 - * @return 16进制密文 - */ - public static String encryptAES2HexString(byte[] data, byte[] key) - { - return bytes2HexString(encryptAES(data, key)); - } - - /** - * AES加密 - * - * @param data 明文 - * @param key 16、24、32字节秘钥 - * @return 密文 - */ - public static byte[] encryptAES(byte[] data, byte[] key) - { - return desTemplate(data, key, AES_Algorithm, AES_Transformation, true); - } - - /** - * AES解密Base64编码密文 - * - * @param data Base64编码密文 - * @param key 16、24、32字节秘钥 - * @return 明文 - */ - public static byte[] decryptBase64AES(byte[] data, byte[] key) - { - return decryptAES(base64Decode(data), key); - } - - /** - * AES解密16进制密文 - * - * @param data 16进制密文 - * @param key 16、24、32字节秘钥 - * @return 明文 - */ - public static byte[] decryptHexStringAES(String data, byte[] key) - { - return decryptAES(hexString2Bytes(data), key); - } - - /** - * AES解密 - * - * @param data 密文 - * @param key 16、24、32字节秘钥 - * @return 明文 - */ - public static byte[] decryptAES(byte[] data, byte[] key) - { - return desTemplate(data, key, AES_Algorithm, AES_Transformation, false); - } - - /** - * DES加密模板 - * - * @param data 数据 - * @param key 秘钥 - * @param algorithm 加密算法 - * @param transformation 转变 - * @param isEncrypt {@code true}: 加密 {@code false}: 解密 - * @return 密文或者明文,适用于DES,3DES,AES - */ - public static byte[] desTemplate(byte[] data, byte[] key, String algorithm, - String transformation, boolean isEncrypt) - { - if(data == null || data.length == 0 || key == null || key.length == 0) return null; - try - { - SecretKeySpec keySpec = new SecretKeySpec(key, algorithm); - Cipher cipher = Cipher.getInstance(transformation); - SecureRandom random = new SecureRandom(); - cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, keySpec, random); - return cipher.doFinal(data); - } catch(Throwable e) - { - e.printStackTrace(); - return null; - } - } - - private static final char hexDigits[] = {'0', - '1', - '2', - '3', - '4', - '5', - '6', - '7', - '8', - '9', - 'A', - 'B', - 'C', - 'D', - 'E', - 'F'}; - - /** - * byteArr转hexString - *

例如:

- * bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns 00A8 - * - * @param bytes 字节数组 - * @return 16进制大写字符串 - */ - private static String bytes2HexString(byte[] bytes) - { - if(bytes == null) return null; - int len = bytes.length; - if(len <= 0) return null; - char[] ret = new char[len << 1]; - for(int i = 0, j = 0; i < len; i++) - { - ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f]; - ret[j++] = hexDigits[bytes[i] & 0x0f]; - } - return new String(ret); - } - - - /** - * hexString转byteArr - *

例如:

- * hexString2Bytes("00A8") returns { 0, (byte) 0xA8 } - * - * @param hexString 十六进制字符串 - * @return 字节数组 - */ - private static byte[] hexString2Bytes(String hexString) - { - if(TextTool.isEmpty(hexString)) - { - return null; - } - - int len = hexString.length(); - if(len % 2 != 0) - { - hexString = "0" + hexString; - len = len + 1; - } - char[] hexBytes = hexString.toUpperCase().toCharArray(); - byte[] ret = new byte[len >> 1]; - for(int i = 0; i < len; i += 2) - { - ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1])); - } - return ret; - } - - /** - * hexChar转int - * - * @param hexChar hex单个字节 - * @return 0..15 - */ - private static int hex2Dec(char hexChar) - { - if(hexChar >= '0' && hexChar <= '9') - { - return hexChar - '0'; - } - else if(hexChar >= 'A' && hexChar <= 'F') - { - return hexChar - 'A' + 10; - } - else - { - throw new IllegalArgumentException(); - } - } - - /** - * Base64编码 - * - * @param input 要编码的字节数组 - * @return Base64编码后的字符串 - */ - private static byte[] base64Encode(byte[] input) - { - return Base64.encode(input, Base64.NO_WRAP); - } - - /** - * Base64解码 - * - * @param input 要解码的字符串 - * @return Base64解码后的字符串 - */ - private static byte[] base64Decode(byte[] input) - { - return Base64.decode(input, Base64.NO_WRAP); - } +package com.ayvytr.easyandroidlibrary.tools; + +import android.util.Base64; + +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2016/8/2
+ *     desc  : 加密解密相关的工具类
+ * 
+ */ +public class EncryptTool +{ + + private EncryptTool() + { + throw new UnsupportedOperationException("u can't instantiate me..."); + } + + /*********************** 哈希加密相关 ***********************/ + /** + * MD2加密 + * + * @param data 明文字符串 + * @return 16进制密文 + */ + public static String encryptMD2ToString(String data) + { + return encryptMD2ToString(data.getBytes()); + } + + /** + * MD2加密 + * + * @param data 明文字节数组 + * @return 16进制密文 + */ + public static String encryptMD2ToString(byte[] data) + { + return bytes2HexString(encryptMD2(data)); + } + + /** + * MD2加密 + * + * @param data 明文字节数组 + * @return 密文字节数组 + */ + public static byte[] encryptMD2(byte[] data) + { + return hashTemplate(data, "MD2"); + } + + /** + * MD5加密 + * + * @param data 明文字符串 + * @return 16进制密文 + */ + public static String encryptMD5ToString(String data) + { + return encryptMD5ToString(data.getBytes()); + } + + /** + * MD5加密 + * + * @param data 明文字符串 + * @param salt 盐 + * @return 16进制加盐密文 + */ + public static String encryptMD5ToString(String data, String salt) + { + return bytes2HexString(encryptMD5((data + salt).getBytes())); + } + + /** + * MD5加密 + * + * @param data 明文字节数组 + * @return 16进制密文 + */ + public static String encryptMD5ToString(byte[] data) + { + return bytes2HexString(encryptMD5(data)); + } + + /** + * MD5加密 + * + * @param data 明文字节数组 + * @param salt 盐字节数组 + * @return 16进制加盐密文 + */ + public static String encryptMD5ToString(byte[] data, byte[] salt) + { + if(data == null || salt == null) return null; + byte[] dataSalt = new byte[data.length + salt.length]; + System.arraycopy(data, 0, dataSalt, 0, data.length); + System.arraycopy(salt, 0, dataSalt, data.length, salt.length); + return bytes2HexString(encryptMD5(dataSalt)); + } + + /** + * MD5加密 + * + * @param data 明文字节数组 + * @return 密文字节数组 + */ + public static byte[] encryptMD5(byte[] data) + { + return hashTemplate(data, "MD5"); + } + + /** + * SHA1加密 + * + * @param data 明文字符串 + * @return 16进制密文 + */ + public static String encryptSHA1ToString(String data) + { + return encryptSHA1ToString(data.getBytes()); + } + + /** + * SHA1加密 + * + * @param data 明文字节数组 + * @return 16进制密文 + */ + public static String encryptSHA1ToString(byte[] data) + { + return bytes2HexString(encryptSHA1(data)); + } + + /** + * SHA1加密 + * + * @param data 明文字节数组 + * @return 密文字节数组 + */ + public static byte[] encryptSHA1(byte[] data) + { + return hashTemplate(data, "SHA1"); + } + + /** + * SHA224加密 + * + * @param data 明文字符串 + * @return 16进制密文 + */ + public static String encryptSHA224ToString(String data) + { + return encryptSHA224ToString(data.getBytes()); + } + + /** + * SHA224加密 + * + * @param data 明文字节数组 + * @return 16进制密文 + */ + public static String encryptSHA224ToString(byte[] data) + { + return bytes2HexString(encryptSHA224(data)); + } + + /** + * SHA224加密 + * + * @param data 明文字节数组 + * @return 密文字节数组 + */ + public static byte[] encryptSHA224(byte[] data) + { + return hashTemplate(data, "SHA224"); + } + + /** + * SHA256加密 + * + * @param data 明文字符串 + * @return 16进制密文 + */ + public static String encryptSHA256ToString(String data) + { + return encryptSHA256ToString(data.getBytes()); + } + + /** + * SHA256加密 + * + * @param data 明文字节数组 + * @return 16进制密文 + */ + public static String encryptSHA256ToString(byte[] data) + { + return bytes2HexString(encryptSHA256(data)); + } + + /** + * SHA256加密 + * + * @param data 明文字节数组 + * @return 密文字节数组 + */ + public static byte[] encryptSHA256(byte[] data) + { + return hashTemplate(data, "SHA256"); + } + + /** + * SHA384加密 + * + * @param data 明文字符串 + * @return 16进制密文 + */ + public static String encryptSHA384ToString(String data) + { + return encryptSHA384ToString(data.getBytes()); + } + + /** + * SHA384加密 + * + * @param data 明文字节数组 + * @return 16进制密文 + */ + public static String encryptSHA384ToString(byte[] data) + { + return bytes2HexString(encryptSHA384(data)); + } + + /** + * SHA384加密 + * + * @param data 明文字节数组 + * @return 密文字节数组 + */ + public static byte[] encryptSHA384(byte[] data) + { + return hashTemplate(data, "SHA384"); + } + + /** + * SHA512加密 + * + * @param data 明文字符串 + * @return 16进制密文 + */ + public static String encryptSHA512ToString(String data) + { + return encryptSHA512ToString(data.getBytes()); + } + + /** + * SHA512加密 + * + * @param data 明文字节数组 + * @return 16进制密文 + */ + public static String encryptSHA512ToString(byte[] data) + { + return bytes2HexString(encryptSHA512(data)); + } + + /** + * SHA512加密 + * + * @param data 明文字节数组 + * @return 密文字节数组 + */ + public static byte[] encryptSHA512(byte[] data) + { + return hashTemplate(data, "SHA512"); + } + + /** + * hash加密模板 + * + * @param data 数据 + * @param algorithm 加密算法 + * @return 密文字节数组 + */ + private static byte[] hashTemplate(byte[] data, String algorithm) + { + if(data == null || data.length <= 0) return null; + try + { + MessageDigest md = MessageDigest.getInstance(algorithm); + md.update(data); + return md.digest(); + } catch(NoSuchAlgorithmException e) + { + e.printStackTrace(); + return null; + } + } + + /** + * HmacMD5加密 + * + * @param data 明文字符串 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacMD5ToString(String data, String key) + { + return encryptHmacMD5ToString(data.getBytes(), key.getBytes()); + } + + /** + * HmacMD5加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacMD5ToString(byte[] data, byte[] key) + { + return bytes2HexString(encryptHmacMD5(data, key)); + } + + /** + * HmacMD5加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 密文字节数组 + */ + public static byte[] encryptHmacMD5(byte[] data, byte[] key) + { + return hmacTemplate(data, key, "HmacMD5"); + } + + /** + * HmacSHA1加密 + * + * @param data 明文字符串 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacSHA1ToString(String data, String key) + { + return encryptHmacSHA1ToString(data.getBytes(), key.getBytes()); + } + + /** + * HmacSHA1加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacSHA1ToString(byte[] data, byte[] key) + { + return bytes2HexString(encryptHmacSHA1(data, key)); + } + + /** + * HmacSHA1加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 密文字节数组 + */ + public static byte[] encryptHmacSHA1(byte[] data, byte[] key) + { + return hmacTemplate(data, key, "HmacSHA1"); + } + + /** + * HmacSHA224加密 + * + * @param data 明文字符串 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacSHA224ToString(String data, String key) + { + return encryptHmacSHA224ToString(data.getBytes(), key.getBytes()); + } + + /** + * HmacSHA224加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacSHA224ToString(byte[] data, byte[] key) + { + return bytes2HexString(encryptHmacSHA224(data, key)); + } + + /** + * HmacSHA224加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 密文字节数组 + */ + public static byte[] encryptHmacSHA224(byte[] data, byte[] key) + { + return hmacTemplate(data, key, "HmacSHA224"); + } + + /** + * HmacSHA256加密 + * + * @param data 明文字符串 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacSHA256ToString(String data, String key) + { + return encryptHmacSHA256ToString(data.getBytes(), key.getBytes()); + } + + /** + * HmacSHA256加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacSHA256ToString(byte[] data, byte[] key) + { + return bytes2HexString(encryptHmacSHA256(data, key)); + } + + /** + * HmacSHA256加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 密文字节数组 + */ + public static byte[] encryptHmacSHA256(byte[] data, byte[] key) + { + return hmacTemplate(data, key, "HmacSHA256"); + } + + /** + * HmacSHA384加密 + * + * @param data 明文字符串 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacSHA384ToString(String data, String key) + { + return encryptHmacSHA384ToString(data.getBytes(), key.getBytes()); + } + + /** + * HmacSHA384加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacSHA384ToString(byte[] data, byte[] key) + { + return bytes2HexString(encryptHmacSHA384(data, key)); + } + + /** + * HmacSHA384加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 密文字节数组 + */ + public static byte[] encryptHmacSHA384(byte[] data, byte[] key) + { + return hmacTemplate(data, key, "HmacSHA384"); + } + + /** + * HmacSHA512加密 + * + * @param data 明文字符串 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacSHA512ToString(String data, String key) + { + return encryptHmacSHA512ToString(data.getBytes(), key.getBytes()); + } + + /** + * HmacSHA512加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 16进制密文 + */ + public static String encryptHmacSHA512ToString(byte[] data, byte[] key) + { + return bytes2HexString(encryptHmacSHA512(data, key)); + } + + /** + * HmacSHA512加密 + * + * @param data 明文字节数组 + * @param key 秘钥 + * @return 密文字节数组 + */ + public static byte[] encryptHmacSHA512(byte[] data, byte[] key) + { + return hmacTemplate(data, key, "HmacSHA512"); + } + + /** + * Hmac加密模板 + * + * @param data 数据 + * @param key 秘钥 + * @param algorithm 加密算法 + * @return 密文字节数组 + */ + private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) + { + if(data == null || data.length == 0 || key == null || key.length == 0) return null; + try + { + SecretKeySpec secretKey = new SecretKeySpec(key, algorithm); + Mac mac = Mac.getInstance(algorithm); + mac.init(secretKey); + return mac.doFinal(data); + } catch(InvalidKeyException | NoSuchAlgorithmException e) + { + e.printStackTrace(); + return null; + } + } + + /************************ DES加密相关 ***********************/ + /** + * DES转变 + *

法算法名称/加密模式/填充方式

+ *

加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB

+ *

填充方式有:NoPadding、ZerosPadding、PKCS5Padding

+ */ + public static String DES_Transformation = "DES/ECB/NoPadding"; + private static final String DES_Algorithm = "DES"; + + /** + * DES加密后转为Base64编码 + * + * @param data 明文 + * @param key 8字节秘钥 + * @return Base64密文 + */ + public static byte[] encryptDES2Base64(byte[] data, byte[] key) + { + return base64Encode(encryptDES(data, key)); + } + + /** + * DES加密后转为16进制 + * + * @param data 明文 + * @param key 8字节秘钥 + * @return 16进制密文 + */ + public static String encryptDES2HexString(byte[] data, byte[] key) + { + return bytes2HexString(encryptDES(data, key)); + } + + /** + * DES加密 + * + * @param data 明文 + * @param key 8字节秘钥 + * @return 密文 + */ + public static byte[] encryptDES(byte[] data, byte[] key) + { + return desTemplate(data, key, DES_Algorithm, DES_Transformation, true); + } + + /** + * DES解密Base64编码密文 + * + * @param data Base64编码密文 + * @param key 8字节秘钥 + * @return 明文 + */ + public static byte[] decryptBase64DES(byte[] data, byte[] key) + { + return decryptDES(base64Decode(data), key); + } + + /** + * DES解密16进制密文 + * + * @param data 16进制密文 + * @param key 8字节秘钥 + * @return 明文 + */ + public static byte[] decryptHexStringDES(String data, byte[] key) + { + return decryptDES(hexString2Bytes(data), key); + } + + /** + * DES解密 + * + * @param data 密文 + * @param key 8字节秘钥 + * @return 明文 + */ + public static byte[] decryptDES(byte[] data, byte[] key) + { + return desTemplate(data, key, DES_Algorithm, DES_Transformation, false); + } + + /************************ 3DES加密相关 ***********************/ + /** + * 3DES转变 + *

法算法名称/加密模式/填充方式

+ *

加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB

+ *

填充方式有:NoPadding、ZerosPadding、PKCS5Padding

+ */ + public static String TripleDES_Transformation = "DESede/ECB/NoPadding"; + private static final String TripleDES_Algorithm = "DESede"; + + + /** + * 3DES加密后转为Base64编码 + * + * @param data 明文 + * @param key 24字节秘钥 + * @return Base64密文 + */ + public static byte[] encrypt3DES2Base64(byte[] data, byte[] key) + { + return base64Encode(encrypt3DES(data, key)); + } + + /** + * 3DES加密后转为16进制 + * + * @param data 明文 + * @param key 24字节秘钥 + * @return 16进制密文 + */ + public static String encrypt3DES2HexString(byte[] data, byte[] key) + { + return bytes2HexString(encrypt3DES(data, key)); + } + + /** + * 3DES加密 + * + * @param data 明文 + * @param key 24字节密钥 + * @return 密文 + */ + public static byte[] encrypt3DES(byte[] data, byte[] key) + { + return desTemplate(data, key, TripleDES_Algorithm, TripleDES_Transformation, true); + } + + /** + * 3DES解密Base64编码密文 + * + * @param data Base64编码密文 + * @param key 24字节秘钥 + * @return 明文 + */ + public static byte[] decryptBase64_3DES(byte[] data, byte[] key) + { + return decrypt3DES(base64Decode(data), key); + } + + /** + * 3DES解密16进制密文 + * + * @param data 16进制密文 + * @param key 24字节秘钥 + * @return 明文 + */ + public static byte[] decryptHexString3DES(String data, byte[] key) + { + return decrypt3DES(hexString2Bytes(data), key); + } + + /** + * 3DES解密 + * + * @param data 密文 + * @param key 24字节密钥 + * @return 明文 + */ + public static byte[] decrypt3DES(byte[] data, byte[] key) + { + return desTemplate(data, key, TripleDES_Algorithm, TripleDES_Transformation, false); + } + + /************************ AES加密相关 ***********************/ + /** + * AES转变 + *

法算法名称/加密模式/填充方式

+ *

加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB

+ *

填充方式有:NoPadding、ZerosPadding、PKCS5Padding

+ */ + public static String AES_Transformation = "AES/ECB/NoPadding"; + private static final String AES_Algorithm = "AES"; + + + /** + * AES加密后转为Base64编码 + * + * @param data 明文 + * @param key 16、24、32字节秘钥 + * @return Base64密文 + */ + public static byte[] encryptAES2Base64(byte[] data, byte[] key) + { + return base64Encode(encryptAES(data, key)); + } + + /** + * AES加密后转为16进制 + * + * @param data 明文 + * @param key 16、24、32字节秘钥 + * @return 16进制密文 + */ + public static String encryptAES2HexString(byte[] data, byte[] key) + { + return bytes2HexString(encryptAES(data, key)); + } + + /** + * AES加密 + * + * @param data 明文 + * @param key 16、24、32字节秘钥 + * @return 密文 + */ + public static byte[] encryptAES(byte[] data, byte[] key) + { + return desTemplate(data, key, AES_Algorithm, AES_Transformation, true); + } + + /** + * AES解密Base64编码密文 + * + * @param data Base64编码密文 + * @param key 16、24、32字节秘钥 + * @return 明文 + */ + public static byte[] decryptBase64AES(byte[] data, byte[] key) + { + return decryptAES(base64Decode(data), key); + } + + /** + * AES解密16进制密文 + * + * @param data 16进制密文 + * @param key 16、24、32字节秘钥 + * @return 明文 + */ + public static byte[] decryptHexStringAES(String data, byte[] key) + { + return decryptAES(hexString2Bytes(data), key); + } + + /** + * AES解密 + * + * @param data 密文 + * @param key 16、24、32字节秘钥 + * @return 明文 + */ + public static byte[] decryptAES(byte[] data, byte[] key) + { + return desTemplate(data, key, AES_Algorithm, AES_Transformation, false); + } + + /** + * DES加密模板 + * + * @param data 数据 + * @param key 秘钥 + * @param algorithm 加密算法 + * @param transformation 转变 + * @param isEncrypt {@code true}: 加密 {@code false}: 解密 + * @return 密文或者明文,适用于DES,3DES,AES + */ + public static byte[] desTemplate(byte[] data, byte[] key, String algorithm, + String transformation, boolean isEncrypt) + { + if(data == null || data.length == 0 || key == null || key.length == 0) return null; + try + { + SecretKeySpec keySpec = new SecretKeySpec(key, algorithm); + Cipher cipher = Cipher.getInstance(transformation); + SecureRandom random = new SecureRandom(); + cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, keySpec, random); + return cipher.doFinal(data); + } catch(Throwable e) + { + e.printStackTrace(); + return null; + } + } + + private static final char hexDigits[] = {'0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F'}; + + /** + * byteArr转hexString + *

例如:

+ * bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns 00A8 + * + * @param bytes 字节数组 + * @return 16进制大写字符串 + */ + private static String bytes2HexString(byte[] bytes) + { + if(bytes == null) return null; + int len = bytes.length; + if(len <= 0) return null; + char[] ret = new char[len << 1]; + for(int i = 0, j = 0; i < len; i++) + { + ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f]; + ret[j++] = hexDigits[bytes[i] & 0x0f]; + } + return new String(ret); + } + + + /** + * hexString转byteArr + *

例如:

+ * hexString2Bytes("00A8") returns { 0, (byte) 0xA8 } + * + * @param hexString 十六进制字符串 + * @return 字节数组 + */ + private static byte[] hexString2Bytes(String hexString) + { + if(TextTool.isEmpty(hexString)) + { + return null; + } + + int len = hexString.length(); + if(len % 2 != 0) + { + hexString = "0" + hexString; + len = len + 1; + } + char[] hexBytes = hexString.toUpperCase().toCharArray(); + byte[] ret = new byte[len >> 1]; + for(int i = 0; i < len; i += 2) + { + ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1])); + } + return ret; + } + + /** + * hexChar转int + * + * @param hexChar hex单个字节 + * @return 0..15 + */ + private static int hex2Dec(char hexChar) + { + if(hexChar >= '0' && hexChar <= '9') + { + return hexChar - '0'; + } + else if(hexChar >= 'A' && hexChar <= 'F') + { + return hexChar - 'A' + 10; + } + else + { + throw new IllegalArgumentException(); + } + } + + /** + * Base64编码 + * + * @param input 要编码的字节数组 + * @return Base64编码后的字符串 + */ + private static byte[] base64Encode(byte[] input) + { + return Base64.encode(input, Base64.NO_WRAP); + } + + /** + * Base64解码 + * + * @param input 要解码的字符串 + * @return Base64解码后的字符串 + */ + private static byte[] base64Decode(byte[] input) + { + return Base64.decode(input, Base64.NO_WRAP); + } } \ No newline at end of file diff --git a/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/FileTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/FileTool.java new file mode 100644 index 0000000..ac67b64 --- /dev/null +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/FileTool.java @@ -0,0 +1,943 @@ +package com.ayvytr.easyandroidlibrary.tools; + +import com.ayvytr.easyandroidlibrary.exception.UnsupportedInitializationException; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2016/8/11
+ *     desc  : 文件相关工具类
+ * 
+ */ +public class FileTool +{ + + private FileTool() + { + throw new UnsupportedInitializationException(); + } + + /** + * return File from pathname(根据文件路径返回文件). + * + * @param pathname 文件路径 + * @return File + */ + public static File fromName(String pathname) + { + return new File(pathname); + } + + /** + * 判断文件是否存在 + * + * @param filePath 文件路径 + * @return {@code true}: 存在
{@code false}: 不存在 + */ + public static boolean isExists(String filePath) + { + return isExists(fromName(filePath)); + } + + /** + * 判断文件是否存在 + * + * @param file 文件 + * @return {@code true}: 存在
{@code false}: 不存在 + */ + public static boolean isExists(File file) + { + return file != null && file.exists(); + } + + /** + * 重命名文件 + * + * @param filePath 文件路径 + * @param newName 新名称 + * @return {@code true}: 重命名成功
{@code false}: 重命名失败 + */ + public static boolean rename(String filePath, String newName) + { + return rename(fromName(filePath), newName); + } + + /** + * 重命名文件 + * + * @param file 文件 + * @param newName 新名称 + * @return {@code true}: 重命名成功
{@code false}: 重命名失败 + */ + public static boolean rename(File file, String newName) + { + if(file == null || !file.exists()) + { + return false; + } + + // 新的文件名为空返回false + if(TextTool.isBlank(newName)) + { + return false; + } + + if(newName.equals(file.getName())) + { + return false; + } + + File newFile = new File(file.getParent() + File.separator + newName); + // 如果重命名的文件已存/重命名失败, 返回false + return !newFile.exists() && file.renameTo(newFile); + } + + /** + * 判断是否是目录 + * + * @param dirPath 目录路径 + * @return {@code true}: 是
{@code false}: 否 + */ + public static boolean isDir(String dirPath) + { + return isDir(fromName(dirPath)); + } + + /** + * 判断是否是目录 + * + * @param file 文件 + * @return {@code true}: 是
{@code false}: 否 + */ + public static boolean isDir(File file) + { + return isExists(file) && file.isDirectory(); + } + + + /** + * 判断是否是文件 + * + * @param filePath 文件路径 + * @return {@code true}: 是
{@code false}: 否 + */ + public static boolean isFile(String filePath) + { + return isFile(fromName(filePath)); + } + + /** + * 判断是否是文件 + * + * @param file 文件 + * @return {@code true}: 是
{@code false}: 否 + */ + public static boolean isFile(File file) + { + return isExists(file) && file.isFile(); + } + + /** + * 根据pathname创建目录. + * + * @param pathname 文件路径 + */ + public static void createDir(String pathname) + { + createDir(fromName(pathname)); + } + + /** + * 根据file创建目录. + * + * @param file File实例 + */ + private static void createDir(File file) + { + if(file != null && !isExists(file)) + { + file.mkdirs(); + } + } + + public static void createFile(String pathname) + { + createFile(fromName(pathname)); + } + + private static void createFile(File file) + { + if(file == null || file.exists()) + { + return; + } + + File parentFile = file.getParentFile(); + if(!parentFile.exists()) + { + parentFile.mkdirs(); + } + + try + { + file.createNewFile(); + } catch(IOException e) + { + e.printStackTrace(); + } + } + + +// /** +// * 复制或移动目录 +// * +// * @param srcDirPath 源目录路径 +// * @param destDirPath 目标目录路径 +// * @param isMove 是否移动 +// * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 +// */ +// private static boolean copyOrMoveDir(String srcDirPath, String destDirPath, boolean isMove) +// { +// return copyOrMoveDir(fromName(srcDirPath), fromName(destDirPath), isMove); +// } +// +// /** +// * 复制或移动目录 +// * +// * @param srcDir 源目录 +// * @param destDir 目标目录 +// * @param isMove 是否移动 +// * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 +// */ +// private static boolean copyOrMoveDir(File srcDir, File destDir, boolean isMove) +// { +// if(srcDir == null || destDir == null) return false; +// // 如果目标目录在源目录中则返回false,看不懂的话好好想想递归怎么结束 +// // srcPath : F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res +// // destPath: F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res1 +// // 为防止以上这种情况出现出现误判,须分别在后面加个路径分隔符 +// String srcPath = srcDir.getPath() + File.separator; +// String destPath = destDir.getPath() + File.separator; +// if(destPath.contains(srcPath)) return false; +// // 源文件不存在或者不是目录则返回false +// if(!srcDir.exists() || !srcDir.isDirectory()) return false; +// // 目标目录不存在返回false +// if(!createOrExistsDir(destDir)) return false; +// File[] files = srcDir.listFiles(); +// for(File file : files) +// { +// File oneDestFile = new File(destPath + file.getName()); +// if(file.isFile()) +// { +// // 如果操作失败返回false +// if(!copyOrMoveFile(file, oneDestFile, isMove)) return false; +// } +// else if(file.isDirectory()) +// { +// // 如果操作失败返回false +// if(!copyOrMoveDir(file, oneDestFile, isMove)) return false; +// } +// } +// return !isMove || deleteDir(srcDir); +// } +// +// /** +// * 复制或移动文件 +// * +// * @param srcFilePath 源文件路径 +// * @param destFilePath 目标文件路径 +// * @param isMove 是否移动 +// * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 +// */ +// private static boolean copyOrMoveFile(String srcFilePath, String destFilePath, boolean isMove) +// { +// return copyOrMoveFile(fromName(srcFilePath), fromName(destFilePath), isMove); +// } +// +// /** +// * 复制或移动文件 +// * +// * @param srcFile 源文件 +// * @param destFile 目标文件 +// * @param isMove 是否移动 +// * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 +// */ +// private static boolean copyOrMoveFile(File srcFile, File destFile, boolean isMove) +// { +// if(srcFile == null || destFile == null) return false; +// // 源文件不存在或者不是文件则返回false +// if(!srcFile.exists() || !srcFile.isFile()) return false; +// // 目标文件存在且是文件则返回false +// if(destFile.exists() && destFile.isFile()) return false; +// // 目标目录不存在返回false +// if(!createOrExistsDir(destFile.getParentFile())) return false; +// try +// { +// return writeFileFromIS(destFile, new FileInputStream(srcFile), false) +// && !(isMove && !deleteFile(srcFile)); +// } catch(FileNotFoundException e) +// { +// e.printStackTrace(); +// return false; +// } +// } + +// /** +// * 复制目录 +// * +// * @param srcDirPath 源目录路径 +// * @param destDirPath 目标目录路径 +// * @return {@code true}: 复制成功
{@code false}: 复制失败 +// */ +// public static boolean copyDir(String srcDirPath, String destDirPath) +// { +// return copyDir(fromName(srcDirPath), fromName(destDirPath)); +// } +// +// /** +// * 复制目录 +// * +// * @param srcDir 源目录 +// * @param destDir 目标目录 +// * @return {@code true}: 复制成功
{@code false}: 复制失败 +// */ +// public static boolean copyDir(File srcDir, File destDir) +// { +// return copyOrMoveDir(srcDir, destDir, false); +// } +// +// /** +// * 复制文件 +// * +// * @param srcFilePath 源文件路径 +// * @param destFilePath 目标文件路径 +// * @return {@code true}: 复制成功
{@code false}: 复制失败 +// */ +// public static boolean copyFile(String srcFilePath, String destFilePath) +// { +// return copyFile(fromName(srcFilePath), fromName(destFilePath)); +// } +// +// /** +// * 复制文件 +// * +// * @param srcFile 源文件 +// * @param destFile 目标文件 +// * @return {@code true}: 复制成功
{@code false}: 复制失败 +// */ +// public static boolean copyFile(File srcFile, File destFile) +// { +// return copyOrMoveFile(srcFile, destFile, false); +// } +// +// /** +// * 移动目录 +// * +// * @param srcDirPath 源目录路径 +// * @param destDirPath 目标目录路径 +// * @return {@code true}: 移动成功
{@code false}: 移动失败 +// */ +// public static boolean moveDir(String srcDirPath, String destDirPath) +// { +// return moveDir(fromName(srcDirPath), fromName(destDirPath)); +// } +// +// /** +// * 移动目录 +// * +// * @param srcDir 源目录 +// * @param destDir 目标目录 +// * @return {@code true}: 移动成功
{@code false}: 移动失败 +// */ +// public static boolean moveDir(File srcDir, File destDir) +// { +// return copyOrMoveDir(srcDir, destDir, true); +// } +// +// /** +// * 移动文件 +// * +// * @param srcFilePath 源文件路径 +// * @param destFilePath 目标文件路径 +// * @return {@code true}: 移动成功
{@code false}: 移动失败 +// */ +// public static boolean moveFile(String srcFilePath, String destFilePath) +// { +// return moveFile(fromName(srcFilePath), fromName(destFilePath)); +// } +// +// /** +// * 移动文件 +// * +// * @param srcFile 源文件 +// * @param destFile 目标文件 +// * @return {@code true}: 移动成功
{@code false}: 移动失败 +// */ +// public static boolean moveFile(File srcFile, File destFile) +// { +// return copyOrMoveFile(srcFile, destFile, true); +// } +// +// /** +// * 删除目录 +// * +// * @param dirPath 目录路径 +// * @return {@code true}: 删除成功
{@code false}: 删除失败 +// */ +// public static boolean deleteDir(String dirPath) +// { +// return deleteDir(fromName(dirPath)); +// } +// +// /** +// * 删除目录 +// * +// * @param dir 目录 +// * @return {@code true}: 删除成功
{@code false}: 删除失败 +// */ +// public static boolean deleteDir(File dir) +// { +// if(dir == null) return false; +// // 目录不存在返回true +// if(!dir.exists()) return true; +// // 不是目录返回false +// if(!dir.isDirectory()) return false; +// // 现在文件存在且是文件夹 +// File[] files = dir.listFiles(); +// if(files != null && files.length != 0) +// { +// for(File file : files) +// { +// if(file.isFile()) +// { +// if(!deleteFile(file)) return false; +// } +// else if(file.isDirectory()) +// { +// if(!deleteDir(file)) return false; +// } +// } +// } +// return dir.delete(); +// } +// +// /** +// * 删除文件 +// * +// * @param srcFilePath 文件路径 +// * @return {@code true}: 删除成功
{@code false}: 删除失败 +// */ +// public static boolean deleteFile(String srcFilePath) +// { +// return deleteFile(fromName(srcFilePath)); +// } +// +// /** +// * 删除文件 +// * +// * @param file 文件 +// * @return {@code true}: 删除成功
{@code false}: 删除失败 +// */ +// public static boolean deleteFile(File file) +// { +// return file != null && (!file.exists() || file.isFile() && file.delete()); +// } +// +// /** +// * 删除目录下的所有文件 +// * +// * @param dirPath 目录路径 +// * @return {@code true}: 删除成功
{@code false}: 删除失败 +// */ +// public static boolean deleteFilesInDir(String dirPath) +// { +// return deleteFilesInDir(fromName(dirPath)); +// } +// +// /** +// * 删除目录下的所有文件 +// * +// * @param dir 目录 +// * @return {@code true}: 删除成功
{@code false}: 删除失败 +// */ +// public static boolean deleteFilesInDir(File dir) +// { +// if(dir == null) return false; +// // 目录不存在返回true +// if(!dir.exists()) return true; +// // 不是目录返回false +// if(!dir.isDirectory()) return false; +// // 现在文件存在且是文件夹 +// File[] files = dir.listFiles(); +// if(files != null && files.length != 0) +// { +// for(File file : files) +// { +// if(file.isFile()) +// { +// if(!deleteFile(file)) return false; +// } +// else if(file.isDirectory()) +// { +// if(!deleteDir(file)) return false; +// } +// } +// } +// return true; +// } + + /** + * 获取目录下所有文件 + * + * @param dirPath 目录路径 + * @param isRecursive 是否递归进子目录 + * @return 文件链表 + */ + public static List listFilesInDir(String dirPath, boolean isRecursive) + { + return listFilesInDir(fromName(dirPath), isRecursive); + } + + /** + * 获取目录下所有文件 + * + * @param dir 目录 + * @param isRecursive 是否递归进子目录 + * @return 文件链表 + */ + public static List listFilesInDir(File dir, boolean isRecursive) + { + if(!isDir(dir)) return null; + if(isRecursive) return listFilesInDir(dir); + List list = new ArrayList<>(); + File[] files = dir.listFiles(); + if(files != null && files.length != 0) + { + Collections.addAll(list, files); + } + return list; + } + + /** + * 获取目录下所有文件包括子目录 + * + * @param dirPath 目录路径 + * @return 文件链表 + */ + public static List listFilesInDir(String dirPath) + { + return listFilesInDir(fromName(dirPath)); + } + + /** + * 获取目录下所有文件包括子目录 + * + * @param dir 目录 + * @return 文件链表 + */ + public static List listFilesInDir(File dir) + { + if(!isDir(dir)) return null; + List list = new ArrayList<>(); + File[] files = dir.listFiles(); + if(files != null && files.length != 0) + { + for(File file : files) + { + list.add(file); + if(file.isDirectory()) + { + list.addAll(listFilesInDir(file)); + } + } + } + return list; + } + + /** + * 获取目录下所有后缀名为suffix的文件 + *

大小写忽略

+ * + * @param dirPath 目录路径 + * @param suffix 后缀名 + * @param isRecursive 是否递归进子目录 + * @return 文件链表 + */ + public static List listFilesInDirWithFilter(String dirPath, String suffix, + boolean isRecursive) + { + return listFilesInDirWithFilter(fromName(dirPath), suffix, isRecursive); + } + + /** + * 获取目录下所有后缀名为suffix的文件 + *

大小写忽略

+ * + * @param dir 目录 + * @param suffix 后缀名 + * @param isRecursive 是否递归进子目录 + * @return 文件链表 + */ + public static List listFilesInDirWithFilter(File dir, String suffix, boolean isRecursive) + { + if(isRecursive) return listFilesInDirWithFilter(dir, suffix); + if(dir == null || !isDir(dir)) return null; + List list = new ArrayList<>(); + File[] files = dir.listFiles(); + if(files != null && files.length != 0) + { + for(File file : files) + { + if(file.getName().toUpperCase().endsWith(suffix.toUpperCase())) + { + list.add(file); + } + } + } + return list; + } + + /** + * 获取目录下所有后缀名为suffix的文件包括子目录 + *

大小写忽略

+ * + * @param dirPath 目录路径 + * @param suffix 后缀名 + * @return 文件链表 + */ + public static List listFilesInDirWithFilter(String dirPath, String suffix) + { + return listFilesInDirWithFilter(fromName(dirPath), suffix); + } + + /** + * 获取目录下所有后缀名为suffix的文件包括子目录 + *

大小写忽略

+ * + * @param dir 目录 + * @param suffix 后缀名 + * @return 文件链表 + */ + public static List listFilesInDirWithFilter(File dir, String suffix) + { + if(dir == null || !isDir(dir)) return null; + List list = new ArrayList<>(); + File[] files = dir.listFiles(); + if(files != null && files.length != 0) + { + for(File file : files) + { + if(file.getName().toUpperCase().endsWith(suffix.toUpperCase())) + { + list.add(file); + } + if(file.isDirectory()) + { + list.addAll(listFilesInDirWithFilter(file, suffix)); + } + } + } + return list; + } + + /** + * 获取目录下所有符合filter的文件 + * + * @param dirPath 目录路径 + * @param filter 过滤器 + * @param isRecursive 是否递归进子目录 + * @return 文件链表 + */ + public static List listFilesInDirWithFilter(String dirPath, FilenameFilter filter, + boolean isRecursive) + { + return listFilesInDirWithFilter(fromName(dirPath), filter, isRecursive); + } + + /** + * 获取目录下所有符合filter的文件 + * + * @param dir 目录 + * @param filter 过滤器 + * @param isRecursive 是否递归进子目录 + * @return 文件链表 + */ + public static List listFilesInDirWithFilter(File dir, FilenameFilter filter, + boolean isRecursive) + { + if(isRecursive) return listFilesInDirWithFilter(dir, filter); + if(dir == null || !isDir(dir)) return null; + List list = new ArrayList<>(); + File[] files = dir.listFiles(); + if(files != null && files.length != 0) + { + for(File file : files) + { + if(filter.accept(file.getParentFile(), file.getName())) + { + list.add(file); + } + } + } + return list; + } + + /** + * 获取目录下所有符合filter的文件包括子目录 + * + * @param dirPath 目录路径 + * @param filter 过滤器 + * @return 文件链表 + */ + public static List listFilesInDirWithFilter(String dirPath, FilenameFilter filter) + { + return listFilesInDirWithFilter(fromName(dirPath), filter); + } + + /** + * 获取目录下所有符合filter的文件包括子目录 + * + * @param dir 目录 + * @param filter 过滤器 + * @return 文件链表 + */ + public static List listFilesInDirWithFilter(File dir, FilenameFilter filter) + { + if(dir == null || !isDir(dir)) return null; + List list = new ArrayList<>(); + File[] files = dir.listFiles(); + if(files != null && files.length != 0) + { + for(File file : files) + { + if(filter.accept(file.getParentFile(), file.getName())) + { + list.add(file); + } + if(file.isDirectory()) + { + list.addAll(listFilesInDirWithFilter(file, filter)); + } + } + } + return list; + } + + /** + * 获取目录下指定文件名的文件包括子目录 + *

大小写忽略

+ * + * @param dirPath 目录路径 + * @param fileName 文件名 + * @return 文件链表 + */ + public static List searchFileInDir(String dirPath, String fileName) + { + return searchFileInDir(fromName(dirPath), fileName); + } + + /** + * 获取目录下指定文件名的文件包括子目录 + *

大小写忽略

+ * + * @param dir 目录 + * @param fileName 文件名 + * @return 文件链表 + */ + public static List searchFileInDir(File dir, String fileName) + { + if(dir == null || !isDir(dir)) return null; + List list = new ArrayList<>(); + File[] files = dir.listFiles(); + if(files != null && files.length != 0) + { + for(File file : files) + { + if(file.getName().toUpperCase().equals(fileName.toUpperCase())) + { + list.add(file); + } + if(file.isDirectory()) + { + list.addAll(searchFileInDir(file, fileName)); + } + } + } + return list; + } + + /** + * 写入content到file,不处理filepath,content异常 + * + * @param filepath 文件路径 + * @param content 文件内容 + * @param isAppend 是不是追加模式 + */ + public void writeFile(String filepath, String content, boolean isAppend) + { + writeFile(new File(filepath), content, isAppend); + } + + /** + * 写入content到file,不处理file,content异常 + * + * @param file File + * @param content 文件内容 + * @param isAppend 是不是追加模式 + */ + public void writeFile(File file, String content, boolean isAppend) + { + try + { + FileOutputStream fileOutputStream = new FileOutputStream(file, isAppend); + BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); + bufferedOutputStream.write(content.getBytes()); + bufferedOutputStream.close(); + fileOutputStream.close(); + } catch(IOException e) + { + e.printStackTrace(); + } + } + + + /** + * 获取文件最后修改的毫秒时间戳 + * + * @param filePath 文件路径 + * @return 文件最后修改的毫秒时间戳 + */ + public static long getLastModified(String filePath) + { + return getLastModified(fromName(filePath)); + } + + /** + * 获取文件最后修改的毫秒时间戳 + * + * @param file 文件 + * @return 文件最后修改的毫秒时间戳 + */ + public static long getLastModified(File file) + { + return file.lastModified(); + } + + + /** + * 根据文件路径获取文件名. + * + * @param pathname 文件路径名 + * @return 文件名 + */ + public static String getName(String pathname) + { + return getName(fromName(pathname)); + } + + private static String getName(File file) + { + return file.getName(); + } + + /** + * 获取文件标题,不包含扩展名 + * + * @param pathname 文件路径名 + * @return 文件标题 + */ + public static String getTitle(String pathname) + { + return getTitle(fromName(pathname)); + } + + /** + * 获取文件标题 + * + * @param file File + * @return 文件标题 + */ + private static String getTitle(File file) + { + String name = file.getName(); + if(!name.contains(".")) + { + return name; + } + + return name.substring(0, name.lastIndexOf(".")); + } + + /** + * 根据pathname返回文件扩展名 + * + * @param pathname 文件路径名 + * @return 扩展名 + */ + public static String getExtension(String pathname) + { + return getExtension(fromName(pathname)); + } + + /** + * 根据File返回扩展名 + * + * @param file + * @return + */ + public static String getExtension(File file) + { + String name = file.getName(); + if(!hasExtension(file)) + { + return ""; + } + + return name.substring(name.lastIndexOf(".") + 1); + } + + /** + * 判断文件是不是有扩展名 + * + * @param file + * @return + */ + private static boolean hasExtension(File file) + { + String name = file.getName(); + if(!name.contains(".")) + { + return false; + } + + //防止文件名以.结束 + if(name.lastIndexOf(".") == name.length() - 1) + { + return false; + } + + return true; + } + + /** + * 判断文件是不是类型化的文件(相当于判断是不是有扩展名) + * + * @param file File + * @return true 是类型化文件. false 不是类型化文件 + */ + public static boolean isTyped(File file) + { + return hasExtension(file); + } + +} \ No newline at end of file diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/RegexTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/RegexTool.java similarity index 79% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/RegexTool.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/RegexTool.java index a50ba22..a48e226 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/RegexTool.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/RegexTool.java @@ -1,207 +1,225 @@ -package com.ayvytr.easydeveloper.tools; - - -import com.ayvytr.easydeveloper.consts.RegexConstant; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - *
- *     author: Blankj
- *     blog  : http://blankj.com
- *     time  : 2016/8/2
- *     desc  : 正则相关工具类
- * 
- */ -public class RegexTool -{ - - private RegexTool() { - throw new UnsupportedOperationException("u can't instantiate me..."); - } - - /** - * If u want more please visit http://toutiao.com/i6231678548520731137/ - */ - - /** - * 验证手机号(简单) - * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isMobileSimple(CharSequence input) { - return isMatch(RegexConstant.REGEX_MOBILE_SIMPLE, input); - } - - /** - * 验证手机号(精确) - * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isMobileExact(CharSequence input) { - return isMatch(RegexConstant.REGEX_MOBILE_EXACT, input); - } - - /** - * 验证电话号码 - * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isTel(CharSequence input) { - return isMatch(RegexConstant.REGEX_TEL, input); - } - - /** - * 验证身份证号码15位 - * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isIDCard15(CharSequence input) { - return isMatch(RegexConstant.REGEX_ID_CARD15, input); - } - - /** - * 验证身份证号码18位 - * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isIDCard18(CharSequence input) { - return isMatch(RegexConstant.REGEX_ID_CARD18, input); - } - - /** - * 验证邮箱 - * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isEmail(CharSequence input) { - return isMatch(RegexConstant.REGEX_EMAIL, input); - } - - /** - * 验证URL - * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isURL(CharSequence input) { - return isMatch(RegexConstant.REGEX_URL, input); - } - - /** - * 验证汉字 - * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isZh(CharSequence input) { - return isMatch(RegexConstant.REGEX_ZH, input); - } - - /** - * 验证用户名 - *

取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位

- * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isUsername(CharSequence input) { - return isMatch(RegexConstant.REGEX_USERNAME, input); - } - - /** - * 验证yyyy-MM-dd格式的日期校验,已考虑平闰年 - * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isDate(CharSequence input) { - return isMatch(RegexConstant.REGEX_DATE, input); - } - - /** - * 验证IP地址 - * - * @param input 待验证文本 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isIP(CharSequence input) { - return isMatch(RegexConstant.REGEX_IP, input); - } - - /** - * 判断是否匹配正则 - * - * @param regex 正则表达式 - * @param input 要匹配的字符串 - * @return {@code true}: 匹配
{@code false}: 不匹配 - */ - public static boolean isMatch(String regex, CharSequence input) { - return input != null && input.length() > 0 && Pattern.matches(regex, input); - } - - /** - * 获取正则匹配的部分 - * - * @param regex 正则表达式 - * @param input 要匹配的字符串 - * @return 正则匹配的部分 - */ - public static List getMatches(String regex, CharSequence input) { - if (input == null) return null; - List matches = new ArrayList<>(); - Pattern pattern = Pattern.compile(regex); - Matcher matcher = pattern.matcher(input); - while (matcher.find()) { - matches.add(matcher.group()); - } - return matches; - } - - /** - * 获取正则匹配分组 - * - * @param input 要分组的字符串 - * @param regex 正则表达式 - * @return 正则匹配分组 - */ - public static String[] getSplits(String input, String regex) { - if (input == null) return null; - return input.split(regex); - } - - /** - * 替换正则匹配的第一部分 - * - * @param input 要替换的字符串 - * @param regex 正则表达式 - * @param replacement 代替者 - * @return 替换正则匹配的第一部分 - */ - public static String getReplaceFirst(String input, String regex, String replacement) { - if (input == null) return null; - return Pattern.compile(regex).matcher(input).replaceFirst(replacement); - } - - /** - * 替换所有正则匹配的部分 - * - * @param input 要替换的字符串 - * @param regex 正则表达式 - * @param replacement 代替者 - * @return 替换所有正则匹配的部分 - */ - public static String getReplaceAll(String input, String regex, String replacement) { - if (input == null) return null; - return Pattern.compile(regex).matcher(input).replaceAll(replacement); - } +package com.ayvytr.easyandroidlibrary.tools; + + +import com.ayvytr.easyandroidlibrary.consts.RegexConstant; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2016/8/2
+ *     desc  : 正则相关工具类
+ * 
+ */ +public class RegexTool +{ + + private RegexTool() + { + throw new UnsupportedOperationException("u can't instantiate me..."); + } + + /** + * If u want more please visit http://toutiao.com/i6231678548520731137/ + */ + + /** + * 验证手机号(简单) + * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isMobileSimple(CharSequence input) + { + return isMatch(RegexConstant.REGEX_MOBILE_SIMPLE, input); + } + + /** + * 验证手机号(精确) + * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isMobileExact(CharSequence input) + { + return isMatch(RegexConstant.REGEX_MOBILE_EXACT, input); + } + + /** + * 验证电话号码 + * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isTel(CharSequence input) + { + return isMatch(RegexConstant.REGEX_TEL, input); + } + + /** + * 验证身份证号码15位 + * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isIDCard15(CharSequence input) + { + return isMatch(RegexConstant.REGEX_ID_CARD15, input); + } + + /** + * 验证身份证号码18位 + * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isIDCard18(CharSequence input) + { + return isMatch(RegexConstant.REGEX_ID_CARD18, input); + } + + /** + * 验证邮箱 + * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isEmail(CharSequence input) + { + return isMatch(RegexConstant.REGEX_EMAIL, input); + } + + /** + * 验证URL + * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isURL(CharSequence input) + { + return isMatch(RegexConstant.REGEX_URL, input); + } + + /** + * 验证汉字 + * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isZh(CharSequence input) + { + return isMatch(RegexConstant.REGEX_ZH, input); + } + + /** + * 验证用户名 + *

取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位

+ * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isUsername(CharSequence input) + { + return isMatch(RegexConstant.REGEX_USERNAME, input); + } + + /** + * 验证yyyy-MM-dd格式的日期校验,已考虑平闰年 + * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isDate(CharSequence input) + { + return isMatch(RegexConstant.REGEX_DATE, input); + } + + /** + * 验证IP地址 + * + * @param input 待验证文本 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isIP(CharSequence input) + { + return isMatch(RegexConstant.REGEX_IP, input); + } + + /** + * 判断是否匹配正则 + * + * @param regex 正则表达式 + * @param input 要匹配的字符串 + * @return {@code true}: 匹配
{@code false}: 不匹配 + */ + public static boolean isMatch(String regex, CharSequence input) + { + return input != null && input.length() > 0 && Pattern.matches(regex, input); + } + + /** + * 获取正则匹配的部分 + * + * @param regex 正则表达式 + * @param input 要匹配的字符串 + * @return 正则匹配的部分 + */ + public static List getMatches(String regex, CharSequence input) + { + if(input == null) return null; + List matches = new ArrayList<>(); + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(input); + while(matcher.find()) + { + matches.add(matcher.group()); + } + return matches; + } + + /** + * 获取正则匹配分组 + * + * @param input 要分组的字符串 + * @param regex 正则表达式 + * @return 正则匹配分组 + */ + public static String[] getSplits(String input, String regex) + { + if(input == null) return null; + return input.split(regex); + } + + /** + * 替换正则匹配的第一部分 + * + * @param input 要替换的字符串 + * @param regex 正则表达式 + * @param replacement 代替者 + * @return 替换正则匹配的第一部分 + */ + public static String getReplaceFirst(String input, String regex, String replacement) + { + if(input == null) return null; + return Pattern.compile(regex).matcher(input).replaceFirst(replacement); + } + + /** + * 替换所有正则匹配的部分 + * + * @param input 要替换的字符串 + * @param regex 正则表达式 + * @param replacement 代替者 + * @return 替换所有正则匹配的部分 + */ + public static String getReplaceAll(String input, String regex, String replacement) + { + if(input == null) return null; + return Pattern.compile(regex).matcher(input).replaceAll(replacement); + } } \ No newline at end of file diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/TextTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/TextTool.java similarity index 89% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/TextTool.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/TextTool.java index 01c40cb..51d0993 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/TextTool.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/TextTool.java @@ -1,117 +1,116 @@ -package com.ayvytr.easydeveloper.tools; - -import android.text.TextUtils; - -import com.ayvytr.easydeveloper.exception.UnsupportedInitializationException; - -/** - * Created by davidwang on 2017/3/15. - * - */ - -public class TextTool -{ - private TextTool() - { - throw new UnsupportedInitializationException(); - } - - /** - * 设置文本到剪贴板 - * - - /** - * 判断字符串是不是空值:str == null / str.length() == 0 - */ - public static boolean isEmpty(String str) - { - return str == null || str.isEmpty(); - } - - /** - * 判断字符串是不是纯数字字符 - */ - public static boolean isDigit(String str) - { - if(isEmpty(str)) - { - return false; - } - - return TextUtils.isDigitsOnly(str); - } - - /** - * 判断字符串是不是纯数字字符 - */ - public static boolean isNumber(String str) - { - return isDigit(str); - } - - /** - * 字符串反转,如果为空,返回空字符串 - */ - public static String reverse(String str) - { - if(isEmpty(str)) - { - return emptyString(); - } - - int length = str.length(); - if(length <= 1) - { - return str; - } - - int mid = length >> 1; - char[] chars = str.toCharArray(); - char c; - for(int i = 0; i < mid; ++i) - { - c = chars[i]; - chars[i] = chars[length - i - 1]; - chars[length - i - 1] = c; - } - - return new String(chars); - } - - private static String emptyString() - { - return ""; - } - - /** - * 字符串分割方法,当字符串末尾是 regex 时,循环去掉 regex,以处理后的字符串进行分割 - */ - public static String[] split(String str, String regex) - { - if(regex == null) - { - throw new NullPointerException(); - } - - String s = str; - while(s.endsWith(regex)) - { - s = s.substring(0, s.lastIndexOf(regex)); - } - - return s.split(regex); - } - - /** - * 判断字符串是不是空白。null/长度为0/全部为空格 - */ - public static boolean isBlank(String str) - { - if(isEmpty(str)) - { - return true; - } - - return isEmpty(str.trim()); - } -} +package com.ayvytr.easyandroidlibrary.tools; + +import android.text.TextUtils; + +import com.ayvytr.easyandroidlibrary.exception.UnsupportedInitializationException; + +/** + * Created by davidwang on 2017/3/15. + */ + +public class TextTool +{ + private TextTool() + { + throw new UnsupportedInitializationException(); + } + + /** + * 设置文本到剪贴板 + *

+ *

+ * /** + * 判断字符串是不是空值:str == null / str.length() == 0 + */ + public static boolean isEmpty(String str) + { + return str == null || str.isEmpty(); + } + + /** + * 判断字符串是不是纯数字字符 + */ + public static boolean isDigit(String str) + { + if(isEmpty(str)) + { + return false; + } + + return TextUtils.isDigitsOnly(str); + } + + /** + * 判断字符串是不是纯数字字符 + */ + public static boolean isNumber(String str) + { + return isDigit(str); + } + + /** + * 字符串反转,如果为空,返回空字符串 + */ + public static String reverse(String str) + { + if(isEmpty(str)) + { + return emptyString(); + } + + int length = str.length(); + if(length <= 1) + { + return str; + } + + int mid = length >> 1; + char[] chars = str.toCharArray(); + char c; + for(int i = 0; i < mid; ++i) + { + c = chars[i]; + chars[i] = chars[length - i - 1]; + chars[length - i - 1] = c; + } + + return new String(chars); + } + + private static String emptyString() + { + return ""; + } + + /** + * 字符串分割方法,当字符串末尾是 regex 时,循环去掉 regex,以处理后的字符串进行分割 + */ + public static String[] split(String str, String regex) + { + if(regex == null) + { + throw new NullPointerException(); + } + + String s = str; + while(s.endsWith(regex)) + { + s = s.substring(0, s.lastIndexOf(regex)); + } + + return s.split(regex); + } + + /** + * 判断字符串是不是空白。null/长度为0/全部为空格 + */ + public static boolean isBlank(String str) + { + if(isEmpty(str)) + { + return true; + } + + return isEmpty(str.trim()); + } +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/TimeTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/TimeTool.java similarity index 85% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/TimeTool.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/TimeTool.java index 18913b6..f8651a5 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/TimeTool.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/TimeTool.java @@ -1,1160 +1,1273 @@ -package com.ayvytr.easydeveloper.tools; - -import android.annotation.SuppressLint; - -import com.ayvytr.easydeveloper.consts.TimeConstant; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -/** - *

- *     author: Blankj
- *     blog  : http://blankj.com
- *     time  : 2016/8/2
- *     desc  : 时间相关工具类
- * 
- */ -public class TimeTool -{ - - private TimeTool() { - throw new UnsupportedOperationException("u can't instantiate me..."); - } - - /** - *

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

- * 格式的意义如下: 日期和时间模式
- *

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

- * 定义了以下模式字母(所有其他字符 'A' 到 'Z' 和 'a' 到 'z' 都被保留):
- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
字母日期或时间元素表示示例
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
- *
-     *                          HH:mm    15:44
-     *                         h:mm a    3:44 下午
-     *                        HH:mm z    15:44 CST
-     *                        HH:mm Z    15:44 +0800
-     *                     HH:mm zzzz    15:44 中国标准时间
-     *                       HH:mm:ss    15:44:40
-     *                     yyyy-MM-dd    2016-08-12
-     *               yyyy-MM-dd HH:mm    2016-08-12 15:44
-     *            yyyy-MM-dd HH:mm:ss    2016-08-12 15:44:40
-     *       yyyy-MM-dd HH:mm:ss zzzz    2016-08-12 15:44:40 中国标准时间
-     *  EEEE yyyy-MM-dd HH:mm:ss zzzz    星期五 2016-08-12 15:44:40 中国标准时间
-     *       yyyy-MM-dd HH:mm:ss.SSSZ    2016-08-12 15:44:40.461+0800
-     *     yyyy-MM-dd'T'HH:mm:ss.SSSZ    2016-08-12T15:44:40.461+0800
-     *   yyyy.MM.dd G 'at' HH:mm:ss z    2016.08.12 公元 at 15:44:40 CST
-     *                         K:mm a    3:44 下午
-     *               EEE, MMM d, ''yy    星期五, 八月 12, '16
-     *          hh 'o''clock' a, zzzz    03 o'clock 下午, 中国标准时间
-     *   yyyyy.MMMMM.dd GGG hh:mm aaa    02016.八月.12 公元 03:44 下午
-     *     EEE, d MMM yyyy HH:mm:ss Z    星期五, 12 八月 2016 15:44:40 +0800
-     *                  yyMMddHHmmssZ    160812154440+0800
-     *     yyyy-MM-dd'T'HH:mm:ss.SSSZ    2016-08-12T15:44:40.461+0800
-     * EEEE 'DATE('yyyy-MM-dd')' 'TIME('HH:mm:ss')' zzzz    星期五 DATE(2016-08-12) TIME(15:44:40) 中国标准时间
-     * 
- * 注意:SimpleDateFormat不是线程安全的,线程安全需用{@code ThreadLocal} - */ - public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss"; - - /** - * 将时间戳转为时间字符串 - *

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

- * - * @param millis 毫秒时间戳 - * @return 时间字符串 - */ - public static String millis2String(long millis) { - return new SimpleDateFormat(DEFAULT_PATTERN, Locale.getDefault()).format(new Date(millis)); - } - - /** - * 将时间戳转为时间字符串 - *

格式为pattern

- * - * @param millis 毫秒时间戳 - * @param pattern 时间格式 - * @return 时间字符串 - */ - public static String millis2String(long millis, String pattern) { - return new SimpleDateFormat(pattern, Locale.getDefault()).format(new Date(millis)); - } - - /** - * 将时间字符串转为时间戳 - *

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

- * - * @param time 时间字符串 - * @return 毫秒时间戳 - */ - public static long string2Millis(String time) { - return string2Millis(time, DEFAULT_PATTERN); - } - - /** - * 将时间字符串转为时间戳 - *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return 毫秒时间戳 - */ - public static long string2Millis(String time, String pattern) { - try { - return new SimpleDateFormat(pattern, Locale.getDefault()).parse(time).getTime(); - } catch (ParseException e) { - e.printStackTrace(); - } - return -1; - } - - /** - * 将时间字符串转为Date类型 - *

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

- * - * @param time 时间字符串 - * @return Date类型 - */ - public static Date string2Date(String time) { - return string2Date(time, DEFAULT_PATTERN); - } - - /** - * 将时间字符串转为Date类型 - *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return Date类型 - */ - public static Date string2Date(String time, String pattern) { - return new Date(string2Millis(time, pattern)); - } - - /** - * 将Date类型转为时间字符串 - *

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

- * - * @param date Date类型时间 - * @return 时间字符串 - */ - public static String date2String(Date date) { - return date2String(date, DEFAULT_PATTERN); - } - - /** - * 将Date类型转为时间字符串 - *

格式为pattern

- * - * @param date Date类型时间 - * @param pattern 时间格式 - * @return 时间字符串 - */ - public static String date2String(Date date, String pattern) { - return new SimpleDateFormat(pattern, Locale.getDefault()).format(date); - } - - /** - * 将Date类型转为时间戳 - * - * @param date Date类型时间 - * @return 毫秒时间戳 - */ - public static long date2Millis(Date date) { - return date.getTime(); - } - - /** - * 将时间戳转为Date类型 - * - * @param millis 毫秒时间戳 - * @return Date类型时间 - */ - public static Date millis2Date(long millis) { - return new Date(millis); - } - - /** - * 获取两个时间差(单位:unit) - *

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

- * - * @param time0 时间字符串0 - * @param time1 时间字符串1 - * @param unit 单位类型 - *
    - *
  • {@link TimeConstant#MSEC}: 毫秒
  • - *
  • {@link TimeConstant#SEC }: 秒
  • - *
  • {@link TimeConstant#MIN }: 分
  • - *
  • {@link TimeConstant#HOUR}: 小时
  • - *
  • {@link TimeConstant#DAY }: 天
  • - *
- * @return unit时间戳 - */ - public static long getTimeSpan(String time0, String time1, @TimeConstant.Unit int unit) { - return getTimeSpan(time0, time1, unit, DEFAULT_PATTERN); - } - - /** - * 获取两个时间差(单位:unit) - *

time0和time1格式都为format

- * - * @param time0 时间字符串0 - * @param time1 时间字符串1 - * @param unit 单位类型 - *
    - *
  • {@link TimeConstant#MSEC}: 毫秒
  • - *
  • {@link TimeConstant#SEC }: 秒
  • - *
  • {@link TimeConstant#MIN }: 分
  • - *
  • {@link TimeConstant#HOUR}: 小时
  • - *
  • {@link TimeConstant#DAY }: 天
  • - *
- * @param pattern 时间格式 - * @return unit时间戳 - */ - public static long getTimeSpan(String time0, String time1, @TimeConstant.Unit int unit, String pattern) { - return ConvertTool.millis2TimeSpan(Math.abs(string2Millis(time0, pattern) - string2Millis(time1, pattern)), unit); - } - - /** - * 获取两个时间差(单位:unit) - * - * @param date0 Date类型时间0 - * @param date1 Date类型时间1 - * @param unit 单位类型 - *
    - *
  • {@link TimeConstant#MSEC}: 毫秒
  • - *
  • {@link TimeConstant#SEC }: 秒
  • - *
  • {@link TimeConstant#MIN }: 分
  • - *
  • {@link TimeConstant#HOUR}: 小时
  • - *
  • {@link TimeConstant#DAY }: 天
  • - *
- * @return unit时间戳 - */ - public static long getTimeSpan(Date date0, Date date1, @TimeConstant.Unit int unit) { - return ConvertTool.millis2TimeSpan(Math.abs(date2Millis(date0) - date2Millis(date1)), unit); - } - - /** - * 获取两个时间差(单位:unit) - * - * @param millis0 毫秒时间戳0 - * @param millis1 毫秒时间戳1 - * @param unit 单位类型 - *
    - *
  • {@link TimeConstant#MSEC}: 毫秒
  • - *
  • {@link TimeConstant#SEC }: 秒
  • - *
  • {@link TimeConstant#MIN }: 分
  • - *
  • {@link TimeConstant#HOUR}: 小时
  • - *
  • {@link TimeConstant#DAY }: 天
  • - *
- * @return unit时间戳 - */ - public static long getTimeSpan(long millis0, long millis1, @TimeConstant.Unit int unit) { - return ConvertTool.millis2TimeSpan(Math.abs(millis0 - millis1), unit); - } - - /** - * 获取合适型两个时间差 - *

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

- * - * @param time0 时间字符串0 - * @param time1 时间字符串1 - * @param precision 精度 - *

precision = 0,返回null

- *

precision = 1,返回天

- *

precision = 2,返回天和小时

- *

precision = 3,返回天、小时和分钟

- *

precision = 4,返回天、小时、分钟和秒

- *

precision >= 5,返回天、小时、分钟、秒和毫秒

- * @return 合适型两个时间差 - */ - public static String getFitTimeSpan(String time0, String time1, int precision) { - return ConvertTool.millis2FitTimeSpan(Math.abs(string2Millis(time0, DEFAULT_PATTERN) - string2Millis(time1, DEFAULT_PATTERN)), precision); - } - - /** - * 获取合适型两个时间差 - *

time0和time1格式都为pattern

- * - * @param time0 时间字符串0 - * @param time1 时间字符串1 - * @param precision 精度 - *

precision = 0,返回null

- *

precision = 1,返回天

- *

precision = 2,返回天和小时

- *

precision = 3,返回天、小时和分钟

- *

precision = 4,返回天、小时、分钟和秒

- *

precision >= 5,返回天、小时、分钟、秒和毫秒

- * @param pattern 时间格式 - * @return 合适型两个时间差 - */ - public static String getFitTimeSpan(String time0, String time1, int precision, String pattern) { - return ConvertTool.millis2FitTimeSpan(Math.abs(string2Millis(time0, pattern) - string2Millis(time1, pattern)), precision); - } - - /** - * 获取合适型两个时间差 - * - * @param date0 Date类型时间0 - * @param date1 Date类型时间1 - * @param precision 精度 - *

precision = 0,返回null

- *

precision = 1,返回天

- *

precision = 2,返回天和小时

- *

precision = 3,返回天、小时和分钟

- *

precision = 4,返回天、小时、分钟和秒

- *

precision >= 5,返回天、小时、分钟、秒和毫秒

- * @return 合适型两个时间差 - */ - public static String getFitTimeSpan(Date date0, Date date1, int precision) { - return ConvertTool - .millis2FitTimeSpan(Math.abs(date2Millis(date0) - date2Millis(date1)), precision); - } - - /** - * 获取合适型两个时间差 - * - * @param millis0 毫秒时间戳1 - * @param millis1 毫秒时间戳2 - * @param precision 精度 - *

precision = 0,返回null

- *

precision = 1,返回天

- *

precision = 2,返回天和小时

- *

precision = 3,返回天、小时和分钟

- *

precision = 4,返回天、小时、分钟和秒

- *

precision >= 5,返回天、小时、分钟、秒和毫秒

- * @return 合适型两个时间差 - */ - public static String getFitTimeSpan(long millis0, long millis1, int precision) { - return ConvertTool.millis2FitTimeSpan(Math.abs(millis0 - millis1), precision); - } - - /** - * 获取当前毫秒时间戳 - * - * @return 毫秒时间戳 - */ - public static long getNowTimeMills() { - return System.currentTimeMillis(); - } - - /** - * 获取当前时间字符串 - *

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

- * - * @return 时间字符串 - */ - public static String getNowTimeString() { - return millis2String(System.currentTimeMillis(), DEFAULT_PATTERN); - } - - /** - * 获取当前时间字符串 - *

格式为pattern

- * - * @param pattern 时间格式 - * @return 时间字符串 - */ - public static String getNowTimeString(String pattern) { - return millis2String(System.currentTimeMillis(), pattern); - } - - /** - * 获取当前Date - * - * @return Date类型时间 - */ - public static Date getNowTimeDate() { - return new Date(); - } - - /** - * 获取与当前时间的差(单位:unit) - *

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

- * - * @param time 时间字符串 - * @param unit 单位类型 - *
    - *
  • {@link TimeConstant#MSEC}: 毫秒
  • - *
  • {@link TimeConstant#SEC }: 秒
  • - *
  • {@link TimeConstant#MIN }: 分
  • - *
  • {@link TimeConstant#HOUR}: 小时
  • - *
  • {@link TimeConstant#DAY }: 天
  • - *
- * @return unit时间戳 - */ - public static long getTimeSpanByNow(String time, @TimeConstant.Unit int unit) { - return getTimeSpan(getNowTimeString(), time, unit, DEFAULT_PATTERN); - } - - /** - * 获取与当前时间的差(单位:unit) - *

time格式为pattern

- * - * @param time 时间字符串 - * @param unit 单位类型 - *
    - *
  • {@link TimeConstant#MSEC}: 毫秒
  • - *
  • {@link TimeConstant#SEC }: 秒
  • - *
  • {@link TimeConstant#MIN }: 分
  • - *
  • {@link TimeConstant#HOUR}: 小时
  • - *
  • {@link TimeConstant#DAY }: 天
  • - *
- * @param pattern 时间格式 - * @return unit时间戳 - */ - public static long getTimeSpanByNow(String time, @TimeConstant.Unit int unit, String pattern) { - return getTimeSpan(getNowTimeString(), time, unit, pattern); - } - - /** - * 获取与当前时间的差(单位:unit) - * - * @param date Date类型时间 - * @param unit 单位类型 - *
    - *
  • {@link TimeConstant#MSEC}: 毫秒
  • - *
  • {@link TimeConstant#SEC }: 秒
  • - *
  • {@link TimeConstant#MIN }: 分
  • - *
  • {@link TimeConstant#HOUR}: 小时
  • - *
  • {@link TimeConstant#DAY }: 天
  • - *
- * @return unit时间戳 - */ - public static long getTimeSpanByNow(Date date, @TimeConstant.Unit int unit) { - return getTimeSpan(new Date(), date, unit); - } - - /** - * 获取与当前时间的差(单位:unit) - * - * @param millis 毫秒时间戳 - * @param unit 单位类型 - *
    - *
  • {@link TimeConstant#MSEC}: 毫秒
  • - *
  • {@link TimeConstant#SEC }: 秒
  • - *
  • {@link TimeConstant#MIN }: 分
  • - *
  • {@link TimeConstant#HOUR}: 小时
  • - *
  • {@link TimeConstant#DAY }: 天
  • - *
- * @return unit时间戳 - */ - public static long getTimeSpanByNow(long millis, @TimeConstant.Unit int unit) { - return getTimeSpan(System.currentTimeMillis(), millis, unit); - } - - /** - * 获取合适型与当前时间的差 - *

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

- * - * @param time 时间字符串 - * @param precision 精度 - *
    - *
  • precision = 0,返回null
  • - *
  • precision = 1,返回天
  • - *
  • precision = 2,返回天和小时
  • - *
  • precision = 3,返回天、小时和分钟
  • - *
  • precision = 4,返回天、小时、分钟和秒
  • - *
  • precision >= 5,返回天、小时、分钟、秒和毫秒
  • - *
- * @return 合适型与当前时间的差 - */ - public static String getFitTimeSpanByNow(String time, int precision) { - return getFitTimeSpan(getNowTimeString(), time, precision, DEFAULT_PATTERN); - } - - /** - * 获取合适型与当前时间的差 - *

time格式为pattern

- * - * @param time 时间字符串 - * @param precision 精度 - * @param pattern 时间格式 - *
    - *
  • precision = 0,返回null
  • - *
  • precision = 1,返回天
  • - *
  • precision = 2,返回天和小时
  • - *
  • precision = 3,返回天、小时和分钟
  • - *
  • precision = 4,返回天、小时、分钟和秒
  • - *
  • precision >= 5,返回天、小时、分钟、秒和毫秒
  • - *
- * @return 合适型与当前时间的差 - */ - public static String getFitTimeSpanByNow(String time, int precision, String pattern) { - return getFitTimeSpan(getNowTimeString(), time, precision, pattern); - } - - /** - * 获取合适型与当前时间的差 - * - * @param date Date类型时间 - * @param precision 精度 - *
    - *
  • precision = 0,返回null
  • - *
  • precision = 1,返回天
  • - *
  • precision = 2,返回天和小时
  • - *
  • precision = 3,返回天、小时和分钟
  • - *
  • precision = 4,返回天、小时、分钟和秒
  • - *
  • precision >= 5,返回天、小时、分钟、秒和毫秒
  • - *
- * @return 合适型与当前时间的差 - */ - public static String getFitTimeSpanByNow(Date date, int precision) { - return getFitTimeSpan(getNowTimeDate(), date, precision); - } - - /** - * 获取合适型与当前时间的差 - * - * @param millis 毫秒时间戳 - * @param precision 精度 - *
    - *
  • precision = 0,返回null
  • - *
  • precision = 1,返回天
  • - *
  • precision = 2,返回天和小时
  • - *
  • precision = 3,返回天、小时和分钟
  • - *
  • precision = 4,返回天、小时、分钟和秒
  • - *
  • precision >= 5,返回天、小时、分钟、秒和毫秒
  • - *
- * @return 合适型与当前时间的差 - */ - public static String getFitTimeSpanByNow(long millis, int precision) { - return getFitTimeSpan(System.currentTimeMillis(), millis, precision); - } - - /** - * 获取友好型与当前时间的差 - *

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

- * - * @param time 时间字符串 - * @return 友好型与当前时间的差 - *
    - *
  • 如果小于1秒钟内,显示刚刚
  • - *
  • 如果在1分钟内,显示XXX秒前
  • - *
  • 如果在1小时内,显示XXX分钟前
  • - *
  • 如果在1小时外的今天内,显示今天15:32
  • - *
  • 如果是昨天的,显示昨天15:32
  • - *
  • 其余显示,2016-10-15
  • - *
  • 时间不合法的情况全部日期和时间信息,如星期六 十月 27 14:21:20 CST 2007
  • - *
- */ - public static String getFriendlyTimeSpanByNow(String time) { - return getFriendlyTimeSpanByNow(time, DEFAULT_PATTERN); - } - - /** - * 获取友好型与当前时间的差 - *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return 友好型与当前时间的差 - *
    - *
  • 如果小于1秒钟内,显示刚刚
  • - *
  • 如果在1分钟内,显示XXX秒前
  • - *
  • 如果在1小时内,显示XXX分钟前
  • - *
  • 如果在1小时外的今天内,显示今天15:32
  • - *
  • 如果是昨天的,显示昨天15:32
  • - *
  • 其余显示,2016-10-15
  • - *
  • 时间不合法的情况全部日期和时间信息,如星期六 十月 27 14:21:20 CST 2007
  • - *
- */ - public static String getFriendlyTimeSpanByNow(String time, String pattern) { - return getFriendlyTimeSpanByNow(string2Millis(time, pattern)); - } - - /** - * 获取友好型与当前时间的差 - * - * @param date Date类型时间 - * @return 友好型与当前时间的差 - *
    - *
  • 如果小于1秒钟内,显示刚刚
  • - *
  • 如果在1分钟内,显示XXX秒前
  • - *
  • 如果在1小时内,显示XXX分钟前
  • - *
  • 如果在1小时外的今天内,显示今天15:32
  • - *
  • 如果是昨天的,显示昨天15:32
  • - *
  • 其余显示,2016-10-15
  • - *
  • 时间不合法的情况全部日期和时间信息,如星期六 十月 27 14:21:20 CST 2007
  • - *
- */ - public static String getFriendlyTimeSpanByNow(Date date) { - return getFriendlyTimeSpanByNow(date.getTime()); - } - - /** - * 获取友好型与当前时间的差 - * - * @param millis 毫秒时间戳 - * @return 友好型与当前时间的差 - *
    - *
  • 如果小于1秒钟内,显示刚刚
  • - *
  • 如果在1分钟内,显示XXX秒前
  • - *
  • 如果在1小时内,显示XXX分钟前
  • - *
  • 如果在1小时外的今天内,显示今天15:32
  • - *
  • 如果是昨天的,显示昨天15:32
  • - *
  • 其余显示,2016-10-15
  • - *
  • 时间不合法的情况全部日期和时间信息,如星期六 十月 27 14:21:20 CST 2007
  • - *
- */ - @SuppressLint("DefaultLocale") - public static String getFriendlyTimeSpanByNow(long millis) { - long now = System.currentTimeMillis(); - long span = now - millis; - if (span < 0) - return String.format("%tc", millis);// U can read http://www.apihome.cn/api/java/Formatter.html to understand it. - if (span < 1000) { - return "刚刚"; - } else if (span < TimeConstant.MIN) { - return String.format("%d秒前", span / TimeConstant.SEC); - } else if (span < TimeConstant.HOUR) { - return String.format("%d分钟前", span / TimeConstant.MIN); - } - // 获取当天00:00 - long wee = (now / TimeConstant.DAY) * TimeConstant.DAY - 8 * TimeConstant.HOUR; - if (millis >= wee) { - return String.format("今天%tR", millis); - } else if (millis >= wee - TimeConstant.DAY) { - return String.format("昨天%tR", millis); - } else { - return String.format("%tF", millis); - } - } - - /** - * 判断是否同一天 - *

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

- * - * @param time 时间字符串 - * @return {@code true}: 是
{@code false}: 否 - */ - public static boolean isSameDay(String time) { - return isSameDay(string2Millis(time, DEFAULT_PATTERN)); - } - - /** - * 判断是否同一天 - *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return {@code true}: 是
{@code false}: 否 - */ - public static boolean isSameDay(String time, String pattern) { - return isSameDay(string2Millis(time, pattern)); - } - - /** - * 判断是否同一天 - * - * @param date Date类型时间 - * @return {@code true}: 是
{@code false}: 否 - */ - public static boolean isSameDay(Date date) { - return isSameDay(date.getTime()); - } - - /** - * 判断是否同一天 - * - * @param millis 毫秒时间戳 - * @return {@code true}: 是
{@code false}: 否 - */ - public static boolean isSameDay(long millis) { - long wee = (System.currentTimeMillis() / TimeConstant.DAY) * TimeConstant.DAY - 8 * TimeConstant.HOUR; - return millis >= wee && millis < wee + TimeConstant.DAY; - } - - /** - * 判断是否闰年 - *

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

- * - * @param time 时间字符串 - * @return {@code true}: 闰年
{@code false}: 平年 - */ - public static boolean isLeapYear(String time) { - return isLeapYear(string2Date(time, DEFAULT_PATTERN)); - } - - /** - * 判断是否闰年 - *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return {@code true}: 闰年
{@code false}: 平年 - */ - public static boolean isLeapYear(String time, String pattern) { - return isLeapYear(string2Date(time, pattern)); - } - - /** - * 判断是否闰年 - * - * @param date Date类型时间 - * @return {@code true}: 闰年
{@code false}: 平年 - */ - public static boolean isLeapYear(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - int year = cal.get(Calendar.YEAR); - return isLeapYear(year); - } - - /** - * 判断是否闰年 - * - * @param millis 毫秒时间戳 - * @return {@code true}: 闰年
{@code false}: 平年 - */ - public static boolean isLeapYear(long millis) { - return isLeapYear(millis2Date(millis)); - } - - /** - * 判断是否闰年 - * - * @param year 年份 - * @return {@code true}: 闰年
{@code false}: 平年 - */ - public static boolean isLeapYear(int year) { - return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; - } - - /** - * 获取星期 - *

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

- * - * @param time 时间字符串 - * @return 星期 - */ - public static String getWeek(String time) { - return getWeek(string2Date(time, DEFAULT_PATTERN)); - } - - /** - * 获取星期 - *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return 星期 - */ - public static String getWeek(String time, String pattern) { - return getWeek(string2Date(time, pattern)); - } - - /** - * 获取星期 - * - * @param date Date类型时间 - * @return 星期 - */ - public static String getWeek(Date date) { - return new SimpleDateFormat("EEEE", Locale.getDefault()).format(date); - } - - /** - * 获取星期 - * - * @param millis 毫秒时间戳 - * @return 星期 - */ - public static String getWeek(long millis) { - return getWeek(new Date(millis)); - } - - /** - * 获取星期 - *

注意:周日的Index才是1,周六为7

- *

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

- * - * @param time 时间字符串 - * @return 1...5 - */ - public static int getWeekIndex(String time) { - return getWeekIndex(string2Date(time, DEFAULT_PATTERN)); - } - - /** - * 获取星期 - *

注意:周日的Index才是1,周六为7

- *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return 1...7 - */ - public static int getWeekIndex(String time, String pattern) { - return getWeekIndex(string2Date(time, pattern)); - } - - /** - * 获取星期 - *

注意:周日的Index才是1,周六为7

- * - * @param date Date类型时间 - * @return 1...7 - */ - public static int getWeekIndex(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - return cal.get(Calendar.DAY_OF_WEEK); - } - - /** - * 获取星期 - *

注意:周日的Index才是1,周六为7

- * - * @param millis 毫秒时间戳 - * @return 1...7 - */ - public static int getWeekIndex(long millis) { - return getWeekIndex(millis2Date(millis)); - } - - /** - * 获取月份中的第几周 - *

注意:国外周日才是新的一周的开始

- *

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

- * - * @param time 时间字符串 - * @return 1...5 - */ - public static int getWeekOfMonth(String time) { - return getWeekOfMonth(string2Date(time, DEFAULT_PATTERN)); - } - - /** - * 获取月份中的第几周 - *

注意:国外周日才是新的一周的开始

- *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return 1...5 - */ - public static int getWeekOfMonth(String time, String pattern) { - return getWeekOfMonth(string2Date(time, pattern)); - } - - /** - * 获取月份中的第几周 - *

注意:国外周日才是新的一周的开始

- * - * @param date Date类型时间 - * @return 1...5 - */ - public static int getWeekOfMonth(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - return cal.get(Calendar.WEEK_OF_MONTH); - } - - /** - * 获取月份中的第几周 - *

注意:国外周日才是新的一周的开始

- * - * @param millis 毫秒时间戳 - * @return 1...5 - */ - public static int getWeekOfMonth(long millis) { - return getWeekOfMonth(millis2Date(millis)); - } - - /** - * 获取年份中的第几周 - *

注意:国外周日才是新的一周的开始

- *

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

- * - * @param time 时间字符串 - * @return 1...54 - */ - public static int getWeekOfYear(String time) { - return getWeekOfYear(string2Date(time, DEFAULT_PATTERN)); - } - - /** - * 获取年份中的第几周 - *

注意:国外周日才是新的一周的开始

- *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return 1...54 - */ - public static int getWeekOfYear(String time, String pattern) { - return getWeekOfYear(string2Date(time, pattern)); - } - - /** - * 获取年份中的第几周 - *

注意:国外周日才是新的一周的开始

- * - * @param date Date类型时间 - * @return 1...54 - */ - public static int getWeekOfYear(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - return cal.get(Calendar.WEEK_OF_YEAR); - } - - /** - * 获取年份中的第几周 - *

注意:国外周日才是新的一周的开始

- * - * @param millis 毫秒时间戳 - * @return 1...54 - */ - public static int getWeekOfYear(long millis) { - return getWeekOfYear(millis2Date(millis)); - } - - private static final String[] CHINESE_ZODIAC = {"猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊"}; - - /** - * 获取生肖 - *

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

- * - * @param time 时间字符串 - * @return 生肖 - */ - public static String getChineseZodiac(String time) { - return getChineseZodiac(string2Date(time, DEFAULT_PATTERN)); - } - - /** - * 获取生肖 - *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return 生肖 - */ - public static String getChineseZodiac(String time, String pattern) { - return getChineseZodiac(string2Date(time, pattern)); - } - - /** - * 获取生肖 - * - * @param date Date类型时间 - * @return 生肖 - */ - public static String getChineseZodiac(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - return CHINESE_ZODIAC[cal.get(Calendar.YEAR) % 12]; - } - - /** - * 获取生肖 - * - * @param millis 毫秒时间戳 - * @return 生肖 - */ - public static String getChineseZodiac(long millis) { - return getChineseZodiac(millis2Date(millis)); - } - - /** - * 获取生肖 - * - * @param year 年 - * @return 生肖 - */ - public static String getChineseZodiac(int year) { - return CHINESE_ZODIAC[year % 12]; - } - - private static final String[] ZODIAC = {"水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "魔羯座"}; - private static final int[] ZODIAC_FLAGS = {20, 19, 21, 21, 21, 22, 23, 23, 23, 24, 23, 22}; - - /** - * 获取星座 - *

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

- * - * @param time 时间字符串 - * @return 生肖 - */ - public static String getZodiac(String time) { - return getZodiac(string2Date(time, DEFAULT_PATTERN)); - } - - /** - * 获取星座 - *

time格式为pattern

- * - * @param time 时间字符串 - * @param pattern 时间格式 - * @return 生肖 - */ - public static String getZodiac(String time, String pattern) { - return getZodiac(string2Date(time, pattern)); - } - - /** - * 获取星座 - * - * @param date Date类型时间 - * @return 星座 - */ - public static String getZodiac(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - int month = cal.get(Calendar.MONTH) + 1; - int day = cal.get(Calendar.DAY_OF_MONTH); - return getZodiac(month, day); - } - - /** - * 获取星座 - * - * @param millis 毫秒时间戳 - * @return 星座 - */ - public static String getZodiac(long millis) { - return getZodiac(millis2Date(millis)); - } - - /** - * 获取星座 - * - * @param month 月 - * @param day 日 - * @return 星座 - */ - public static String getZodiac(int month, int day) { - return ZODIAC[day >= ZODIAC_FLAGS[month - 1] - ? month - 1 - : (month + 10) % 12]; - } +package com.ayvytr.easyandroidlibrary.tools; + +import android.annotation.SuppressLint; + +import com.ayvytr.easyandroidlibrary.consts.TimeConstant; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2016/8/2
+ *     desc  : 时间相关工具类
+ * 
+ */ +public class TimeTool +{ + + private TimeTool() + { + throw new UnsupportedOperationException("u can't instantiate me..."); + } + + /** + *

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

+ * 格式的意义如下: 日期和时间模式
+ *

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

+ * 定义了以下模式字母(所有其他字符 'A' 到 'Z' 和 'a' 到 'z' 都被保留):
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
字母日期或时间元素表示示例
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
+ *
+     *                          HH:mm    15:44
+     *                         h:mm a    3:44 下午
+     *                        HH:mm z    15:44 CST
+     *                        HH:mm Z    15:44 +0800
+     *                     HH:mm zzzz    15:44 中国标准时间
+     *                       HH:mm:ss    15:44:40
+     *                     yyyy-MM-dd    2016-08-12
+     *               yyyy-MM-dd HH:mm    2016-08-12 15:44
+     *            yyyy-MM-dd HH:mm:ss    2016-08-12 15:44:40
+     *       yyyy-MM-dd HH:mm:ss zzzz    2016-08-12 15:44:40 中国标准时间
+     *  EEEE yyyy-MM-dd HH:mm:ss zzzz    星期五 2016-08-12 15:44:40 中国标准时间
+     *       yyyy-MM-dd HH:mm:ss.SSSZ    2016-08-12 15:44:40.461+0800
+     *     yyyy-MM-dd'T'HH:mm:ss.SSSZ    2016-08-12T15:44:40.461+0800
+     *   yyyy.MM.dd G 'at' HH:mm:ss z    2016.08.12 公元 at 15:44:40 CST
+     *                         K:mm a    3:44 下午
+     *               EEE, MMM d, ''yy    星期五, 八月 12, '16
+     *          hh 'o''clock' a, zzzz    03 o'clock 下午, 中国标准时间
+     *   yyyyy.MMMMM.dd GGG hh:mm aaa    02016.八月.12 公元 03:44 下午
+     *     EEE, d MMM yyyy HH:mm:ss Z    星期五, 12 八月 2016 15:44:40 +0800
+     *                  yyMMddHHmmssZ    160812154440+0800
+     *     yyyy-MM-dd'T'HH:mm:ss.SSSZ    2016-08-12T15:44:40.461+0800
+     * EEEE 'DATE('yyyy-MM-dd')' 'TIME('HH:mm:ss')' zzzz    星期五 DATE(2016-08-12) TIME(15:44:40) 中国标准时间
+     * 
+ * 注意:SimpleDateFormat不是线程安全的,线程安全需用{@code ThreadLocal} + */ + public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss"; + + /** + * 将时间戳转为时间字符串 + *

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

+ * + * @param millis 毫秒时间戳 + * @return 时间字符串 + */ + public static String millis2String(long millis) + { + return new SimpleDateFormat(DEFAULT_PATTERN, Locale.getDefault()).format(new Date(millis)); + } + + /** + * 将时间戳转为时间字符串 + *

格式为pattern

+ * + * @param millis 毫秒时间戳 + * @param pattern 时间格式 + * @return 时间字符串 + */ + public static String millis2String(long millis, String pattern) + { + return new SimpleDateFormat(pattern, Locale.getDefault()).format(new Date(millis)); + } + + /** + * 将时间字符串转为时间戳 + *

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

+ * + * @param time 时间字符串 + * @return 毫秒时间戳 + */ + public static long string2Millis(String time) + { + return string2Millis(time, DEFAULT_PATTERN); + } + + /** + * 将时间字符串转为时间戳 + *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return 毫秒时间戳 + */ + public static long string2Millis(String time, String pattern) + { + try + { + return new SimpleDateFormat(pattern, Locale.getDefault()).parse(time).getTime(); + } catch(ParseException e) + { + e.printStackTrace(); + } + return -1; + } + + /** + * 将时间字符串转为Date类型 + *

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

+ * + * @param time 时间字符串 + * @return Date类型 + */ + public static Date string2Date(String time) + { + return string2Date(time, DEFAULT_PATTERN); + } + + /** + * 将时间字符串转为Date类型 + *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return Date类型 + */ + public static Date string2Date(String time, String pattern) + { + return new Date(string2Millis(time, pattern)); + } + + /** + * 将Date类型转为时间字符串 + *

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

+ * + * @param date Date类型时间 + * @return 时间字符串 + */ + public static String date2String(Date date) + { + return date2String(date, DEFAULT_PATTERN); + } + + /** + * 将Date类型转为时间字符串 + *

格式为pattern

+ * + * @param date Date类型时间 + * @param pattern 时间格式 + * @return 时间字符串 + */ + public static String date2String(Date date, String pattern) + { + return new SimpleDateFormat(pattern, Locale.getDefault()).format(date); + } + + /** + * 将Date类型转为时间戳 + * + * @param date Date类型时间 + * @return 毫秒时间戳 + */ + public static long date2Millis(Date date) + { + return date.getTime(); + } + + /** + * 将时间戳转为Date类型 + * + * @param millis 毫秒时间戳 + * @return Date类型时间 + */ + public static Date millis2Date(long millis) + { + return new Date(millis); + } + + /** + * 获取两个时间差(单位:unit) + *

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

+ * + * @param time0 时间字符串0 + * @param time1 时间字符串1 + * @param unit 单位类型 + *
    + *
  • {@link TimeConstant#MSEC}: 毫秒
  • + *
  • {@link TimeConstant#SEC }: 秒
  • + *
  • {@link TimeConstant#MIN }: 分
  • + *
  • {@link TimeConstant#HOUR}: 小时
  • + *
  • {@link TimeConstant#DAY }: 天
  • + *
+ * @return unit时间戳 + */ + public static long getTimeSpan(String time0, String time1, @TimeConstant.Unit int unit) + { + return getTimeSpan(time0, time1, unit, DEFAULT_PATTERN); + } + + /** + * 获取两个时间差(单位:unit) + *

time0和time1格式都为format

+ * + * @param time0 时间字符串0 + * @param time1 时间字符串1 + * @param unit 单位类型 + *
    + *
  • {@link TimeConstant#MSEC}: 毫秒
  • + *
  • {@link TimeConstant#SEC }: 秒
  • + *
  • {@link TimeConstant#MIN }: 分
  • + *
  • {@link TimeConstant#HOUR}: 小时
  • + *
  • {@link TimeConstant#DAY }: 天
  • + *
+ * @param pattern 时间格式 + * @return unit时间戳 + */ + public static long getTimeSpan(String time0, String time1, @TimeConstant.Unit int unit, + String pattern) + { + return ConvertTool.millis2TimeSpan( + Math.abs(string2Millis(time0, pattern) - string2Millis(time1, pattern)), unit); + } + + /** + * 获取两个时间差(单位:unit) + * + * @param date0 Date类型时间0 + * @param date1 Date类型时间1 + * @param unit 单位类型 + *
    + *
  • {@link TimeConstant#MSEC}: 毫秒
  • + *
  • {@link TimeConstant#SEC }: 秒
  • + *
  • {@link TimeConstant#MIN }: 分
  • + *
  • {@link TimeConstant#HOUR}: 小时
  • + *
  • {@link TimeConstant#DAY }: 天
  • + *
+ * @return unit时间戳 + */ + public static long getTimeSpan(Date date0, Date date1, @TimeConstant.Unit int unit) + { + return ConvertTool.millis2TimeSpan(Math.abs(date2Millis(date0) - date2Millis(date1)), unit); + } + + /** + * 获取两个时间差(单位:unit) + * + * @param millis0 毫秒时间戳0 + * @param millis1 毫秒时间戳1 + * @param unit 单位类型 + *
    + *
  • {@link TimeConstant#MSEC}: 毫秒
  • + *
  • {@link TimeConstant#SEC }: 秒
  • + *
  • {@link TimeConstant#MIN }: 分
  • + *
  • {@link TimeConstant#HOUR}: 小时
  • + *
  • {@link TimeConstant#DAY }: 天
  • + *
+ * @return unit时间戳 + */ + public static long getTimeSpan(long millis0, long millis1, @TimeConstant.Unit int unit) + { + return ConvertTool.millis2TimeSpan(Math.abs(millis0 - millis1), unit); + } + + /** + * 获取合适型两个时间差 + *

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

+ * + * @param time0 时间字符串0 + * @param time1 时间字符串1 + * @param precision 精度 + *

precision = 0,返回null

+ *

precision = 1,返回天

+ *

precision = 2,返回天和小时

+ *

precision = 3,返回天、小时和分钟

+ *

precision = 4,返回天、小时、分钟和秒

+ *

precision >= 5,返回天、小时、分钟、秒和毫秒

+ * @return 合适型两个时间差 + */ + public static String getFitTimeSpan(String time0, String time1, int precision) + { + return ConvertTool.millis2FitTimeSpan(Math.abs( + string2Millis(time0, DEFAULT_PATTERN) - string2Millis(time1, DEFAULT_PATTERN)), + precision); + } + + /** + * 获取合适型两个时间差 + *

time0和time1格式都为pattern

+ * + * @param time0 时间字符串0 + * @param time1 时间字符串1 + * @param precision 精度 + *

precision = 0,返回null

+ *

precision = 1,返回天

+ *

precision = 2,返回天和小时

+ *

precision = 3,返回天、小时和分钟

+ *

precision = 4,返回天、小时、分钟和秒

+ *

precision >= 5,返回天、小时、分钟、秒和毫秒

+ * @param pattern 时间格式 + * @return 合适型两个时间差 + */ + public static String getFitTimeSpan(String time0, String time1, int precision, String pattern) + { + return ConvertTool.millis2FitTimeSpan( + Math.abs(string2Millis(time0, pattern) - string2Millis(time1, pattern)), precision); + } + + /** + * 获取合适型两个时间差 + * + * @param date0 Date类型时间0 + * @param date1 Date类型时间1 + * @param precision 精度 + *

precision = 0,返回null

+ *

precision = 1,返回天

+ *

precision = 2,返回天和小时

+ *

precision = 3,返回天、小时和分钟

+ *

precision = 4,返回天、小时、分钟和秒

+ *

precision >= 5,返回天、小时、分钟、秒和毫秒

+ * @return 合适型两个时间差 + */ + public static String getFitTimeSpan(Date date0, Date date1, int precision) + { + return ConvertTool + .millis2FitTimeSpan(Math.abs(date2Millis(date0) - date2Millis(date1)), precision); + } + + /** + * 获取合适型两个时间差 + * + * @param millis0 毫秒时间戳1 + * @param millis1 毫秒时间戳2 + * @param precision 精度 + *

precision = 0,返回null

+ *

precision = 1,返回天

+ *

precision = 2,返回天和小时

+ *

precision = 3,返回天、小时和分钟

+ *

precision = 4,返回天、小时、分钟和秒

+ *

precision >= 5,返回天、小时、分钟、秒和毫秒

+ * @return 合适型两个时间差 + */ + public static String getFitTimeSpan(long millis0, long millis1, int precision) + { + return ConvertTool.millis2FitTimeSpan(Math.abs(millis0 - millis1), precision); + } + + /** + * 获取当前毫秒时间戳 + * + * @return 毫秒时间戳 + */ + public static long getNowTimeMills() + { + return System.currentTimeMillis(); + } + + /** + * 获取当前时间字符串 + *

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

+ * + * @return 时间字符串 + */ + public static String getNowTimeString() + { + return millis2String(System.currentTimeMillis(), DEFAULT_PATTERN); + } + + /** + * 获取当前时间字符串 + *

格式为pattern

+ * + * @param pattern 时间格式 + * @return 时间字符串 + */ + public static String getNowTimeString(String pattern) + { + return millis2String(System.currentTimeMillis(), pattern); + } + + /** + * 获取当前Date + * + * @return Date类型时间 + */ + public static Date getNowTimeDate() + { + return new Date(); + } + + /** + * 获取与当前时间的差(单位:unit) + *

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

+ * + * @param time 时间字符串 + * @param unit 单位类型 + *
    + *
  • {@link TimeConstant#MSEC}: 毫秒
  • + *
  • {@link TimeConstant#SEC }: 秒
  • + *
  • {@link TimeConstant#MIN }: 分
  • + *
  • {@link TimeConstant#HOUR}: 小时
  • + *
  • {@link TimeConstant#DAY }: 天
  • + *
+ * @return unit时间戳 + */ + public static long getTimeSpanByNow(String time, @TimeConstant.Unit int unit) + { + return getTimeSpan(getNowTimeString(), time, unit, DEFAULT_PATTERN); + } + + /** + * 获取与当前时间的差(单位:unit) + *

time格式为pattern

+ * + * @param time 时间字符串 + * @param unit 单位类型 + *
    + *
  • {@link TimeConstant#MSEC}: 毫秒
  • + *
  • {@link TimeConstant#SEC }: 秒
  • + *
  • {@link TimeConstant#MIN }: 分
  • + *
  • {@link TimeConstant#HOUR}: 小时
  • + *
  • {@link TimeConstant#DAY }: 天
  • + *
+ * @param pattern 时间格式 + * @return unit时间戳 + */ + public static long getTimeSpanByNow(String time, @TimeConstant.Unit int unit, String pattern) + { + return getTimeSpan(getNowTimeString(), time, unit, pattern); + } + + /** + * 获取与当前时间的差(单位:unit) + * + * @param date Date类型时间 + * @param unit 单位类型 + *
    + *
  • {@link TimeConstant#MSEC}: 毫秒
  • + *
  • {@link TimeConstant#SEC }: 秒
  • + *
  • {@link TimeConstant#MIN }: 分
  • + *
  • {@link TimeConstant#HOUR}: 小时
  • + *
  • {@link TimeConstant#DAY }: 天
  • + *
+ * @return unit时间戳 + */ + public static long getTimeSpanByNow(Date date, @TimeConstant.Unit int unit) + { + return getTimeSpan(new Date(), date, unit); + } + + /** + * 获取与当前时间的差(单位:unit) + * + * @param millis 毫秒时间戳 + * @param unit 单位类型 + *
    + *
  • {@link TimeConstant#MSEC}: 毫秒
  • + *
  • {@link TimeConstant#SEC }: 秒
  • + *
  • {@link TimeConstant#MIN }: 分
  • + *
  • {@link TimeConstant#HOUR}: 小时
  • + *
  • {@link TimeConstant#DAY }: 天
  • + *
+ * @return unit时间戳 + */ + public static long getTimeSpanByNow(long millis, @TimeConstant.Unit int unit) + { + return getTimeSpan(System.currentTimeMillis(), millis, unit); + } + + /** + * 获取合适型与当前时间的差 + *

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

+ * + * @param time 时间字符串 + * @param precision 精度 + *
    + *
  • precision = 0,返回null
  • + *
  • precision = 1,返回天
  • + *
  • precision = 2,返回天和小时
  • + *
  • precision = 3,返回天、小时和分钟
  • + *
  • precision = 4,返回天、小时、分钟和秒
  • + *
  • precision >= 5,返回天、小时、分钟、秒和毫秒
  • + *
+ * @return 合适型与当前时间的差 + */ + public static String getFitTimeSpanByNow(String time, int precision) + { + return getFitTimeSpan(getNowTimeString(), time, precision, DEFAULT_PATTERN); + } + + /** + * 获取合适型与当前时间的差 + *

time格式为pattern

+ * + * @param time 时间字符串 + * @param precision 精度 + * @param pattern 时间格式 + *
    + *
  • precision = 0,返回null
  • + *
  • precision = 1,返回天
  • + *
  • precision = 2,返回天和小时
  • + *
  • precision = 3,返回天、小时和分钟
  • + *
  • precision = 4,返回天、小时、分钟和秒
  • + *
  • precision >= 5,返回天、小时、分钟、秒和毫秒
  • + *
+ * @return 合适型与当前时间的差 + */ + public static String getFitTimeSpanByNow(String time, int precision, String pattern) + { + return getFitTimeSpan(getNowTimeString(), time, precision, pattern); + } + + /** + * 获取合适型与当前时间的差 + * + * @param date Date类型时间 + * @param precision 精度 + *
    + *
  • precision = 0,返回null
  • + *
  • precision = 1,返回天
  • + *
  • precision = 2,返回天和小时
  • + *
  • precision = 3,返回天、小时和分钟
  • + *
  • precision = 4,返回天、小时、分钟和秒
  • + *
  • precision >= 5,返回天、小时、分钟、秒和毫秒
  • + *
+ * @return 合适型与当前时间的差 + */ + public static String getFitTimeSpanByNow(Date date, int precision) + { + return getFitTimeSpan(getNowTimeDate(), date, precision); + } + + /** + * 获取合适型与当前时间的差 + * + * @param millis 毫秒时间戳 + * @param precision 精度 + *
    + *
  • precision = 0,返回null
  • + *
  • precision = 1,返回天
  • + *
  • precision = 2,返回天和小时
  • + *
  • precision = 3,返回天、小时和分钟
  • + *
  • precision = 4,返回天、小时、分钟和秒
  • + *
  • precision >= 5,返回天、小时、分钟、秒和毫秒
  • + *
+ * @return 合适型与当前时间的差 + */ + public static String getFitTimeSpanByNow(long millis, int precision) + { + return getFitTimeSpan(System.currentTimeMillis(), millis, precision); + } + + /** + * 获取友好型与当前时间的差 + *

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

+ * + * @param time 时间字符串 + * @return 友好型与当前时间的差 + *
    + *
  • 如果小于1秒钟内,显示刚刚
  • + *
  • 如果在1分钟内,显示XXX秒前
  • + *
  • 如果在1小时内,显示XXX分钟前
  • + *
  • 如果在1小时外的今天内,显示今天15:32
  • + *
  • 如果是昨天的,显示昨天15:32
  • + *
  • 其余显示,2016-10-15
  • + *
  • 时间不合法的情况全部日期和时间信息,如星期六 十月 27 14:21:20 CST 2007
  • + *
+ */ + public static String getFriendlyTimeSpanByNow(String time) + { + return getFriendlyTimeSpanByNow(time, DEFAULT_PATTERN); + } + + /** + * 获取友好型与当前时间的差 + *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return 友好型与当前时间的差 + *
    + *
  • 如果小于1秒钟内,显示刚刚
  • + *
  • 如果在1分钟内,显示XXX秒前
  • + *
  • 如果在1小时内,显示XXX分钟前
  • + *
  • 如果在1小时外的今天内,显示今天15:32
  • + *
  • 如果是昨天的,显示昨天15:32
  • + *
  • 其余显示,2016-10-15
  • + *
  • 时间不合法的情况全部日期和时间信息,如星期六 十月 27 14:21:20 CST 2007
  • + *
+ */ + public static String getFriendlyTimeSpanByNow(String time, String pattern) + { + return getFriendlyTimeSpanByNow(string2Millis(time, pattern)); + } + + /** + * 获取友好型与当前时间的差 + * + * @param date Date类型时间 + * @return 友好型与当前时间的差 + *
    + *
  • 如果小于1秒钟内,显示刚刚
  • + *
  • 如果在1分钟内,显示XXX秒前
  • + *
  • 如果在1小时内,显示XXX分钟前
  • + *
  • 如果在1小时外的今天内,显示今天15:32
  • + *
  • 如果是昨天的,显示昨天15:32
  • + *
  • 其余显示,2016-10-15
  • + *
  • 时间不合法的情况全部日期和时间信息,如星期六 十月 27 14:21:20 CST 2007
  • + *
+ */ + public static String getFriendlyTimeSpanByNow(Date date) + { + return getFriendlyTimeSpanByNow(date.getTime()); + } + + /** + * 获取友好型与当前时间的差 + * + * @param millis 毫秒时间戳 + * @return 友好型与当前时间的差 + *
    + *
  • 如果小于1秒钟内,显示刚刚
  • + *
  • 如果在1分钟内,显示XXX秒前
  • + *
  • 如果在1小时内,显示XXX分钟前
  • + *
  • 如果在1小时外的今天内,显示今天15:32
  • + *
  • 如果是昨天的,显示昨天15:32
  • + *
  • 其余显示,2016-10-15
  • + *
  • 时间不合法的情况全部日期和时间信息,如星期六 十月 27 14:21:20 CST 2007
  • + *
+ */ + @SuppressLint("DefaultLocale") + public static String getFriendlyTimeSpanByNow(long millis) + { + long now = System.currentTimeMillis(); + long span = now - millis; + if(span < 0) + { + return String.format("%tc", + millis);// U can read http://www.apihome.cn/api/java/Formatter.html to understand it. + } + if(span < 1000) + { + return "刚刚"; + } + else if(span < TimeConstant.MIN) + { + return String.format("%d秒前", span / TimeConstant.SEC); + } + else if(span < TimeConstant.HOUR) + { + return String.format("%d分钟前", span / TimeConstant.MIN); + } + // 获取当天00:00 + long wee = (now / TimeConstant.DAY) * TimeConstant.DAY - 8 * TimeConstant.HOUR; + if(millis >= wee) + { + return String.format("今天%tR", millis); + } + else if(millis >= wee - TimeConstant.DAY) + { + return String.format("昨天%tR", millis); + } + else + { + return String.format("%tF", millis); + } + } + + /** + * 判断是否同一天 + *

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

+ * + * @param time 时间字符串 + * @return {@code true}: 是
{@code false}: 否 + */ + public static boolean isSameDay(String time) + { + return isSameDay(string2Millis(time, DEFAULT_PATTERN)); + } + + /** + * 判断是否同一天 + *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return {@code true}: 是
{@code false}: 否 + */ + public static boolean isSameDay(String time, String pattern) + { + return isSameDay(string2Millis(time, pattern)); + } + + /** + * 判断是否同一天 + * + * @param date Date类型时间 + * @return {@code true}: 是
{@code false}: 否 + */ + public static boolean isSameDay(Date date) + { + return isSameDay(date.getTime()); + } + + /** + * 判断是否同一天 + * + * @param millis 毫秒时间戳 + * @return {@code true}: 是
{@code false}: 否 + */ + public static boolean isSameDay(long millis) + { + long wee = (System + .currentTimeMillis() / TimeConstant.DAY) * TimeConstant.DAY - 8 * TimeConstant.HOUR; + return millis >= wee && millis < wee + TimeConstant.DAY; + } + + /** + * 判断是否闰年 + *

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

+ * + * @param time 时间字符串 + * @return {@code true}: 闰年
{@code false}: 平年 + */ + public static boolean isLeapYear(String time) + { + return isLeapYear(string2Date(time, DEFAULT_PATTERN)); + } + + /** + * 判断是否闰年 + *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return {@code true}: 闰年
{@code false}: 平年 + */ + public static boolean isLeapYear(String time, String pattern) + { + return isLeapYear(string2Date(time, pattern)); + } + + /** + * 判断是否闰年 + * + * @param date Date类型时间 + * @return {@code true}: 闰年
{@code false}: 平年 + */ + public static boolean isLeapYear(Date date) + { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int year = cal.get(Calendar.YEAR); + return isLeapYear(year); + } + + /** + * 判断是否闰年 + * + * @param millis 毫秒时间戳 + * @return {@code true}: 闰年
{@code false}: 平年 + */ + public static boolean isLeapYear(long millis) + { + return isLeapYear(millis2Date(millis)); + } + + /** + * 判断是否闰年 + * + * @param year 年份 + * @return {@code true}: 闰年
{@code false}: 平年 + */ + public static boolean isLeapYear(int year) + { + return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; + } + + /** + * 获取星期 + *

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

+ * + * @param time 时间字符串 + * @return 星期 + */ + public static String getWeek(String time) + { + return getWeek(string2Date(time, DEFAULT_PATTERN)); + } + + /** + * 获取星期 + *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return 星期 + */ + public static String getWeek(String time, String pattern) + { + return getWeek(string2Date(time, pattern)); + } + + /** + * 获取星期 + * + * @param date Date类型时间 + * @return 星期 + */ + public static String getWeek(Date date) + { + return new SimpleDateFormat("EEEE", Locale.getDefault()).format(date); + } + + /** + * 获取星期 + * + * @param millis 毫秒时间戳 + * @return 星期 + */ + public static String getWeek(long millis) + { + return getWeek(new Date(millis)); + } + + /** + * 获取星期 + *

注意:周日的Index才是1,周六为7

+ *

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

+ * + * @param time 时间字符串 + * @return 1...5 + */ + public static int getWeekIndex(String time) + { + return getWeekIndex(string2Date(time, DEFAULT_PATTERN)); + } + + /** + * 获取星期 + *

注意:周日的Index才是1,周六为7

+ *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return 1...7 + */ + public static int getWeekIndex(String time, String pattern) + { + return getWeekIndex(string2Date(time, pattern)); + } + + /** + * 获取星期 + *

注意:周日的Index才是1,周六为7

+ * + * @param date Date类型时间 + * @return 1...7 + */ + public static int getWeekIndex(Date date) + { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal.get(Calendar.DAY_OF_WEEK); + } + + /** + * 获取星期 + *

注意:周日的Index才是1,周六为7

+ * + * @param millis 毫秒时间戳 + * @return 1...7 + */ + public static int getWeekIndex(long millis) + { + return getWeekIndex(millis2Date(millis)); + } + + /** + * 获取月份中的第几周 + *

注意:国外周日才是新的一周的开始

+ *

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

+ * + * @param time 时间字符串 + * @return 1...5 + */ + public static int getWeekOfMonth(String time) + { + return getWeekOfMonth(string2Date(time, DEFAULT_PATTERN)); + } + + /** + * 获取月份中的第几周 + *

注意:国外周日才是新的一周的开始

+ *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return 1...5 + */ + public static int getWeekOfMonth(String time, String pattern) + { + return getWeekOfMonth(string2Date(time, pattern)); + } + + /** + * 获取月份中的第几周 + *

注意:国外周日才是新的一周的开始

+ * + * @param date Date类型时间 + * @return 1...5 + */ + public static int getWeekOfMonth(Date date) + { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal.get(Calendar.WEEK_OF_MONTH); + } + + /** + * 获取月份中的第几周 + *

注意:国外周日才是新的一周的开始

+ * + * @param millis 毫秒时间戳 + * @return 1...5 + */ + public static int getWeekOfMonth(long millis) + { + return getWeekOfMonth(millis2Date(millis)); + } + + /** + * 获取年份中的第几周 + *

注意:国外周日才是新的一周的开始

+ *

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

+ * + * @param time 时间字符串 + * @return 1...54 + */ + public static int getWeekOfYear(String time) + { + return getWeekOfYear(string2Date(time, DEFAULT_PATTERN)); + } + + /** + * 获取年份中的第几周 + *

注意:国外周日才是新的一周的开始

+ *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return 1...54 + */ + public static int getWeekOfYear(String time, String pattern) + { + return getWeekOfYear(string2Date(time, pattern)); + } + + /** + * 获取年份中的第几周 + *

注意:国外周日才是新的一周的开始

+ * + * @param date Date类型时间 + * @return 1...54 + */ + public static int getWeekOfYear(Date date) + { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal.get(Calendar.WEEK_OF_YEAR); + } + + /** + * 获取年份中的第几周 + *

注意:国外周日才是新的一周的开始

+ * + * @param millis 毫秒时间戳 + * @return 1...54 + */ + public static int getWeekOfYear(long millis) + { + return getWeekOfYear(millis2Date(millis)); + } + + private static final String[] CHINESE_ZODIAC = {"猴", + "鸡", + "狗", + "猪", + "鼠", + "牛", + "虎", + "兔", + "龙", + "蛇", + "马", + "羊"}; + + /** + * 获取生肖 + *

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

+ * + * @param time 时间字符串 + * @return 生肖 + */ + public static String getChineseZodiac(String time) + { + return getChineseZodiac(string2Date(time, DEFAULT_PATTERN)); + } + + /** + * 获取生肖 + *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return 生肖 + */ + public static String getChineseZodiac(String time, String pattern) + { + return getChineseZodiac(string2Date(time, pattern)); + } + + /** + * 获取生肖 + * + * @param date Date类型时间 + * @return 生肖 + */ + public static String getChineseZodiac(Date date) + { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return CHINESE_ZODIAC[cal.get(Calendar.YEAR) % 12]; + } + + /** + * 获取生肖 + * + * @param millis 毫秒时间戳 + * @return 生肖 + */ + public static String getChineseZodiac(long millis) + { + return getChineseZodiac(millis2Date(millis)); + } + + /** + * 获取生肖 + * + * @param year 年 + * @return 生肖 + */ + public static String getChineseZodiac(int year) + { + return CHINESE_ZODIAC[year % 12]; + } + + private static final String[] ZODIAC = {"水瓶座", + "双鱼座", + "白羊座", + "金牛座", + "双子座", + "巨蟹座", + "狮子座", + "处女座", + "天秤座", + "天蝎座", + "射手座", + "魔羯座"}; + private static final int[] ZODIAC_FLAGS = {20, 19, 21, 21, 21, 22, 23, 23, 23, 24, 23, 22}; + + /** + * 获取星座 + *

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

+ * + * @param time 时间字符串 + * @return 生肖 + */ + public static String getZodiac(String time) + { + return getZodiac(string2Date(time, DEFAULT_PATTERN)); + } + + /** + * 获取星座 + *

time格式为pattern

+ * + * @param time 时间字符串 + * @param pattern 时间格式 + * @return 生肖 + */ + public static String getZodiac(String time, String pattern) + { + return getZodiac(string2Date(time, pattern)); + } + + /** + * 获取星座 + * + * @param date Date类型时间 + * @return 星座 + */ + public static String getZodiac(Date date) + { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int month = cal.get(Calendar.MONTH) + 1; + int day = cal.get(Calendar.DAY_OF_MONTH); + return getZodiac(month, day); + } + + /** + * 获取星座 + * + * @param millis 毫秒时间戳 + * @return 星座 + */ + public static String getZodiac(long millis) + { + return getZodiac(millis2Date(millis)); + } + + /** + * 获取星座 + * + * @param month 月 + * @param day 日 + * @return 星座 + */ + public static String getZodiac(int month, int day) + { + return ZODIAC[day >= ZODIAC_FLAGS[month - 1] + ? month - 1 + : (month + 10) % 12]; + } } \ No newline at end of file diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/BarTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/BarTool.java similarity index 96% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/BarTool.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/BarTool.java index 5d06a17..db76b74 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/BarTool.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/BarTool.java @@ -1,844 +1,844 @@ -package com.ayvytr.easydeveloper.tools.withcontext; - -import android.annotation.TargetApi; -import android.app.Activity; -import android.content.Context; -import android.graphics.Color; -import android.os.Build; -import android.support.v4.widget.DrawerLayout; -import android.util.AttributeSet; -import android.util.TypedValue; -import android.view.View; -import android.view.ViewGroup; -import android.view.Window; -import android.view.WindowManager; -import android.widget.LinearLayout; - -import com.ayvytr.easydeveloper.exception.UnsupportedInitializationException; - -import java.lang.reflect.Method; - -/** - * StatusBar, ActionBar等相关工具类 - */ -public class BarTool -{ - - private BarTool() - { - throw new UnsupportedInitializationException(); - } - - public static class StatusBarView extends View - { - public StatusBarView(Context context, AttributeSet attrs) - { - super(context, attrs); - } - - public StatusBarView(Context context) - { - super(context); - } - } - - public static final int DEFAULT_STATUS_BAR_ALPHA = 112; - - /** - * 设置状态栏颜色 - * - * @param activity 需要设置的 activity - * @param color 状态栏颜色值 - */ - public static void setColor(Activity activity, int color) - { - setColor(activity, color, DEFAULT_STATUS_BAR_ALPHA); - } - - /** - * 设置状态栏颜色 - * - * @param activity 需要设置的activity - * @param color 状态栏颜色值 - * @param statusBarAlpha 状态栏透明度 - */ - - public static void setColor(Activity activity, int color, int statusBarAlpha) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) - { - activity.getWindow() - .addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - activity.getWindow().setStatusBarColor(calculateStatusColor(color, statusBarAlpha)); - } - else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) - { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); - int count = decorView.getChildCount(); - if(count > 0 && decorView.getChildAt(count - 1) instanceof StatusBarView) - { - decorView.getChildAt(count - 1) - .setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); - } - else - { - StatusBarView statusView = createStatusBarView(activity, color, statusBarAlpha); - decorView.addView(statusView); - } - setRootView(activity); - } - } - - /** - * 为滑动返回界面设置状态栏颜色 - * - * @param activity 需要设置的activity - * @param color 状态栏颜色值 - */ - public static void setColorForSwipeBack(Activity activity, int color) - { - setColorForSwipeBack(activity, color, DEFAULT_STATUS_BAR_ALPHA); - } - - /** - * 为滑动返回界面设置状态栏颜色 - * - * @param activity 需要设置的activity - * @param color 状态栏颜色值 - * @param statusBarAlpha 状态栏透明度 - */ - public static void setColorForSwipeBack(Activity activity, int color, int statusBarAlpha) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) - { - ViewGroup contentView = ((ViewGroup) activity.findViewById(android.R.id.content)); - contentView.setPadding(0, getStatusBarHeight(activity), 0, 0); - contentView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); - setTransparentForWindow(activity); - } - } - - /** - * 设置状态栏纯色 不加半透明效果 - * - * @param activity 需要设置的 activity - * @param color 状态栏颜色值 - */ - public static void setColorNoTranslucent(Activity activity, int color) - { - setColor(activity, color, 0); - } - - /** - * 设置状态栏颜色(5.0以下无半透明效果,不建议使用) - * - * @param activity 需要设置的 activity - * @param color 状态栏颜色值 - */ - @Deprecated - public static void setColorDiff(Activity activity, int color) - { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) - { - return; - } - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - // 生成一个状态栏大小的矩形 - ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); - int count = decorView.getChildCount(); - if(count > 0 && decorView.getChildAt(count - 1) instanceof StatusBarView) - { - decorView.getChildAt(count - 1).setBackgroundColor(color); - } - else - { - StatusBarView statusView = createStatusBarView(activity, color); - decorView.addView(statusView); - } - setRootView(activity); - } - - /** - * 使状态栏半透明 - * 适用于图片作为背景的界面,此时需要图片填充到状态栏 - * - * @param activity 需要设置的activity - */ - public static void setTranslucent(Activity activity) - { - setTranslucent(activity, DEFAULT_STATUS_BAR_ALPHA); - } - - /** - * 使状态栏半透明 - *

- * 适用于图片作为背景的界面,此时需要图片填充到状态栏 - * - * @param activity 需要设置的activity - * @param statusBarAlpha 状态栏透明度 - */ - public static void setTranslucent(Activity activity, int statusBarAlpha) - { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) - { - return; - } - setTransparent(activity); - addTranslucentView(activity, statusBarAlpha); - } - - /** - * 针对根布局是 CoordinatorLayout, 使状态栏半透明 - *

- * 适用于图片作为背景的界面,此时需要图片填充到状态栏 - * - * @param activity 需要设置的activity - * @param statusBarAlpha 状态栏透明度 - */ - public static void setTranslucentForCoordinatorLayout(Activity activity, int statusBarAlpha) - { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) - { - return; - } - transparentStatusBar(activity); - addTranslucentView(activity, statusBarAlpha); - } - - /** - * 设置状态栏全透明 - * - * @param activity 需要设置的activity - */ - public static void setTransparent(Activity activity) - { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) - { - return; - } - transparentStatusBar(activity); - setRootView(activity); - } - - /** - * 使状态栏透明(5.0以上半透明效果,不建议使用) - *

- * 适用于图片作为背景的界面,此时需要图片填充到状态栏 - * - * @param activity 需要设置的activity - */ - @Deprecated - public static void setTranslucentDiff(Activity activity) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) - { - // 设置状态栏透明 - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - setRootView(activity); - } - } - - /** - * 为DrawerLayout 布局设置状态栏变色 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - * @param color 状态栏颜色值 - */ - public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, - int color) - { - setColorForDrawerLayout(activity, drawerLayout, color, DEFAULT_STATUS_BAR_ALPHA); - } - - /** - * 为DrawerLayout 布局设置状态栏颜色,纯色 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - * @param color 状态栏颜色值 - */ - public static void setColorNoTranslucentForDrawerLayout(Activity activity, - DrawerLayout drawerLayout, int color) - { - setColorForDrawerLayout(activity, drawerLayout, color, 0); - } - - /** - * 为DrawerLayout 布局设置状态栏变色 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - * @param color 状态栏颜色值 - * @param statusBarAlpha 状态栏透明度 - */ - public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, - int color, - int statusBarAlpha) - { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) - { - return; - } - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) - { - activity.getWindow() - .addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - activity.getWindow().setStatusBarColor(Color.TRANSPARENT); - } - else - { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - } - // 生成一个状态栏大小的矩形 - // 添加 statusBarView 到布局中 - ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); - if(contentLayout.getChildCount() > 0 && contentLayout - .getChildAt(0) instanceof StatusBarView) - { - contentLayout.getChildAt(0) - .setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); - } - else - { - StatusBarView statusBarView = createStatusBarView(activity, color); - contentLayout.addView(statusBarView, 0); - } - // 内容布局不是 LinearLayout 时,设置padding top - if(!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) - { - contentLayout.getChildAt(1) - .setPadding(contentLayout.getPaddingLeft(), - getStatusBarHeight(activity) + contentLayout.getPaddingTop(), - contentLayout.getPaddingRight(), contentLayout.getPaddingBottom()); - } - // 设置属性 - ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); - drawerLayout.setFitsSystemWindows(false); - contentLayout.setFitsSystemWindows(false); - contentLayout.setClipToPadding(true); - drawer.setFitsSystemWindows(false); - - addTranslucentView(activity, statusBarAlpha); - } - - /** - * 为DrawerLayout 布局设置状态栏变色(5.0以下无半透明效果,不建议使用) - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - * @param color 状态栏颜色值 - */ - @Deprecated - public static void setColorForDrawerLayoutDiff(Activity activity, DrawerLayout drawerLayout, - int color) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) - { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - // 生成一个状态栏大小的矩形 - ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); - if(contentLayout.getChildCount() > 0 && contentLayout - .getChildAt(0) instanceof StatusBarView) - { - contentLayout.getChildAt(0).setBackgroundColor( - calculateStatusColor(color, DEFAULT_STATUS_BAR_ALPHA)); - } - else - { - // 添加 statusBarView 到布局中 - StatusBarView statusBarView = createStatusBarView(activity, color); - contentLayout.addView(statusBarView, 0); - } - // 内容布局不是 LinearLayout 时,设置padding top - if(!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) - { - contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0); - } - // 设置属性 - ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); - drawerLayout.setFitsSystemWindows(false); - contentLayout.setFitsSystemWindows(false); - contentLayout.setClipToPadding(true); - drawer.setFitsSystemWindows(false); - } - } - - /** - * 为 DrawerLayout 布局设置状态栏透明 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - */ - public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) - { - setTranslucentForDrawerLayout(activity, drawerLayout, DEFAULT_STATUS_BAR_ALPHA); - } - - /** - * 为 DrawerLayout 布局设置状态栏透明 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - * @param statusBarAlpha 透明度 - */ - public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, - int statusBarAlpha) - { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) - { - return; - } - setTransparentForDrawerLayout(activity, drawerLayout); - addTranslucentView(activity, statusBarAlpha); - } - - /** - * 为 DrawerLayout 布局设置状态栏透明 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - */ - public static void setTransparentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) - { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) - { - return; - } - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) - { - activity.getWindow() - .addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - activity.getWindow().setStatusBarColor(Color.TRANSPARENT); - } - else - { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - } - - ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); - // 内容布局不是 LinearLayout 时,设置padding top - if(!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) - { - contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0); - } - - // 设置属性 - ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); - drawerLayout.setFitsSystemWindows(false); - contentLayout.setFitsSystemWindows(false); - contentLayout.setClipToPadding(true); - drawer.setFitsSystemWindows(false); - } - - /** - * 为 DrawerLayout 布局设置状态栏透明(5.0以上半透明效果,不建议使用) - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - */ - @Deprecated - public static void setTranslucentForDrawerLayoutDiff(Activity activity, - DrawerLayout drawerLayout) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) - { - // 设置状态栏透明 - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - // 设置内容布局属性 - ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); - contentLayout.setFitsSystemWindows(true); - contentLayout.setClipToPadding(true); - // 设置抽屉布局属性 - ViewGroup vg = (ViewGroup) drawerLayout.getChildAt(1); - vg.setFitsSystemWindows(false); - // 设置 DrawerLayout 属性 - drawerLayout.setFitsSystemWindows(false); - } - } - - /** - * 为头部是 ImageView 的界面设置状态栏全透明 - * - * @param activity 需要设置的activity - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTransparentForImageView(Activity activity, View needOffsetView) - { - setTranslucentForImageView(activity, 0, needOffsetView); - } - - /** - * 为头部是 ImageView 的界面设置状态栏透明(使用默认透明度) - * - * @param activity 需要设置的activity - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTranslucentForImageView(Activity activity, View needOffsetView) - { - setTranslucentForImageView(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView); - } - - /** - * 为头部是 ImageView 的界面设置状态栏透明 - * - * @param activity 需要设置的activity - * @param statusBarAlpha 状态栏透明度 - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTranslucentForImageView(Activity activity, int statusBarAlpha, - View needOffsetView) - { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) - { - return; - } - setTransparentForWindow(activity); - addTranslucentView(activity, statusBarAlpha); - if(needOffsetView != null) - { - ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) needOffsetView - .getLayoutParams(); - layoutParams.setMargins(0, getStatusBarHeight(activity), 0, 0); - } - } - - /** - * 为 fragment 头部是 ImageView 的设置状态栏透明 - * - * @param activity fragment 对应的 activity - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTranslucentForImageViewInFragment(Activity activity, View needOffsetView) - { - setTranslucentForImageViewInFragment(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView); - } - - /** - * 为 fragment 头部是 ImageView 的设置状态栏透明 - * - * @param activity fragment 对应的 activity - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTransparentForImageViewInFragment(Activity activity, View needOffsetView) - { - setTranslucentForImageViewInFragment(activity, 0, needOffsetView); - } - - /** - * 为 fragment 头部是 ImageView 的设置状态栏透明 - * - * @param activity fragment 对应的 activity - * @param statusBarAlpha 状态栏透明度 - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTranslucentForImageViewInFragment(Activity activity, int statusBarAlpha, - View needOffsetView) - { - setTranslucentForImageView(activity, statusBarAlpha, needOffsetView); - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) - { - clearPreviousSetting(activity); - } - } - - /////////////////////////////////////////////////////////////////////////////////// - - @TargetApi(Build.VERSION_CODES.KITKAT) - private static void clearPreviousSetting(Activity activity) - { - ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); - int count = decorView.getChildCount(); - if(count > 0 && decorView.getChildAt(count - 1) instanceof StatusBarView) - { - decorView.removeViewAt(count - 1); - ViewGroup rootView = (ViewGroup) ((ViewGroup) activity - .findViewById(android.R.id.content)).getChildAt(0); - rootView.setPadding(0, 0, 0, 0); - } - } - - /** - * 添加半透明矩形条 - * - * @param activity 需要设置的 activity - * @param statusBarAlpha 透明值 - */ - private static void addTranslucentView(Activity activity, int statusBarAlpha) - { - ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); - if(contentView.getChildCount() > 1) - { - contentView.getChildAt(1).setBackgroundColor(Color.argb(statusBarAlpha, 0, 0, 0)); - } - else - { - contentView.addView(createTranslucentStatusBarView(activity, statusBarAlpha)); - } - } - - /** - * 生成一个和状态栏大小相同的彩色矩形条 - * - * @param activity 需要设置的 activity - * @param color 状态栏颜色值 - * @return 状态栏矩形条 - */ - private static StatusBarView createStatusBarView(Activity activity, int color) - { - // 绘制一个和状态栏一样高的矩形 - StatusBarView statusBarView = new StatusBarView(activity); - LinearLayout.LayoutParams params = - new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, - getStatusBarHeight(activity)); - statusBarView.setLayoutParams(params); - statusBarView.setBackgroundColor(color); - return statusBarView; - } - - /** - * 生成一个和状态栏大小相同的半透明矩形条 - * - * @param activity 需要设置的activity - * @param color 状态栏颜色值 - * @param alpha 透明值 - * @return 状态栏矩形条 - */ - private static StatusBarView createStatusBarView(Activity activity, int color, int alpha) - { - // 绘制一个和状态栏一样高的矩形 - StatusBarView statusBarView = new StatusBarView(activity); - LinearLayout.LayoutParams params = - new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, - getStatusBarHeight(activity)); - statusBarView.setLayoutParams(params); - statusBarView.setBackgroundColor(calculateStatusColor(color, alpha)); - return statusBarView; - } - - /** - * 设置根布局参数 - */ - @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) - private static void setRootView(Activity activity) - { - ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)) - .getChildAt(0); - rootView.setFitsSystemWindows(true); - rootView.setClipToPadding(true); - } - - /** - * 设置透明 - */ - private static void setTransparentForWindow(Activity activity) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) - { - activity.getWindow().setStatusBarColor(Color.TRANSPARENT); - activity.getWindow() - .getDecorView() - .setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); - } - else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) - { - activity.getWindow() - .setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, - WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - } - } - - /** - * 使状态栏透明 - */ - @TargetApi(Build.VERSION_CODES.KITKAT) - private static void transparentStatusBar(Activity activity) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) - { - activity.getWindow() - .addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); - activity.getWindow().setStatusBarColor(Color.TRANSPARENT); - } - else - { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - } - } - - /** - * 创建半透明矩形 View - * - * @param alpha 透明值 - * @return 半透明 View - */ - private static StatusBarView createTranslucentStatusBarView(Activity activity, int alpha) - { - // 绘制一个和状态栏一样高的矩形 - StatusBarView statusBarView = new StatusBarView(activity); - LinearLayout.LayoutParams params = - new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, - getStatusBarHeight(activity)); - statusBarView.setLayoutParams(params); - statusBarView.setBackgroundColor(Color.argb(alpha, 0, 0, 0)); - return statusBarView; - } - - /** - * 获取状态栏高度 - * - * @param context context - * @return 状态栏高度 - */ - public static int getStatusBarHeight(Context context) - { - int result = -1; - int resourceId = context.getResources() - .getIdentifier("status_bar_height", "dimen", "android"); - if(resourceId > 0) - { - result = context.getResources().getDimensionPixelSize(resourceId); - } - return result; - } - - /** - * 计算状态栏颜色 - * - * @param color color值 - * @param alpha alpha值 - * @return 最终的状态栏颜色 - */ - private static int calculateStatusColor(int color, int alpha) - { - float a = 1 - alpha / 255f; - int red = color >> 16 & 0xff; - int green = color >> 8 & 0xff; - int blue = color & 0xff; - red = (int) (red * a + 0.5); - green = (int) (green * a + 0.5); - blue = (int) (blue * a + 0.5); - return 0xff << 24 | red << 16 | green << 8 | blue; - } - - /*--------------------------------old--------------------------------*/ - - /** - * 设置透明状态栏(api大于19方可使用) - *

可在Activity的onCreat()中调用

- *

需在顶部控件布局中加入以下属性让内容出现在状态栏之下

- *

android:clipToPadding="true"

- *

android:fitsSystemWindows="true"

- * - * @param activity activity - */ - public static void setTransparentStatusBar(Activity activity) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) - { - //透明状态栏 - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - //透明导航栏 - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); - } - } - - /** - * 隐藏状态栏 - *

也就是设置全屏,一定要在setContentView之前调用,否则报错

- *

此方法Activity可以继承AppCompatActivity

- *

启动的时候状态栏会显示一下再隐藏,比如QQ的欢迎界面

- *

在配置文件中Activity加属性android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

- *

如加了以上配置Activity不能继承AppCompatActivity,会报错

- * - * @param activity activity - */ - public static void hideStatusBar(Activity activity) - { - activity.requestWindowFeature(Window.FEATURE_NO_TITLE); - activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN); - } - - /** - * 判断状态栏是否存在 - * - * @param activity activity - * @return {@code true}: 存在
{@code false}: 不存在 - */ - public static boolean isStatusBarExists(Activity activity) - { - WindowManager.LayoutParams params = activity.getWindow().getAttributes(); - return (params.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != WindowManager.LayoutParams.FLAG_FULLSCREEN; - } - - /** - * 获取ActionBar高度 - * - * @param activity activity - * @return ActionBar高度 - */ - public static int getActionBarHeight(Activity activity) - { - TypedValue tv = new TypedValue(); - if(activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) - { - return TypedValue.complexToDimensionPixelSize(tv.data, - activity.getResources().getDisplayMetrics()); - } - return 0; - } - - /** - * 显示通知栏 - *

需添加权限 {@code }

- * - * @param context 上下文 - * @param isSettingPanel {@code true}: 打开设置
{@code false}: 打开通知 - */ - public static void showNotificationBar(Context context, boolean isSettingPanel) - { - String methodName = (Build.VERSION.SDK_INT <= 16) ? "expand" - : (isSettingPanel ? "expandSettingsPanel" : "expandNotificationsPanel"); - invokePanels(context, methodName); - } - - /** - * 隐藏通知栏 - *

需添加权限 {@code }

- * - * @param context 上下文 - */ - public static void hideNotificationBar(Context context) - { - String methodName = (Build.VERSION.SDK_INT <= 16) ? "collapse" : "collapsePanels"; - invokePanels(context, methodName); - } - - /** - * 反射唤醒通知栏 - * - * @param context 上下文 - * @param methodName 方法名 - */ - private static void invokePanels(Context context, String methodName) - { - try - { - Object service = context.getSystemService("statusbar"); - Class statusBarManager = Class.forName("android.app.StatusBarManager"); - Method expand = statusBarManager.getMethod(methodName); - expand.invoke(service); - } catch(Exception e) - { - e.printStackTrace(); - } - } -} +package com.ayvytr.easyandroidlibrary.tools.withcontext; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.Context; +import android.graphics.Color; +import android.os.Build; +import android.support.v4.widget.DrawerLayout; +import android.util.AttributeSet; +import android.util.TypedValue; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.LinearLayout; + +import com.ayvytr.easyandroidlibrary.exception.UnsupportedInitializationException; + +import java.lang.reflect.Method; + +/** + * StatusBar, ActionBar等相关工具类 + */ +public class BarTool +{ + + private BarTool() + { + throw new UnsupportedInitializationException(); + } + + public static class StatusBarView extends View + { + public StatusBarView(Context context, AttributeSet attrs) + { + super(context, attrs); + } + + public StatusBarView(Context context) + { + super(context); + } + } + + public static final int DEFAULT_STATUS_BAR_ALPHA = 112; + + /** + * 设置状态栏颜色 + * + * @param activity 需要设置的 activity + * @param color 状态栏颜色值 + */ + public static void setColor(Activity activity, int color) + { + setColor(activity, color, DEFAULT_STATUS_BAR_ALPHA); + } + + /** + * 设置状态栏颜色 + * + * @param activity 需要设置的activity + * @param color 状态栏颜色值 + * @param statusBarAlpha 状态栏透明度 + */ + + public static void setColor(Activity activity, int color, int statusBarAlpha) + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) + { + activity.getWindow() + .addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); + activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + activity.getWindow().setStatusBarColor(calculateStatusColor(color, statusBarAlpha)); + } + else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) + { + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); + int count = decorView.getChildCount(); + if(count > 0 && decorView.getChildAt(count - 1) instanceof StatusBarView) + { + decorView.getChildAt(count - 1) + .setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); + } + else + { + StatusBarView statusView = createStatusBarView(activity, color, statusBarAlpha); + decorView.addView(statusView); + } + setRootView(activity); + } + } + + /** + * 为滑动返回界面设置状态栏颜色 + * + * @param activity 需要设置的activity + * @param color 状态栏颜色值 + */ + public static void setColorForSwipeBack(Activity activity, int color) + { + setColorForSwipeBack(activity, color, DEFAULT_STATUS_BAR_ALPHA); + } + + /** + * 为滑动返回界面设置状态栏颜色 + * + * @param activity 需要设置的activity + * @param color 状态栏颜色值 + * @param statusBarAlpha 状态栏透明度 + */ + public static void setColorForSwipeBack(Activity activity, int color, int statusBarAlpha) + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) + { + ViewGroup contentView = ((ViewGroup) activity.findViewById(android.R.id.content)); + contentView.setPadding(0, getStatusBarHeight(activity), 0, 0); + contentView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); + setTransparentForWindow(activity); + } + } + + /** + * 设置状态栏纯色 不加半透明效果 + * + * @param activity 需要设置的 activity + * @param color 状态栏颜色值 + */ + public static void setColorNoTranslucent(Activity activity, int color) + { + setColor(activity, color, 0); + } + + /** + * 设置状态栏颜色(5.0以下无半透明效果,不建议使用) + * + * @param activity 需要设置的 activity + * @param color 状态栏颜色值 + */ + @Deprecated + public static void setColorDiff(Activity activity, int color) + { + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) + { + return; + } + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + // 生成一个状态栏大小的矩形 + ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); + int count = decorView.getChildCount(); + if(count > 0 && decorView.getChildAt(count - 1) instanceof StatusBarView) + { + decorView.getChildAt(count - 1).setBackgroundColor(color); + } + else + { + StatusBarView statusView = createStatusBarView(activity, color); + decorView.addView(statusView); + } + setRootView(activity); + } + + /** + * 使状态栏半透明 + * 适用于图片作为背景的界面,此时需要图片填充到状态栏 + * + * @param activity 需要设置的activity + */ + public static void setTranslucent(Activity activity) + { + setTranslucent(activity, DEFAULT_STATUS_BAR_ALPHA); + } + + /** + * 使状态栏半透明 + *

+ * 适用于图片作为背景的界面,此时需要图片填充到状态栏 + * + * @param activity 需要设置的activity + * @param statusBarAlpha 状态栏透明度 + */ + public static void setTranslucent(Activity activity, int statusBarAlpha) + { + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) + { + return; + } + setTransparent(activity); + addTranslucentView(activity, statusBarAlpha); + } + + /** + * 针对根布局是 CoordinatorLayout, 使状态栏半透明 + *

+ * 适用于图片作为背景的界面,此时需要图片填充到状态栏 + * + * @param activity 需要设置的activity + * @param statusBarAlpha 状态栏透明度 + */ + public static void setTranslucentForCoordinatorLayout(Activity activity, int statusBarAlpha) + { + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) + { + return; + } + transparentStatusBar(activity); + addTranslucentView(activity, statusBarAlpha); + } + + /** + * 设置状态栏全透明 + * + * @param activity 需要设置的activity + */ + public static void setTransparent(Activity activity) + { + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) + { + return; + } + transparentStatusBar(activity); + setRootView(activity); + } + + /** + * 使状态栏透明(5.0以上半透明效果,不建议使用) + *

+ * 适用于图片作为背景的界面,此时需要图片填充到状态栏 + * + * @param activity 需要设置的activity + */ + @Deprecated + public static void setTranslucentDiff(Activity activity) + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) + { + // 设置状态栏透明 + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + setRootView(activity); + } + } + + /** + * 为DrawerLayout 布局设置状态栏变色 + * + * @param activity 需要设置的activity + * @param drawerLayout DrawerLayout + * @param color 状态栏颜色值 + */ + public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, + int color) + { + setColorForDrawerLayout(activity, drawerLayout, color, DEFAULT_STATUS_BAR_ALPHA); + } + + /** + * 为DrawerLayout 布局设置状态栏颜色,纯色 + * + * @param activity 需要设置的activity + * @param drawerLayout DrawerLayout + * @param color 状态栏颜色值 + */ + public static void setColorNoTranslucentForDrawerLayout(Activity activity, + DrawerLayout drawerLayout, int color) + { + setColorForDrawerLayout(activity, drawerLayout, color, 0); + } + + /** + * 为DrawerLayout 布局设置状态栏变色 + * + * @param activity 需要设置的activity + * @param drawerLayout DrawerLayout + * @param color 状态栏颜色值 + * @param statusBarAlpha 状态栏透明度 + */ + public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, + int color, + int statusBarAlpha) + { + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) + { + return; + } + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) + { + activity.getWindow() + .addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); + activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + activity.getWindow().setStatusBarColor(Color.TRANSPARENT); + } + else + { + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + } + // 生成一个状态栏大小的矩形 + // 添加 statusBarView 到布局中 + ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); + if(contentLayout.getChildCount() > 0 && contentLayout + .getChildAt(0) instanceof StatusBarView) + { + contentLayout.getChildAt(0) + .setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); + } + else + { + StatusBarView statusBarView = createStatusBarView(activity, color); + contentLayout.addView(statusBarView, 0); + } + // 内容布局不是 LinearLayout 时,设置padding top + if(!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) + { + contentLayout.getChildAt(1) + .setPadding(contentLayout.getPaddingLeft(), + getStatusBarHeight(activity) + contentLayout.getPaddingTop(), + contentLayout.getPaddingRight(), contentLayout.getPaddingBottom()); + } + // 设置属性 + ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); + drawerLayout.setFitsSystemWindows(false); + contentLayout.setFitsSystemWindows(false); + contentLayout.setClipToPadding(true); + drawer.setFitsSystemWindows(false); + + addTranslucentView(activity, statusBarAlpha); + } + + /** + * 为DrawerLayout 布局设置状态栏变色(5.0以下无半透明效果,不建议使用) + * + * @param activity 需要设置的activity + * @param drawerLayout DrawerLayout + * @param color 状态栏颜色值 + */ + @Deprecated + public static void setColorForDrawerLayoutDiff(Activity activity, DrawerLayout drawerLayout, + int color) + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) + { + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + // 生成一个状态栏大小的矩形 + ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); + if(contentLayout.getChildCount() > 0 && contentLayout + .getChildAt(0) instanceof StatusBarView) + { + contentLayout.getChildAt(0).setBackgroundColor( + calculateStatusColor(color, DEFAULT_STATUS_BAR_ALPHA)); + } + else + { + // 添加 statusBarView 到布局中 + StatusBarView statusBarView = createStatusBarView(activity, color); + contentLayout.addView(statusBarView, 0); + } + // 内容布局不是 LinearLayout 时,设置padding top + if(!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) + { + contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0); + } + // 设置属性 + ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); + drawerLayout.setFitsSystemWindows(false); + contentLayout.setFitsSystemWindows(false); + contentLayout.setClipToPadding(true); + drawer.setFitsSystemWindows(false); + } + } + + /** + * 为 DrawerLayout 布局设置状态栏透明 + * + * @param activity 需要设置的activity + * @param drawerLayout DrawerLayout + */ + public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) + { + setTranslucentForDrawerLayout(activity, drawerLayout, DEFAULT_STATUS_BAR_ALPHA); + } + + /** + * 为 DrawerLayout 布局设置状态栏透明 + * + * @param activity 需要设置的activity + * @param drawerLayout DrawerLayout + * @param statusBarAlpha 透明度 + */ + public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, + int statusBarAlpha) + { + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) + { + return; + } + setTransparentForDrawerLayout(activity, drawerLayout); + addTranslucentView(activity, statusBarAlpha); + } + + /** + * 为 DrawerLayout 布局设置状态栏透明 + * + * @param activity 需要设置的activity + * @param drawerLayout DrawerLayout + */ + public static void setTransparentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) + { + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) + { + return; + } + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) + { + activity.getWindow() + .addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); + activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + activity.getWindow().setStatusBarColor(Color.TRANSPARENT); + } + else + { + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + } + + ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); + // 内容布局不是 LinearLayout 时,设置padding top + if(!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) + { + contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0); + } + + // 设置属性 + ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); + drawerLayout.setFitsSystemWindows(false); + contentLayout.setFitsSystemWindows(false); + contentLayout.setClipToPadding(true); + drawer.setFitsSystemWindows(false); + } + + /** + * 为 DrawerLayout 布局设置状态栏透明(5.0以上半透明效果,不建议使用) + * + * @param activity 需要设置的activity + * @param drawerLayout DrawerLayout + */ + @Deprecated + public static void setTranslucentForDrawerLayoutDiff(Activity activity, + DrawerLayout drawerLayout) + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) + { + // 设置状态栏透明 + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + // 设置内容布局属性 + ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); + contentLayout.setFitsSystemWindows(true); + contentLayout.setClipToPadding(true); + // 设置抽屉布局属性 + ViewGroup vg = (ViewGroup) drawerLayout.getChildAt(1); + vg.setFitsSystemWindows(false); + // 设置 DrawerLayout 属性 + drawerLayout.setFitsSystemWindows(false); + } + } + + /** + * 为头部是 ImageView 的界面设置状态栏全透明 + * + * @param activity 需要设置的activity + * @param needOffsetView 需要向下偏移的 View + */ + public static void setTransparentForImageView(Activity activity, View needOffsetView) + { + setTranslucentForImageView(activity, 0, needOffsetView); + } + + /** + * 为头部是 ImageView 的界面设置状态栏透明(使用默认透明度) + * + * @param activity 需要设置的activity + * @param needOffsetView 需要向下偏移的 View + */ + public static void setTranslucentForImageView(Activity activity, View needOffsetView) + { + setTranslucentForImageView(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView); + } + + /** + * 为头部是 ImageView 的界面设置状态栏透明 + * + * @param activity 需要设置的activity + * @param statusBarAlpha 状态栏透明度 + * @param needOffsetView 需要向下偏移的 View + */ + public static void setTranslucentForImageView(Activity activity, int statusBarAlpha, + View needOffsetView) + { + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) + { + return; + } + setTransparentForWindow(activity); + addTranslucentView(activity, statusBarAlpha); + if(needOffsetView != null) + { + ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) needOffsetView + .getLayoutParams(); + layoutParams.setMargins(0, getStatusBarHeight(activity), 0, 0); + } + } + + /** + * 为 fragment 头部是 ImageView 的设置状态栏透明 + * + * @param activity fragment 对应的 activity + * @param needOffsetView 需要向下偏移的 View + */ + public static void setTranslucentForImageViewInFragment(Activity activity, View needOffsetView) + { + setTranslucentForImageViewInFragment(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView); + } + + /** + * 为 fragment 头部是 ImageView 的设置状态栏透明 + * + * @param activity fragment 对应的 activity + * @param needOffsetView 需要向下偏移的 View + */ + public static void setTransparentForImageViewInFragment(Activity activity, View needOffsetView) + { + setTranslucentForImageViewInFragment(activity, 0, needOffsetView); + } + + /** + * 为 fragment 头部是 ImageView 的设置状态栏透明 + * + * @param activity fragment 对应的 activity + * @param statusBarAlpha 状态栏透明度 + * @param needOffsetView 需要向下偏移的 View + */ + public static void setTranslucentForImageViewInFragment(Activity activity, int statusBarAlpha, + View needOffsetView) + { + setTranslucentForImageView(activity, statusBarAlpha, needOffsetView); + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) + { + clearPreviousSetting(activity); + } + } + + /////////////////////////////////////////////////////////////////////////////////// + + @TargetApi(Build.VERSION_CODES.KITKAT) + private static void clearPreviousSetting(Activity activity) + { + ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); + int count = decorView.getChildCount(); + if(count > 0 && decorView.getChildAt(count - 1) instanceof StatusBarView) + { + decorView.removeViewAt(count - 1); + ViewGroup rootView = (ViewGroup) ((ViewGroup) activity + .findViewById(android.R.id.content)).getChildAt(0); + rootView.setPadding(0, 0, 0, 0); + } + } + + /** + * 添加半透明矩形条 + * + * @param activity 需要设置的 activity + * @param statusBarAlpha 透明值 + */ + private static void addTranslucentView(Activity activity, int statusBarAlpha) + { + ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); + if(contentView.getChildCount() > 1) + { + contentView.getChildAt(1).setBackgroundColor(Color.argb(statusBarAlpha, 0, 0, 0)); + } + else + { + contentView.addView(createTranslucentStatusBarView(activity, statusBarAlpha)); + } + } + + /** + * 生成一个和状态栏大小相同的彩色矩形条 + * + * @param activity 需要设置的 activity + * @param color 状态栏颜色值 + * @return 状态栏矩形条 + */ + private static StatusBarView createStatusBarView(Activity activity, int color) + { + // 绘制一个和状态栏一样高的矩形 + StatusBarView statusBarView = new StatusBarView(activity); + LinearLayout.LayoutParams params = + new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + getStatusBarHeight(activity)); + statusBarView.setLayoutParams(params); + statusBarView.setBackgroundColor(color); + return statusBarView; + } + + /** + * 生成一个和状态栏大小相同的半透明矩形条 + * + * @param activity 需要设置的activity + * @param color 状态栏颜色值 + * @param alpha 透明值 + * @return 状态栏矩形条 + */ + private static StatusBarView createStatusBarView(Activity activity, int color, int alpha) + { + // 绘制一个和状态栏一样高的矩形 + StatusBarView statusBarView = new StatusBarView(activity); + LinearLayout.LayoutParams params = + new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + getStatusBarHeight(activity)); + statusBarView.setLayoutParams(params); + statusBarView.setBackgroundColor(calculateStatusColor(color, alpha)); + return statusBarView; + } + + /** + * 设置根布局参数 + */ + @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) + private static void setRootView(Activity activity) + { + ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)) + .getChildAt(0); + rootView.setFitsSystemWindows(true); + rootView.setClipToPadding(true); + } + + /** + * 设置透明 + */ + private static void setTransparentForWindow(Activity activity) + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) + { + activity.getWindow().setStatusBarColor(Color.TRANSPARENT); + activity.getWindow() + .getDecorView() + .setSystemUiVisibility( + View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); + } + else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) + { + activity.getWindow() + .setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, + WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + } + } + + /** + * 使状态栏透明 + */ + @TargetApi(Build.VERSION_CODES.KITKAT) + private static void transparentStatusBar(Activity activity) + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) + { + activity.getWindow() + .addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); + activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); + activity.getWindow().setStatusBarColor(Color.TRANSPARENT); + } + else + { + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + } + } + + /** + * 创建半透明矩形 View + * + * @param alpha 透明值 + * @return 半透明 View + */ + private static StatusBarView createTranslucentStatusBarView(Activity activity, int alpha) + { + // 绘制一个和状态栏一样高的矩形 + StatusBarView statusBarView = new StatusBarView(activity); + LinearLayout.LayoutParams params = + new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + getStatusBarHeight(activity)); + statusBarView.setLayoutParams(params); + statusBarView.setBackgroundColor(Color.argb(alpha, 0, 0, 0)); + return statusBarView; + } + + /** + * 获取状态栏高度 + * + * @param context context + * @return 状态栏高度 + */ + public static int getStatusBarHeight(Context context) + { + int result = -1; + int resourceId = context.getResources() + .getIdentifier("status_bar_height", "dimen", "android"); + if(resourceId > 0) + { + result = context.getResources().getDimensionPixelSize(resourceId); + } + return result; + } + + /** + * 计算状态栏颜色 + * + * @param color color值 + * @param alpha alpha值 + * @return 最终的状态栏颜色 + */ + private static int calculateStatusColor(int color, int alpha) + { + float a = 1 - alpha / 255f; + int red = color >> 16 & 0xff; + int green = color >> 8 & 0xff; + int blue = color & 0xff; + red = (int) (red * a + 0.5); + green = (int) (green * a + 0.5); + blue = (int) (blue * a + 0.5); + return 0xff << 24 | red << 16 | green << 8 | blue; + } + + /*--------------------------------old--------------------------------*/ + + /** + * 设置透明状态栏(api大于19方可使用) + *

可在Activity的onCreat()中调用

+ *

需在顶部控件布局中加入以下属性让内容出现在状态栏之下

+ *

android:clipToPadding="true"

+ *

android:fitsSystemWindows="true"

+ * + * @param activity activity + */ + public static void setTransparentStatusBar(Activity activity) + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) + { + //透明状态栏 + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + //透明导航栏 + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); + } + } + + /** + * 隐藏状态栏 + *

也就是设置全屏,一定要在setContentView之前调用,否则报错

+ *

此方法Activity可以继承AppCompatActivity

+ *

启动的时候状态栏会显示一下再隐藏,比如QQ的欢迎界面

+ *

在配置文件中Activity加属性android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

+ *

如加了以上配置Activity不能继承AppCompatActivity,会报错

+ * + * @param activity activity + */ + public static void hideStatusBar(Activity activity) + { + activity.requestWindowFeature(Window.FEATURE_NO_TITLE); + activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, + WindowManager.LayoutParams.FLAG_FULLSCREEN); + } + + /** + * 判断状态栏是否存在 + * + * @param activity activity + * @return {@code true}: 存在
{@code false}: 不存在 + */ + public static boolean isStatusBarExists(Activity activity) + { + WindowManager.LayoutParams params = activity.getWindow().getAttributes(); + return (params.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != WindowManager.LayoutParams.FLAG_FULLSCREEN; + } + + /** + * 获取ActionBar高度 + * + * @param activity activity + * @return ActionBar高度 + */ + public static int getActionBarHeight(Activity activity) + { + TypedValue tv = new TypedValue(); + if(activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) + { + return TypedValue.complexToDimensionPixelSize(tv.data, + activity.getResources().getDisplayMetrics()); + } + return 0; + } + + /** + * 显示通知栏 + *

需添加权限 {@code }

+ * + * @param context 上下文 + * @param isSettingPanel {@code true}: 打开设置
{@code false}: 打开通知 + */ + public static void showNotificationBar(Context context, boolean isSettingPanel) + { + String methodName = (Build.VERSION.SDK_INT <= 16) ? "expand" + : (isSettingPanel ? "expandSettingsPanel" : "expandNotificationsPanel"); + invokePanels(context, methodName); + } + + /** + * 隐藏通知栏 + *

需添加权限 {@code }

+ * + * @param context 上下文 + */ + public static void hideNotificationBar(Context context) + { + String methodName = (Build.VERSION.SDK_INT <= 16) ? "collapse" : "collapsePanels"; + invokePanels(context, methodName); + } + + /** + * 反射唤醒通知栏 + * + * @param context 上下文 + * @param methodName 方法名 + */ + private static void invokePanels(Context context, String methodName) + { + try + { + Object service = context.getSystemService("statusbar"); + Class statusBarManager = Class.forName("android.app.StatusBarManager"); + Method expand = statusBarManager.getMethod(methodName); + expand.invoke(service); + } catch(Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ClipboardTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ClipboardTool.java similarity index 89% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ClipboardTool.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ClipboardTool.java index ef8728b..4bf9884 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ClipboardTool.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ClipboardTool.java @@ -1,116 +1,116 @@ -package com.ayvytr.easydeveloper.tools.withcontext; - -import android.content.ClipData; -import android.content.ClipboardManager; -import android.content.Intent; -import android.net.Uri; - -import com.ayvytr.easydeveloper.Easy; -import com.ayvytr.easydeveloper.consts.EasyConst; -import com.ayvytr.easydeveloper.exception.UnsupportedInitializationException; - -/** - * Created by davidwang on 2017/3/15. - */ - -public class ClipboardTool -{ - private ClipboardTool() - { - throw new UnsupportedInitializationException(); - } - - /** - * 设置文本到剪贴板 - * - * @param text 文本 - */ - public static void setText(CharSequence text) - { - ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); - clipboardManager.setPrimaryClip(ClipData.newPlainText(EasyConst.TEXT, text)); - } - - /** - * 获取剪贴板的文本 - * - * @return 剪贴板的文本 - */ - public static String getText() - { - return getText(null); - } - - /** - * 获取剪贴板文本,当获取到是空时,返回默认字符串 - * - * @param textIfNull 剪贴板文本如果为空,返回这个字符串 - * @return 剪贴板文本 - */ - public static String getText(String textIfNull) - { - ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); - ClipData clipData = clipboardManager.getPrimaryClip(); - if(clipData != null && clipData.getItemCount() > 0) - { - return clipData.getItemAt(0).coerceToText(Easy.getContext()).toString(); - } - - return textIfNull; - } - - /** - * 设置uri到剪贴板 - * - * @param uri uri - */ - public static void setUri(Uri uri) - { - ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); - clipboardManager.setPrimaryClip( - ClipData.newUri(Easy.getContext().getContentResolver(), EasyConst.Uri, uri)); - } - - /** - * 获取剪贴板的uri - * - * @return 剪贴板的uri - */ - public static Uri getUri() - { - ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); - ClipData clipData = clipboardManager.getPrimaryClip(); - if(clipData != null && clipData.getItemCount() > 0) - { - return clipData.getItemAt(0).getUri(); - } - return null; - } - - /** - * 设置意图到剪贴板 - * - * @param intent 意图 - */ - public static void setIntent(Intent intent) - { - ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); - clipboardManager.setPrimaryClip(ClipData.newIntent(EasyConst.Intent, intent)); - } - - /** - * 获取剪贴板的意图 - * - * @return 剪贴板的意图 - */ - public static Intent getIntent() - { - ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); - ClipData clipData = clipboardManager.getPrimaryClip(); - if(clipData != null && clipData.getItemCount() > 0) - { - return clipData.getItemAt(0).getIntent(); - } - return null; - } -} +package com.ayvytr.easyandroidlibrary.tools.withcontext; + +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Intent; +import android.net.Uri; + +import com.ayvytr.easyandroidlibrary.Easy; +import com.ayvytr.easyandroidlibrary.consts.EasyConst; +import com.ayvytr.easyandroidlibrary.exception.UnsupportedInitializationException; + +/** + * Created by davidwang on 2017/3/15. + */ + +public class ClipboardTool +{ + private ClipboardTool() + { + throw new UnsupportedInitializationException(); + } + + /** + * 设置文本到剪贴板 + * + * @param text 文本 + */ + public static void setText(CharSequence text) + { + ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); + clipboardManager.setPrimaryClip(ClipData.newPlainText(EasyConst.TEXT, text)); + } + + /** + * 获取剪贴板的文本 + * + * @return 剪贴板的文本 + */ + public static String getText() + { + return getText(null); + } + + /** + * 获取剪贴板文本,当获取到是空时,返回默认字符串 + * + * @param textIfNull 剪贴板文本如果为空,返回这个字符串 + * @return 剪贴板文本 + */ + public static String getText(String textIfNull) + { + ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); + ClipData clipData = clipboardManager.getPrimaryClip(); + if(clipData != null && clipData.getItemCount() > 0) + { + return clipData.getItemAt(0).coerceToText(Easy.getContext()).toString(); + } + + return textIfNull; + } + + /** + * 设置uri到剪贴板 + * + * @param uri uri + */ + public static void setUri(Uri uri) + { + ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); + clipboardManager.setPrimaryClip( + ClipData.newUri(Easy.getContext().getContentResolver(), EasyConst.Uri, uri)); + } + + /** + * 获取剪贴板的uri + * + * @return 剪贴板的uri + */ + public static Uri getUri() + { + ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); + ClipData clipData = clipboardManager.getPrimaryClip(); + if(clipData != null && clipData.getItemCount() > 0) + { + return clipData.getItemAt(0).getUri(); + } + return null; + } + + /** + * 设置意图到剪贴板 + * + * @param intent 意图 + */ + public static void setIntent(Intent intent) + { + ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); + clipboardManager.setPrimaryClip(ClipData.newIntent(EasyConst.Intent, intent)); + } + + /** + * 获取剪贴板的意图 + * + * @return 剪贴板的意图 + */ + public static Intent getIntent() + { + ClipboardManager clipboardManager = Easy.getDefault().getClipboardManager(); + ClipData clipData = clipboardManager.getPrimaryClip(); + if(clipData != null && clipData.getItemCount() > 0) + { + return clipData.getItemAt(0).getIntent(); + } + return null; + } +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/DensityTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/DensityTool.java similarity index 67% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/DensityTool.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/DensityTool.java index 4f7fd23..09e7a05 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/DensityTool.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/DensityTool.java @@ -1,68 +1,68 @@ -package com.ayvytr.easydeveloper.tools.withcontext; - -import com.ayvytr.easydeveloper.Easy; -import com.ayvytr.easydeveloper.exception.UnsupportedInitializationException; - -/** - * Created by davidwang on 2017/3/15. - * DensityTool - * dp - px 相互转化。提供int,float,double重载,尽可能最大化方便计算,减少类外强转 - */ - -public class DensityTool -{ - private DensityTool() - { - throw new UnsupportedInitializationException(); - } - - /** - * 将px转换为dp - */ - public static int px2dp(int px) - { - return (int) px2dp((float)px); - } - - /** - * 将px转换为dp,接收/返回float - */ - public static float px2dp(float px) - { - return (float) px2dp((double)px); - } - - /** - * 将px转换为dp,接收/返回double - */ - public static double px2dp(double px) - { - float scale = Easy.getContext().getResources().getDisplayMetrics().density; - return px / scale + 0.5; - } - - /** - * 将dp转换为px,接收/返回int - */ - public static int dp2px(int dp) - { - return (int) dp2px((float)dp); - } - - /** - * 将dp转换为px,接收/返回float - */ - public static float dp2px(float dp) - { - return (float) dp2px((double)dp); - } - - /** - * 将dp转换为px,接收/返回double - */ - public static double dp2px(double dp) - { - float scale = Easy.getContext().getResources().getDisplayMetrics().density; - return dp * scale + 0.5f; - } -} +package com.ayvytr.easyandroidlibrary.tools.withcontext; + +import com.ayvytr.easyandroidlibrary.Easy; +import com.ayvytr.easyandroidlibrary.exception.UnsupportedInitializationException; + +/** + * Created by davidwang on 2017/3/15. + * DensityTool + * dp - px 相互转化。提供int,float,double重载,尽可能最大化方便计算,减少类外强转 + */ + +public class DensityTool +{ + private DensityTool() + { + throw new UnsupportedInitializationException(); + } + + /** + * 将px转换为dp + */ + public static int px2dp(int px) + { + return (int) px2dp((float) px); + } + + /** + * 将px转换为dp,接收/返回float + */ + public static float px2dp(float px) + { + return (float) px2dp((double) px); + } + + /** + * 将px转换为dp,接收/返回double + */ + public static double px2dp(double px) + { + float scale = Easy.getContext().getResources().getDisplayMetrics().density; + return px / scale + 0.5; + } + + /** + * 将dp转换为px,接收/返回int + */ + public static int dp2px(int dp) + { + return (int) dp2px((float) dp); + } + + /** + * 将dp转换为px,接收/返回float + */ + public static float dp2px(float dp) + { + return (float) dp2px((double) dp); + } + + /** + * 将dp转换为px,接收/返回double + */ + public static double dp2px(double dp) + { + float scale = Easy.getContext().getResources().getDisplayMetrics().density; + return dp * scale + 0.5f; + } +} diff --git a/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/IntentTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/IntentTool.java new file mode 100644 index 0000000..20e45ac --- /dev/null +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/IntentTool.java @@ -0,0 +1,265 @@ +package com.ayvytr.easyandroidlibrary.tools.withcontext; + +import android.content.ComponentName; +import android.content.Intent; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.provider.MediaStore; +import android.support.v4.content.FileProvider; +import android.webkit.MimeTypeMap; + +import com.ayvytr.easyandroidlibrary.Easy; +import com.ayvytr.easyandroidlibrary.exception.UnsupportedInitializationException; +import com.ayvytr.easyandroidlibrary.tools.FileTool; + +import java.io.File; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2016/9/23
+ *     desc  : 意图相关工具类
+ * 
+ */ +public class IntentTool +{ + + private IntentTool() + { + throw new UnsupportedInitializationException(); + } + + /** + * 获取安装App(支持6.0)的意图 + * + * @param filePath 文件路径 + * @return intent + */ + public static Intent getInstallAppIntent(String filePath) + { + return getInstallAppIntent(FileTool.fromName(filePath)); + } + + /** + * 获取安装App(支持6.0)的意图 + * + * @param file 文件 + * @return intent + */ + public static Intent getInstallAppIntent(File file) + { + if(file == null) return null; + Intent intent = new Intent(Intent.ACTION_VIEW); + String type; + + if(Build.VERSION.SDK_INT < 23) + { + type = "application/vnd.android.package-archive"; + } + else + { + type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FileTool.getExtension(file)); + } + + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) + { + intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + Uri contentUri = FileProvider + .getUriForFile(Easy.getContext(), "com.your.package.fileProvider", file); + intent.setDataAndType(contentUri, type); + } + intent.setDataAndType(Uri.fromFile(file), type); + return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + /** + * 获取卸载App的意图 + * + * @param packageName 包名 + * @return intent + */ + public static Intent getUninstallAppIntent(String packageName) + { + Intent intent = new Intent(Intent.ACTION_DELETE); + intent.setData(Uri.parse("package:" + packageName)); + return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + /** + * 获取打开App的意图 + * + * @param packageName 包名 + * @return intent + */ + public static Intent getLaunchAppIntent(String packageName) + { + return Easy.getContext().getPackageManager().getLaunchIntentForPackage(packageName); + } + + /** + * 获取App具体设置的意图 + * + * @param packageName 包名 + * @return intent + */ + public static Intent getAppDetailsSettingsIntent(String packageName) + { + Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS"); + intent.setData(Uri.parse("package:" + packageName)); + return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + /** + * 获取分享文本的意图 + * + * @param content 分享文本 + * @return intent + */ + public static Intent getShareTextIntent(String content) + { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.setType("text/plain"); + intent.putExtra(Intent.EXTRA_TEXT, content); + return intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + /** + * 获取分享图片的意图 + * + * @param content 文本 + * @param imagePath 图片文件路径 + * @return intent + */ + public static Intent getShareImageIntent(String content, String imagePath) + { + return getShareImageIntent(content, FileTool.fromName(imagePath)); + } + + /** + * 获取分享图片的意图 + * + * @param content 文本 + * @param image 图片文件 + * @return intent + */ + public static Intent getShareImageIntent(String content, File image) + { + if(!FileTool.isExists(image)) + { + return null; + } + + return getShareImageIntent(content, Uri.fromFile(image)); + } + + /** + * 获取分享图片的意图 + * + * @param content 分享文本 + * @param uri 图片uri + * @return intent + */ + public static Intent getShareImageIntent(String content, Uri uri) + { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.putExtra(Intent.EXTRA_TEXT, content); + intent.putExtra(Intent.EXTRA_STREAM, uri); + intent.setType("image/*"); + return intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + /** + * 获取其他应用组件的意图 + * + * @param packageName 包名 + * @param className 全类名 + * @return intent + */ + public static Intent getComponentIntent(String packageName, String className) + { + return getComponentIntent(packageName, className, null); + } + + /** + * 获取其他应用组件的意图 + * + * @param packageName 包名 + * @param className 全类名 + * @param bundle bundle + * @return intent + */ + public static Intent getComponentIntent(String packageName, String className, Bundle bundle) + { + Intent intent = new Intent(Intent.ACTION_VIEW); + if(bundle != null) intent.putExtras(bundle); + ComponentName cn = new ComponentName(packageName, className); + intent.setComponent(cn); + return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + /** + * 获取关机的意图 + *

需添加权限 {@code }

+ * + * @return intent + */ + public static Intent getShutdownIntent() + { + Intent intent = new Intent(Intent.ACTION_SHUTDOWN); + return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + /** + * 获取跳至拨号界面意图 + * + * @param phoneNumber 电话号码 + */ + public static Intent getDialIntent(String phoneNumber) + { + Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)); + return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + /** + * 获取拨打电话意图 + *

需添加权限 {@code }

+ * + * @param phoneNumber 电话号码 + */ + public static Intent getCallIntent(String phoneNumber) + { + Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phoneNumber)); + return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + /** + * 获取跳至发送短信界面的意图 + * + * @param phoneNumber 接收号码 + * @param content 短信内容 + */ + public static Intent getSendSmsIntent(String phoneNumber, String content) + { + Uri uri = Uri.parse("smsto:" + phoneNumber); + Intent intent = new Intent(Intent.ACTION_SENDTO, uri); + intent.putExtra("sms_body", content); + return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + + /** + * 获取拍照的意图 + * + * @param outUri 输出的uri + * @return 拍照的意图 + */ + public static Intent getCaptureIntent(Uri outUri) + { + Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); + intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri); + return intent + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK); + } +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ResTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ResTool.java similarity index 88% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ResTool.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ResTool.java index b126f30..8509a7d 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ResTool.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ResTool.java @@ -1,83 +1,84 @@ -package com.ayvytr.easydeveloper.tools.withcontext; - -import android.content.res.Configuration; -import android.graphics.drawable.Drawable; -import android.support.annotation.ColorRes; -import android.support.annotation.DimenRes; -import android.support.annotation.DrawableRes; -import android.support.annotation.StringRes; -import android.support.v4.content.ContextCompat; - -import com.ayvytr.easydeveloper.Easy; -import com.ayvytr.easydeveloper.exception.UnsupportedInitializationException; - -/** - * Created by davidwang on 2017/3/15. - */ - -public class ResTool -{ - private ResTool() - { - throw new UnsupportedInitializationException(); - } - - /** - * 从资源中获取Drawable - */ - public static Drawable getDrawable(@DrawableRes int id) - { - //使用ContextCompat应是谷歌推荐的 - return ContextCompat.getDrawable(Easy.getContext(), id); - } - - /** - * 从资源中获取String - */ - public static String getString(@StringRes int id) - { - return Easy.getContext().getString(id); - } - - /** - * 从资源中获取Dimension,返回int类型 - */ - public static int getDimen(@DimenRes int id) - { - return (int) Easy.getContext().getResources().getDimension(id); - } - - /** - * 从资源中获取Dimension,返回float类型 - */ - public static float getDimenFloat(@DimenRes int id) - { - return Easy.getContext().getResources().getDimension(id); - } - - /** - * 从资源中获取Dimension - */ - public static float getDimenToDp(@DimenRes int id) - { - return Easy.getContext().getResources().getDimension(id); - } - - /** - * 从资源中获取Color - * @param id - * @return - */ - public static int getColor(@ColorRes int id) - { - return ContextCompat.getColor(Easy.getContext(), id); - } - - /** - * 获取 Configuration - */ - public static Configuration getConfiguration() - { - return Easy.getContext().getResources().getConfiguration(); - } -} +package com.ayvytr.easyandroidlibrary.tools.withcontext; + +import android.content.res.Configuration; +import android.graphics.drawable.Drawable; +import android.support.annotation.ColorRes; +import android.support.annotation.DimenRes; +import android.support.annotation.DrawableRes; +import android.support.annotation.StringRes; +import android.support.v4.content.ContextCompat; + +import com.ayvytr.easyandroidlibrary.Easy; +import com.ayvytr.easyandroidlibrary.exception.UnsupportedInitializationException; + +/** + * Created by davidwang on 2017/3/15. + */ + +public class ResTool +{ + private ResTool() + { + throw new UnsupportedInitializationException(); + } + + /** + * 从资源中获取Drawable + */ + public static Drawable getDrawable(@DrawableRes int id) + { + //使用ContextCompat应是谷歌推荐的 + return ContextCompat.getDrawable(Easy.getContext(), id); + } + + /** + * 从资源中获取String + */ + public static String getString(@StringRes int id) + { + return Easy.getContext().getString(id); + } + + /** + * 从资源中获取Dimension,返回int类型 + */ + public static int getDimen(@DimenRes int id) + { + return (int) Easy.getContext().getResources().getDimension(id); + } + + /** + * 从资源中获取Dimension,返回float类型 + */ + public static float getDimenFloat(@DimenRes int id) + { + return Easy.getContext().getResources().getDimension(id); + } + + /** + * 从资源中获取Dimension + */ + public static float getDimenToDp(@DimenRes int id) + { + return Easy.getContext().getResources().getDimension(id); + } + + /** + * 从资源中获取Color + * + * @param id + * @return + */ + public static int getColor(@ColorRes int id) + { + return ContextCompat.getColor(Easy.getContext(), id); + } + + /** + * 获取 Configuration + */ + public static Configuration getConfiguration() + { + return Easy.getContext().getResources().getConfiguration(); + } +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ScreenTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ScreenTool.java similarity index 92% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ScreenTool.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ScreenTool.java index 4d5ceb6..72e82cf 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ScreenTool.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ScreenTool.java @@ -1,169 +1,169 @@ -package com.ayvytr.easydeveloper.tools.withcontext; - -import android.app.Activity; -import android.content.pm.ActivityInfo; -import android.content.res.Configuration; -import android.graphics.Bitmap; -import android.util.DisplayMetrics; -import android.view.Surface; -import android.view.View; -import android.view.WindowManager; - -import com.ayvytr.easydeveloper.Easy; -import com.ayvytr.easydeveloper.exception.UnsupportedInitializationException; - -import static com.ayvytr.easydeveloper.tools.withcontext.ResTool.getConfiguration; - -/** - * ScreenTool 获取屏幕尺寸, - */ -public class ScreenTool -{ - private ScreenTool() - { - throw new UnsupportedInitializationException(); - } - - /** - * 获取屏幕DisplayMetrics - */ - public static DisplayMetrics getDisplayMetrics() - { - WindowManager windowManager = Easy.getDefault().getWindowManager(); - // 创建了一张白纸 - DisplayMetrics dm = new DisplayMetrics(); - // 给白纸设置宽高 - windowManager.getDefaultDisplay().getMetrics(dm); - return dm; - } - - /** - * 获取屏幕的宽度(单位:px) - */ - public static int getScreenWidth() - { - return getDisplayMetrics().widthPixels; - } - - /** - * 获取屏幕的高度(单位:px) - */ - public static int getScreenHeight() - { - return getDisplayMetrics().heightPixels; - } - - /** - * 设置屏幕为横屏 - *

还有一种就是在Activity中加属性android:screenOrientation="landscape"

- *

不设置Activity的android:configChanges时,切屏会重新调用各个生命周期,切横屏时会执行一次,切竖屏时会执行两次

- *

设置Activity的android:configChanges="orientation"时,切屏还是会重新调用各个生命周期,切横、竖屏时只会执行一次

- *

设置Activity的android:configChanges="orientation|keyboardHidden|screenSize"(4.0以上必须带最后一个参数)时 - * 切屏不会重新调用各个生命周期,只会执行onConfigurationChanged方法

- * - * @param activity activity - */ - public static void setLandscape(Activity activity) - { - activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - } - - /** - * 设置屏幕为竖屏 - * - * @param activity activity - */ - public static void setPortrait(Activity activity) - { - activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - } - - /** - * 判断是否横屏 - */ - public static boolean isLandscape() - { - Configuration configuration = getConfiguration(); - return configuration.orientation == Configuration.ORIENTATION_LANDSCAPE; - } - - /** - * 判断是否竖屏 - */ - public static boolean isPortrait() - { - Configuration configuration = getConfiguration(); - return configuration.orientation == Configuration.ORIENTATION_PORTRAIT; - } - - /** - * 获取屏幕旋转角度 - * - * @param activity activity - * @return 屏幕旋转角度 - */ - public static int getScreenRotation(Activity activity) - { - switch(activity.getWindowManager().getDefaultDisplay().getRotation()) - { - default: - case Surface.ROTATION_0: - return 0; - case Surface.ROTATION_90: - return 90; - case Surface.ROTATION_180: - return 180; - case Surface.ROTATION_270: - return 270; - } - } - - /** - * 获取当前屏幕截图,包含状态栏 - * - * @param activity activity - * @return Bitmap - */ - public static Bitmap captureWithStatusBar(Activity activity) - { - View view = activity.getWindow().getDecorView(); - view.setDrawingCacheEnabled(true); - view.buildDrawingCache(); - Bitmap bmp = view.getDrawingCache(); - DisplayMetrics dm = new DisplayMetrics(); - activity.getWindowManager().getDefaultDisplay().getMetrics(dm); - Bitmap ret = Bitmap.createBitmap(bmp, 0, 0, dm.widthPixels, dm.heightPixels); - view.destroyDrawingCache(); - return ret; - } - - /** - * 获取当前屏幕截图,不包含状态栏 - * - * @param activity activity - * @return Bitmap - */ - public static Bitmap captureWithoutStatusBar(Activity activity) - { - View view = activity.getWindow().getDecorView(); - view.setDrawingCacheEnabled(true); - view.buildDrawingCache(); - Bitmap bmp = view.getDrawingCache(); - int statusBarHeight = BarTool.getStatusBarHeight(activity); - DisplayMetrics dm = new DisplayMetrics(); - activity.getWindowManager().getDefaultDisplay().getMetrics(dm); - Bitmap ret = Bitmap.createBitmap(bmp, 0, statusBarHeight, dm.widthPixels, - dm.heightPixels - statusBarHeight); - view.destroyDrawingCache(); - return ret; - } - - /** - * 判断是否锁屏 - */ - public static boolean isScreenLock() - { - return Easy.getDefault().getKeyguardManager().inKeyguardRestrictedInputMode(); - } - +package com.ayvytr.easyandroidlibrary.tools.withcontext; + +import android.app.Activity; +import android.content.pm.ActivityInfo; +import android.content.res.Configuration; +import android.graphics.Bitmap; +import android.util.DisplayMetrics; +import android.view.Surface; +import android.view.View; +import android.view.WindowManager; + +import com.ayvytr.easyandroidlibrary.Easy; +import com.ayvytr.easyandroidlibrary.exception.UnsupportedInitializationException; + +import static com.ayvytr.easyandroidlibrary.tools.withcontext.ResTool.getConfiguration; + +/** + * ScreenTool 获取屏幕尺寸, + */ +public class ScreenTool +{ + private ScreenTool() + { + throw new UnsupportedInitializationException(); + } + + /** + * 获取屏幕DisplayMetrics + */ + public static DisplayMetrics getDisplayMetrics() + { + WindowManager windowManager = Easy.getDefault().getWindowManager(); + // 创建了一张白纸 + DisplayMetrics dm = new DisplayMetrics(); + // 给白纸设置宽高 + windowManager.getDefaultDisplay().getMetrics(dm); + return dm; + } + + /** + * 获取屏幕的宽度(单位:px) + */ + public static int getScreenWidth() + { + return getDisplayMetrics().widthPixels; + } + + /** + * 获取屏幕的高度(单位:px) + */ + public static int getScreenHeight() + { + return getDisplayMetrics().heightPixels; + } + + /** + * 设置屏幕为横屏 + *

还有一种就是在Activity中加属性android:screenOrientation="landscape"

+ *

不设置Activity的android:configChanges时,切屏会重新调用各个生命周期,切横屏时会执行一次,切竖屏时会执行两次

+ *

设置Activity的android:configChanges="orientation"时,切屏还是会重新调用各个生命周期,切横、竖屏时只会执行一次

+ *

设置Activity的android:configChanges="orientation|keyboardHidden|screenSize"(4.0以上必须带最后一个参数)时 + * 切屏不会重新调用各个生命周期,只会执行onConfigurationChanged方法

+ * + * @param activity activity + */ + public static void setLandscape(Activity activity) + { + activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + } + + /** + * 设置屏幕为竖屏 + * + * @param activity activity + */ + public static void setPortrait(Activity activity) + { + activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + } + + /** + * 判断是否横屏 + */ + public static boolean isLandscape() + { + Configuration configuration = getConfiguration(); + return configuration.orientation == Configuration.ORIENTATION_LANDSCAPE; + } + + /** + * 判断是否竖屏 + */ + public static boolean isPortrait() + { + Configuration configuration = getConfiguration(); + return configuration.orientation == Configuration.ORIENTATION_PORTRAIT; + } + + /** + * 获取屏幕旋转角度 + * + * @param activity activity + * @return 屏幕旋转角度 + */ + public static int getScreenRotation(Activity activity) + { + switch(activity.getWindowManager().getDefaultDisplay().getRotation()) + { + default: + case Surface.ROTATION_0: + return 0; + case Surface.ROTATION_90: + return 90; + case Surface.ROTATION_180: + return 180; + case Surface.ROTATION_270: + return 270; + } + } + + /** + * 获取当前屏幕截图,包含状态栏 + * + * @param activity activity + * @return Bitmap + */ + public static Bitmap captureWithStatusBar(Activity activity) + { + View view = activity.getWindow().getDecorView(); + view.setDrawingCacheEnabled(true); + view.buildDrawingCache(); + Bitmap bmp = view.getDrawingCache(); + DisplayMetrics dm = new DisplayMetrics(); + activity.getWindowManager().getDefaultDisplay().getMetrics(dm); + Bitmap ret = Bitmap.createBitmap(bmp, 0, 0, dm.widthPixels, dm.heightPixels); + view.destroyDrawingCache(); + return ret; + } + + /** + * 获取当前屏幕截图,不包含状态栏 + * + * @param activity activity + * @return Bitmap + */ + public static Bitmap captureWithoutStatusBar(Activity activity) + { + View view = activity.getWindow().getDecorView(); + view.setDrawingCacheEnabled(true); + view.buildDrawingCache(); + Bitmap bmp = view.getDrawingCache(); + int statusBarHeight = BarTool.getStatusBarHeight(activity); + DisplayMetrics dm = new DisplayMetrics(); + activity.getWindowManager().getDefaultDisplay().getMetrics(dm); + Bitmap ret = Bitmap.createBitmap(bmp, 0, statusBarHeight, dm.widthPixels, + dm.heightPixels - statusBarHeight); + view.destroyDrawingCache(); + return ret; + } + + /** + * 判断是否锁屏 + */ + public static boolean isScreenLock() + { + return Easy.getDefault().getKeyguardManager().inKeyguardRestrictedInputMode(); + } + } \ No newline at end of file diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ToastTool.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ToastTool.java similarity index 81% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ToastTool.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ToastTool.java index d66f315..8696999 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/ToastTool.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/tools/withcontext/ToastTool.java @@ -1,58 +1,62 @@ -package com.ayvytr.easydeveloper.tools.withcontext; - -import android.widget.Toast; - -import com.ayvytr.easydeveloper.Easy; -import com.ayvytr.easydeveloper.exception.UnsupportedInitializationException; - -/** - * Created by davidwang on 2017/3/15. - * - * Toast工具,简便Toast创建和输出 - */ - -public class ToastTool -{ - private ToastTool() - { - throw new UnsupportedInitializationException(); - } - - /** - * 创建Toast并返回 - * @param text Toast文本 - * @return Toast - */ - public static Toast make(String text) - { - return Toast.makeText(Easy.getContext(), text, Toast.LENGTH_SHORT); - } - - /** - * 创建LENGTH_LONG Toast并返回 - * @param text Toast文本 - * @return Toast - */ - public static Toast makeLong(String text) - { - return Toast.makeText(Easy.getContext(), text, Toast.LENGTH_LONG); - } - - /** - * 显示Toast - * @param text Toast文本 - */ - public static void show(String text) - { - make(text).show(); - } - - /** - * 显示LENGTH_LONG Toast - * @param text Toast文本 - */ - public static void showLong(String text) - { - makeLong(text).show(); - } -} +package com.ayvytr.easyandroidlibrary.tools.withcontext; + +import android.widget.Toast; + +import com.ayvytr.easyandroidlibrary.Easy; +import com.ayvytr.easyandroidlibrary.exception.UnsupportedInitializationException; + +/** + * Created by davidwang on 2017/3/15. + *

+ * Toast工具,简便Toast创建和输出 + */ + +public class ToastTool +{ + private ToastTool() + { + throw new UnsupportedInitializationException(); + } + + /** + * 创建Toast并返回 + * + * @param text Toast文本 + * @return Toast + */ + public static Toast make(String text) + { + return Toast.makeText(Easy.getContext(), text, Toast.LENGTH_SHORT); + } + + /** + * 创建LENGTH_LONG Toast并返回 + * + * @param text Toast文本 + * @return Toast + */ + public static Toast makeLong(String text) + { + return Toast.makeText(Easy.getContext(), text, Toast.LENGTH_LONG); + } + + /** + * 显示Toast + * + * @param text Toast文本 + */ + public static void show(String text) + { + make(text).show(); + } + + /** + * 显示LENGTH_LONG Toast + * + * @param text Toast文本 + */ + public static void showLong(String text) + { + makeLong(text).show(); + } +} diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/view/CenterTextView.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/view/CenterTextView.java similarity index 93% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/view/CenterTextView.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/view/CenterTextView.java index 1db826f..bbe2e03 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/view/CenterTextView.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/view/CenterTextView.java @@ -1,4 +1,4 @@ -package com.ayvytr.easydeveloper.view; +package com.ayvytr.easyandroidlibrary.view; import android.content.Context; import android.support.v7.widget.AppCompatTextView; diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/view/LeftCenterTextView.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/view/LeftCenterTextView.java similarity index 93% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/view/LeftCenterTextView.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/view/LeftCenterTextView.java index 9164aaf..99dcb50 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/view/LeftCenterTextView.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/view/LeftCenterTextView.java @@ -1,4 +1,4 @@ -package com.ayvytr.easydeveloper.view; +package com.ayvytr.easyandroidlibrary.view; import android.content.Context; import android.support.v7.widget.AppCompatTextView; diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/view/RightCenterTextView.java b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/view/RightCenterTextView.java similarity index 85% rename from easydeveloper/src/main/java/com/ayvytr/easydeveloper/view/RightCenterTextView.java rename to easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/view/RightCenterTextView.java index b90e076..36abaed 100644 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/view/RightCenterTextView.java +++ b/easyAndroidLibrary/src/main/java/com/ayvytr/easyandroidlibrary/view/RightCenterTextView.java @@ -1,4 +1,4 @@ -package com.ayvytr.easydeveloper.view; +package com.ayvytr.easyandroidlibrary.view; import android.content.Context; import android.support.v7.widget.AppCompatTextView; @@ -24,6 +24,6 @@ public RightCenterTextView(Context context, AttributeSet attrs) public RightCenterTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); - setGravity(Gravity.CENTER_VERTICAL|Gravity.RIGHT); + setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); } } diff --git a/easydeveloper/src/main/res/values/dimens.xml b/easyAndroidLibrary/src/main/res/values/dimens.xml similarity index 100% rename from easydeveloper/src/main/res/values/dimens.xml rename to easyAndroidLibrary/src/main/res/values/dimens.xml diff --git a/easydeveloper/src/main/res/values/dp.xml b/easyAndroidLibrary/src/main/res/values/dp.xml similarity index 100% rename from easydeveloper/src/main/res/values/dp.xml rename to easyAndroidLibrary/src/main/res/values/dp.xml diff --git a/easydeveloper/src/main/res/values/sp.xml b/easyAndroidLibrary/src/main/res/values/sp.xml similarity index 100% rename from easydeveloper/src/main/res/values/sp.xml rename to easyAndroidLibrary/src/main/res/values/sp.xml diff --git a/easyAndroidLibrary/src/main/res/values/strings.xml b/easyAndroidLibrary/src/main/res/values/strings.xml new file mode 100644 index 0000000..a31be67 --- /dev/null +++ b/easyAndroidLibrary/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + EasyAndroidLibrary + diff --git a/easydeveloper/src/main/res/values/styles.xml b/easyAndroidLibrary/src/main/res/values/styles.xml similarity index 100% rename from easydeveloper/src/main/res/values/styles.xml rename to easyAndroidLibrary/src/main/res/values/styles.xml diff --git a/app/src/test/java/com/ayvytr/androideasydeveloper/ExampleUnitTest.java b/easyAndroidLibrary/src/test/java/com/ayvytr/easyandroidlibrary/ExampleUnitTest.java similarity index 90% rename from app/src/test/java/com/ayvytr/androideasydeveloper/ExampleUnitTest.java rename to easyAndroidLibrary/src/test/java/com/ayvytr/easyandroidlibrary/ExampleUnitTest.java index 7c4d686..382f1ae 100644 --- a/app/src/test/java/com/ayvytr/androideasydeveloper/ExampleUnitTest.java +++ b/easyAndroidLibrary/src/test/java/com/ayvytr/easyandroidlibrary/ExampleUnitTest.java @@ -1,4 +1,4 @@ -package com.ayvytr.androideasydeveloper; +package com.ayvytr.easyandroidlibrary; import org.junit.Test; diff --git a/easydeveloper/src/test/java/com/ayvytr/easydeveloper/TextToolTest.java b/easyAndroidLibrary/src/test/java/com/ayvytr/easyandroidlibrary/TextToolTest.java similarity index 91% rename from easydeveloper/src/test/java/com/ayvytr/easydeveloper/TextToolTest.java rename to easyAndroidLibrary/src/test/java/com/ayvytr/easyandroidlibrary/TextToolTest.java index 440d9b5..c4a0208 100644 --- a/easydeveloper/src/test/java/com/ayvytr/easydeveloper/TextToolTest.java +++ b/easyAndroidLibrary/src/test/java/com/ayvytr/easyandroidlibrary/TextToolTest.java @@ -1,77 +1,78 @@ -package com.ayvytr.easydeveloper; - -import com.ayvytr.easydeveloper.tools.TextTool; - -import org.junit.Test; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -/** - * Created by davidwang on 2017/3/15. - * 测试 TextTool类 - * @see TextTool - */ - -public class TextToolTest -{ - @Test - public void isEmpty() - { - String str = null; - assertEquals(TextTool.isEmpty(str), true); - str = ""; - assertEquals(TextTool.isEmpty(str), true); - } - - @Test - public void reverse() - { - String src = "abcdefg"; - String reverse = TextTool.reverse(src); - assertEquals(src, TextTool.reverse(reverse)); - - src = "中国人"; - reverse = TextTool.reverse(src); - assertEquals(src, TextTool.reverse(reverse)); - - src = "支A持b国C货"; - reverse = TextTool.reverse(src); - assertEquals(src, TextTool.reverse(reverse)); - } - - @Test - public void regex() - { - String src = "a;b;c;;;"; - String[] split = TextTool.split(src, ";"); - String[] values = new String[] - { - "a", - "b", - "c" - }; - assertArrayEquals(split, values); - - src = "ab::cdddd::aaaaa::;:::::::::"; - split = TextTool.split(src, "::"); - values = new String[] - { - "ab", - "cdddd", - "aaaaa", - ";:" - }; - assertArrayEquals(split, values); - } - - @Test - public void isBlock() - { - String str = null; - assertEquals(TextTool.isBlank(str), true); - str = ""; - assertEquals(TextTool.isBlank(str), true); - str = " "; - } -} +package com.ayvytr.easyandroidlibrary; + +import com.ayvytr.easyandroidlibrary.tools.TextTool; + +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +/** + * Created by davidwang on 2017/3/15. + * 测试 TextTool类 + * + * @see TextTool + */ + +public class TextToolTest +{ + @Test + public void isEmpty() + { + String str = null; + assertEquals(TextTool.isEmpty(str), true); + str = ""; + assertEquals(TextTool.isEmpty(str), true); + } + + @Test + public void reverse() + { + String src = "abcdefg"; + String reverse = TextTool.reverse(src); + assertEquals(src, TextTool.reverse(reverse)); + + src = "中国人"; + reverse = TextTool.reverse(src); + assertEquals(src, TextTool.reverse(reverse)); + + src = "支A持b国C货"; + reverse = TextTool.reverse(src); + assertEquals(src, TextTool.reverse(reverse)); + } + + @Test + public void regex() + { + String src = "a;b;c;;;"; + String[] split = TextTool.split(src, ";"); + String[] values = new String[] + { + "a", + "b", + "c" + }; + assertArrayEquals(split, values); + + src = "ab::cdddd::aaaaa::;:::::::::"; + split = TextTool.split(src, "::"); + values = new String[] + { + "ab", + "cdddd", + "aaaaa", + ";:" + }; + assertArrayEquals(split, values); + } + + @Test + public void isBlock() + { + String str = null; + assertEquals(TextTool.isBlank(str), true); + str = ""; + assertEquals(TextTool.isBlank(str), true); + str = " "; + } +} diff --git a/easydeveloper/src/main/AndroidManifest.xml b/easydeveloper/src/main/AndroidManifest.xml deleted file mode 100644 index 3ee8254..0000000 --- a/easydeveloper/src/main/AndroidManifest.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/FileUtils.java b/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/FileUtils.java deleted file mode 100644 index 058affb..0000000 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/FileUtils.java +++ /dev/null @@ -1,1513 +0,0 @@ -package com.ayvytr.easydeveloper.tools; - -/** - *

- *     author: Blankj
- *     blog  : http://blankj.com
- *     time  : 2016/8/11
- *     desc  : 文件相关工具类
- * 
- */ -//TODO 修正错误 -class FileUtils -{ -// -// private FileUtils() -// { -// throw new UnsupportedOperationException("u can't instantiate me..."); -// } -// -// /** -// * 根据文件路径获取文件 -// * -// * @param filePath 文件路径 -// * @return 文件 -// */ -// public static File getFileByPath(String filePath) -// { -// return TextTool.isEmpty(filePath) ? null : new File(filePath); -// } -// -// /** -// * 判断文件是否存在 -// * -// * @param filePath 文件路径 -// * @return {@code true}: 存在
{@code false}: 不存在 -// */ -// public static boolean isFileExists(String filePath) -// { -// return isFileExists(getFileByPath(filePath)); -// } -// -// /** -// * 判断文件是否存在 -// * -// * @param file 文件 -// * @return {@code true}: 存在
{@code false}: 不存在 -// */ -// public static boolean isFileExists(File file) -// { -// return file != null && file.exists(); -// } -// -// /** -// * 重命名文件 -// * -// * @param filePath 文件路径 -// * @param newName 新名称 -// * @return {@code true}: 重命名成功
{@code false}: 重命名失败 -// */ -// public static boolean rename(String filePath, String newName) -// { -// return rename(getFileByPath(filePath), newName); -// } -// -// /** -// * 重命名文件 -// * -// * @param file 文件 -// * @param newName 新名称 -// * @return {@code true}: 重命名成功
{@code false}: 重命名失败 -// */ -// public static boolean rename(File file, String newName) -// { -// if(file == null || file.exists()) -// { -// return false; -// } -// -// // 新的文件名为空返回false -// if(TextTool.isBlank(newName)) -// { -// return false; -// } -// // 如果文件名没有改变返回true -// if(newName.equals(file.getName())) -// { -// return true; -// } -// File newFile = new File(file.getParent() + File.separator + newName); -// // 如果重命名的文件已存在返回false -// return !newFile.exists() -// && file.renameTo(newFile); -// } -// -// /** -// * 判断是否是目录 -// * -// * @param dirPath 目录路径 -// * @return {@code true}: 是
{@code false}: 否 -// */ -// public static boolean isDir(String dirPath) -// { -// return isDir(getFileByPath(dirPath)); -// } -// -// /** -// * 判断是否是目录 -// * -// * @param file 文件 -// * @return {@code true}: 是
{@code false}: 否 -// */ -// public static boolean isDir(File file) -// { -// return isFileExists(file) && file.isDirectory(); -// } -// -// /** -// * 判断是否是文件 -// * -// * @param filePath 文件路径 -// * @return {@code true}: 是
{@code false}: 否 -// */ -// public static boolean isFile(String filePath) -// { -// return isFile(getFileByPath(filePath)); -// } -// -// /** -// * 判断是否是文件 -// * -// * @param file 文件 -// * @return {@code true}: 是
{@code false}: 否 -// */ -// public static boolean isFile(File file) -// { -// return isFileExists(file) && file.isFile(); -// } -// -// /** -// * 判断目录是否存在,不存在则判断是否创建成功 -// * -// * @param dirPath 目录路径 -// * @return {@code true}: 存在或创建成功
{@code false}: 不存在或创建失败 -// */ -// public static boolean createOrExistsDir(String dirPath) -// { -// return createOrExistsDir(getFileByPath(dirPath)); -// } -// -// /** -// * 判断目录是否存在,不存在则判断是否创建成功 -// * -// * @param file 文件 -// * @return {@code true}: 存在或创建成功
{@code false}: 不存在或创建失败 -// */ -// public static boolean createOrExistsDir(File file) -// { -// // 如果存在,是目录则返回true,是文件则返回false,不存在则返回是否创建成功 -// return file != null && (file.exists() ? file.isDirectory() : file.mkdirs()); -// } -// -// /** -// * 判断文件是否存在,不存在则判断是否创建成功 -// * -// * @param filePath 文件路径 -// * @return {@code true}: 存在或创建成功
{@code false}: 不存在或创建失败 -// */ -// public static boolean createOrExistsFile(String filePath) -// { -// return createOrExistsFile(getFileByPath(filePath)); -// } -// -// /** -// * 判断文件是否存在,不存在则判断是否创建成功 -// * -// * @param file 文件 -// * @return {@code true}: 存在或创建成功
{@code false}: 不存在或创建失败 -// */ -// public static boolean createOrExistsFile(File file) -// { -// if(file == null) return false; -// // 如果存在,是文件则返回true,是目录则返回false -// if(file.exists()) return file.isFile(); -// if(!createOrExistsDir(file.getParentFile())) return false; -// try -// { -// return file.createNewFile(); -// } catch(IOException e) -// { -// e.printStackTrace(); -// return false; -// } -// } -// -// /** -// * 判断文件是否存在,存在则在创建之前删除 -// * -// * @param filePath 文件路径 -// * @return {@code true}: 创建成功
{@code false}: 创建失败 -// */ -// public static boolean createFileByDeleteOldFile(String filePath) -// { -// return createFileByDeleteOldFile(getFileByPath(filePath)); -// } -// -// /** -// * 判断文件是否存在,存在则在创建之前删除 -// * -// * @param file 文件 -// * @return {@code true}: 创建成功
{@code false}: 创建失败 -// */ -// public static boolean createFileByDeleteOldFile(File file) -// { -// if(file == null) return false; -// // 文件存在并且删除失败返回false -// if(file.exists() && file.isFile() && !file.delete()) return false; -// // 创建目录失败返回false -// if(!createOrExistsDir(file.getParentFile())) return false; -// try -// { -// return file.createNewFile(); -// } catch(IOException e) -// { -// e.printStackTrace(); -// return false; -// } -// } -// -// /** -// * 复制或移动目录 -// * -// * @param srcDirPath 源目录路径 -// * @param destDirPath 目标目录路径 -// * @param isMove 是否移动 -// * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 -// */ -// private static boolean copyOrMoveDir(String srcDirPath, String destDirPath, boolean isMove) -// { -// return copyOrMoveDir(getFileByPath(srcDirPath), getFileByPath(destDirPath), isMove); -// } -// -// /** -// * 复制或移动目录 -// * -// * @param srcDir 源目录 -// * @param destDir 目标目录 -// * @param isMove 是否移动 -// * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 -// */ -// private static boolean copyOrMoveDir(File srcDir, File destDir, boolean isMove) -// { -// if(srcDir == null || destDir == null) return false; -// // 如果目标目录在源目录中则返回false,看不懂的话好好想想递归怎么结束 -// // srcPath : F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res -// // destPath: F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res1 -// // 为防止以上这种情况出现出现误判,须分别在后面加个路径分隔符 -// String srcPath = srcDir.getPath() + File.separator; -// String destPath = destDir.getPath() + File.separator; -// if(destPath.contains(srcPath)) return false; -// // 源文件不存在或者不是目录则返回false -// if(!srcDir.exists() || !srcDir.isDirectory()) return false; -// // 目标目录不存在返回false -// if(!createOrExistsDir(destDir)) return false; -// File[] files = srcDir.listFiles(); -// for(File file : files) -// { -// File oneDestFile = new File(destPath + file.getName()); -// if(file.isFile()) -// { -// // 如果操作失败返回false -// if(!copyOrMoveFile(file, oneDestFile, isMove)) return false; -// } -// else if(file.isDirectory()) -// { -// // 如果操作失败返回false -// if(!copyOrMoveDir(file, oneDestFile, isMove)) return false; -// } -// } -// return !isMove || deleteDir(srcDir); -// } -// -// /** -// * 复制或移动文件 -// * -// * @param srcFilePath 源文件路径 -// * @param destFilePath 目标文件路径 -// * @param isMove 是否移动 -// * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 -// */ -// private static boolean copyOrMoveFile(String srcFilePath, String destFilePath, boolean isMove) -// { -// return copyOrMoveFile(getFileByPath(srcFilePath), getFileByPath(destFilePath), isMove); -// } -// -// /** -// * 复制或移动文件 -// * -// * @param srcFile 源文件 -// * @param destFile 目标文件 -// * @param isMove 是否移动 -// * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 -// */ -// private static boolean copyOrMoveFile(File srcFile, File destFile, boolean isMove) -// { -// if(srcFile == null || destFile == null) return false; -// // 源文件不存在或者不是文件则返回false -// if(!srcFile.exists() || !srcFile.isFile()) return false; -// // 目标文件存在且是文件则返回false -// if(destFile.exists() && destFile.isFile()) return false; -// // 目标目录不存在返回false -// if(!createOrExistsDir(destFile.getParentFile())) return false; -// try -// { -// return writeFileFromIS(destFile, new FileInputStream(srcFile), false) -// && !(isMove && !deleteFile(srcFile)); -// } catch(FileNotFoundException e) -// { -// e.printStackTrace(); -// return false; -// } -// } -// -// /** -// * 复制目录 -// * -// * @param srcDirPath 源目录路径 -// * @param destDirPath 目标目录路径 -// * @return {@code true}: 复制成功
{@code false}: 复制失败 -// */ -// public static boolean copyDir(String srcDirPath, String destDirPath) -// { -// return copyDir(getFileByPath(srcDirPath), getFileByPath(destDirPath)); -// } -// -// /** -// * 复制目录 -// * -// * @param srcDir 源目录 -// * @param destDir 目标目录 -// * @return {@code true}: 复制成功
{@code false}: 复制失败 -// */ -// public static boolean copyDir(File srcDir, File destDir) -// { -// return copyOrMoveDir(srcDir, destDir, false); -// } -// -// /** -// * 复制文件 -// * -// * @param srcFilePath 源文件路径 -// * @param destFilePath 目标文件路径 -// * @return {@code true}: 复制成功
{@code false}: 复制失败 -// */ -// public static boolean copyFile(String srcFilePath, String destFilePath) -// { -// return copyFile(getFileByPath(srcFilePath), getFileByPath(destFilePath)); -// } -// -// /** -// * 复制文件 -// * -// * @param srcFile 源文件 -// * @param destFile 目标文件 -// * @return {@code true}: 复制成功
{@code false}: 复制失败 -// */ -// public static boolean copyFile(File srcFile, File destFile) -// { -// return copyOrMoveFile(srcFile, destFile, false); -// } -// -// /** -// * 移动目录 -// * -// * @param srcDirPath 源目录路径 -// * @param destDirPath 目标目录路径 -// * @return {@code true}: 移动成功
{@code false}: 移动失败 -// */ -// public static boolean moveDir(String srcDirPath, String destDirPath) -// { -// return moveDir(getFileByPath(srcDirPath), getFileByPath(destDirPath)); -// } -// -// /** -// * 移动目录 -// * -// * @param srcDir 源目录 -// * @param destDir 目标目录 -// * @return {@code true}: 移动成功
{@code false}: 移动失败 -// */ -// public static boolean moveDir(File srcDir, File destDir) -// { -// return copyOrMoveDir(srcDir, destDir, true); -// } -// -// /** -// * 移动文件 -// * -// * @param srcFilePath 源文件路径 -// * @param destFilePath 目标文件路径 -// * @return {@code true}: 移动成功
{@code false}: 移动失败 -// */ -// public static boolean moveFile(String srcFilePath, String destFilePath) -// { -// return moveFile(getFileByPath(srcFilePath), getFileByPath(destFilePath)); -// } -// -// /** -// * 移动文件 -// * -// * @param srcFile 源文件 -// * @param destFile 目标文件 -// * @return {@code true}: 移动成功
{@code false}: 移动失败 -// */ -// public static boolean moveFile(File srcFile, File destFile) -// { -// return copyOrMoveFile(srcFile, destFile, true); -// } -// -// /** -// * 删除目录 -// * -// * @param dirPath 目录路径 -// * @return {@code true}: 删除成功
{@code false}: 删除失败 -// */ -// public static boolean deleteDir(String dirPath) -// { -// return deleteDir(getFileByPath(dirPath)); -// } -// -// /** -// * 删除目录 -// * -// * @param dir 目录 -// * @return {@code true}: 删除成功
{@code false}: 删除失败 -// */ -// public static boolean deleteDir(File dir) -// { -// if(dir == null) return false; -// // 目录不存在返回true -// if(!dir.exists()) return true; -// // 不是目录返回false -// if(!dir.isDirectory()) return false; -// // 现在文件存在且是文件夹 -// File[] files = dir.listFiles(); -// if(files != null && files.length != 0) -// { -// for(File file : files) -// { -// if(file.isFile()) -// { -// if(!deleteFile(file)) return false; -// } -// else if(file.isDirectory()) -// { -// if(!deleteDir(file)) return false; -// } -// } -// } -// return dir.delete(); -// } -// -// /** -// * 删除文件 -// * -// * @param srcFilePath 文件路径 -// * @return {@code true}: 删除成功
{@code false}: 删除失败 -// */ -// public static boolean deleteFile(String srcFilePath) -// { -// return deleteFile(getFileByPath(srcFilePath)); -// } -// -// /** -// * 删除文件 -// * -// * @param file 文件 -// * @return {@code true}: 删除成功
{@code false}: 删除失败 -// */ -// public static boolean deleteFile(File file) -// { -// return file != null && (!file.exists() || file.isFile() && file.delete()); -// } -// -// /** -// * 删除目录下的所有文件 -// * -// * @param dirPath 目录路径 -// * @return {@code true}: 删除成功
{@code false}: 删除失败 -// */ -// public static boolean deleteFilesInDir(String dirPath) -// { -// return deleteFilesInDir(getFileByPath(dirPath)); -// } -// -// /** -// * 删除目录下的所有文件 -// * -// * @param dir 目录 -// * @return {@code true}: 删除成功
{@code false}: 删除失败 -// */ -// public static boolean deleteFilesInDir(File dir) -// { -// if(dir == null) return false; -// // 目录不存在返回true -// if(!dir.exists()) return true; -// // 不是目录返回false -// if(!dir.isDirectory()) return false; -// // 现在文件存在且是文件夹 -// File[] files = dir.listFiles(); -// if(files != null && files.length != 0) -// { -// for(File file : files) -// { -// if(file.isFile()) -// { -// if(!deleteFile(file)) return false; -// } -// else if(file.isDirectory()) -// { -// if(!deleteDir(file)) return false; -// } -// } -// } -// return true; -// } -// -// /** -// * 获取目录下所有文件 -// * -// * @param dirPath 目录路径 -// * @param isRecursive 是否递归进子目录 -// * @return 文件链表 -// */ -// public static List listFilesInDir(String dirPath, boolean isRecursive) -// { -// return listFilesInDir(getFileByPath(dirPath), isRecursive); -// } -// -// /** -// * 获取目录下所有文件 -// * -// * @param dir 目录 -// * @param isRecursive 是否递归进子目录 -// * @return 文件链表 -// */ -// public static List listFilesInDir(File dir, boolean isRecursive) -// { -// if(!isDir(dir)) return null; -// if(isRecursive) return listFilesInDir(dir); -// List list = new ArrayList<>(); -// File[] files = dir.listFiles(); -// if(files != null && files.length != 0) -// { -// Collections.addAll(list, files); -// } -// return list; -// } -// -// /** -// * 获取目录下所有文件包括子目录 -// * -// * @param dirPath 目录路径 -// * @return 文件链表 -// */ -// public static List listFilesInDir(String dirPath) -// { -// return listFilesInDir(getFileByPath(dirPath)); -// } -// -// /** -// * 获取目录下所有文件包括子目录 -// * -// * @param dir 目录 -// * @return 文件链表 -// */ -// public static List listFilesInDir(File dir) -// { -// if(!isDir(dir)) return null; -// List list = new ArrayList<>(); -// File[] files = dir.listFiles(); -// if(files != null && files.length != 0) -// { -// for(File file : files) -// { -// list.add(file); -// if(file.isDirectory()) -// { -// list.addAll(listFilesInDir(file)); -// } -// } -// } -// return list; -// } -// -// /** -// * 获取目录下所有后缀名为suffix的文件 -// *

大小写忽略

-// * -// * @param dirPath 目录路径 -// * @param suffix 后缀名 -// * @param isRecursive 是否递归进子目录 -// * @return 文件链表 -// */ -// public static List listFilesInDirWithFilter(String dirPath, String suffix, -// boolean isRecursive) -// { -// return listFilesInDirWithFilter(getFileByPath(dirPath), suffix, isRecursive); -// } -// -// /** -// * 获取目录下所有后缀名为suffix的文件 -// *

大小写忽略

-// * -// * @param dir 目录 -// * @param suffix 后缀名 -// * @param isRecursive 是否递归进子目录 -// * @return 文件链表 -// */ -// public static List listFilesInDirWithFilter(File dir, String suffix, boolean isRecursive) -// { -// if(isRecursive) return listFilesInDirWithFilter(dir, suffix); -// if(dir == null || !isDir(dir)) return null; -// List list = new ArrayList<>(); -// File[] files = dir.listFiles(); -// if(files != null && files.length != 0) -// { -// for(File file : files) -// { -// if(file.getName().toUpperCase().endsWith(suffix.toUpperCase())) -// { -// list.add(file); -// } -// } -// } -// return list; -// } -// -// /** -// * 获取目录下所有后缀名为suffix的文件包括子目录 -// *

大小写忽略

-// * -// * @param dirPath 目录路径 -// * @param suffix 后缀名 -// * @return 文件链表 -// */ -// public static List listFilesInDirWithFilter(String dirPath, String suffix) -// { -// return listFilesInDirWithFilter(getFileByPath(dirPath), suffix); -// } -// -// /** -// * 获取目录下所有后缀名为suffix的文件包括子目录 -// *

大小写忽略

-// * -// * @param dir 目录 -// * @param suffix 后缀名 -// * @return 文件链表 -// */ -// public static List listFilesInDirWithFilter(File dir, String suffix) -// { -// if(dir == null || !isDir(dir)) return null; -// List list = new ArrayList<>(); -// File[] files = dir.listFiles(); -// if(files != null && files.length != 0) -// { -// for(File file : files) -// { -// if(file.getName().toUpperCase().endsWith(suffix.toUpperCase())) -// { -// list.add(file); -// } -// if(file.isDirectory()) -// { -// list.addAll(listFilesInDirWithFilter(file, suffix)); -// } -// } -// } -// return list; -// } -// -// /** -// * 获取目录下所有符合filter的文件 -// * -// * @param dirPath 目录路径 -// * @param filter 过滤器 -// * @param isRecursive 是否递归进子目录 -// * @return 文件链表 -// */ -// public static List listFilesInDirWithFilter(String dirPath, FilenameFilter filter, -// boolean isRecursive) -// { -// return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive); -// } -// -// /** -// * 获取目录下所有符合filter的文件 -// * -// * @param dir 目录 -// * @param filter 过滤器 -// * @param isRecursive 是否递归进子目录 -// * @return 文件链表 -// */ -// public static List listFilesInDirWithFilter(File dir, FilenameFilter filter, -// boolean isRecursive) -// { -// if(isRecursive) return listFilesInDirWithFilter(dir, filter); -// if(dir == null || !isDir(dir)) return null; -// List list = new ArrayList<>(); -// File[] files = dir.listFiles(); -// if(files != null && files.length != 0) -// { -// for(File file : files) -// { -// if(filter.accept(file.getParentFile(), file.getName())) -// { -// list.add(file); -// } -// } -// } -// return list; -// } -// -// /** -// * 获取目录下所有符合filter的文件包括子目录 -// * -// * @param dirPath 目录路径 -// * @param filter 过滤器 -// * @return 文件链表 -// */ -// public static List listFilesInDirWithFilter(String dirPath, FilenameFilter filter) -// { -// return listFilesInDirWithFilter(getFileByPath(dirPath), filter); -// } -// -// /** -// * 获取目录下所有符合filter的文件包括子目录 -// * -// * @param dir 目录 -// * @param filter 过滤器 -// * @return 文件链表 -// */ -// public static List listFilesInDirWithFilter(File dir, FilenameFilter filter) -// { -// if(dir == null || !isDir(dir)) return null; -// List list = new ArrayList<>(); -// File[] files = dir.listFiles(); -// if(files != null && files.length != 0) -// { -// for(File file : files) -// { -// if(filter.accept(file.getParentFile(), file.getName())) -// { -// list.add(file); -// } -// if(file.isDirectory()) -// { -// list.addAll(listFilesInDirWithFilter(file, filter)); -// } -// } -// } -// return list; -// } -// -// /** -// * 获取目录下指定文件名的文件包括子目录 -// *

大小写忽略

-// * -// * @param dirPath 目录路径 -// * @param fileName 文件名 -// * @return 文件链表 -// */ -// public static List searchFileInDir(String dirPath, String fileName) -// { -// return searchFileInDir(getFileByPath(dirPath), fileName); -// } -// -// /** -// * 获取目录下指定文件名的文件包括子目录 -// *

大小写忽略

-// * -// * @param dir 目录 -// * @param fileName 文件名 -// * @return 文件链表 -// */ -// public static List searchFileInDir(File dir, String fileName) -// { -// if(dir == null || !isDir(dir)) return null; -// List list = new ArrayList<>(); -// File[] files = dir.listFiles(); -// if(files != null && files.length != 0) -// { -// for(File file : files) -// { -// if(file.getName().toUpperCase().equals(fileName.toUpperCase())) -// { -// list.add(file); -// } -// if(file.isDirectory()) -// { -// list.addAll(searchFileInDir(file, fileName)); -// } -// } -// } -// return list; -// } -// -// /** -// * 写入content到file,不处理filepath,content异常 -// * @param filepath 文件路径 -// * @param content 文件内容 -// * @param isAppend 是不是追加模式 -// */ -// public void writeFile(String filepath, String content, boolean isAppend) -// { -// writeFile(new File(filepath), content, isAppend); -// } -// -// /** -// * 写入content到file,不处理file,content异常 -// * @param file File -// * @param content 文件内容 -// * @param isAppend 是不是追加模式 -// */ -// public void writeFile(File file, String content, boolean isAppend) -// { -// try -// { -// FileOutputStream fileOutputStream = new FileOutputStream(file, isAppend); -// BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); -// bufferedOutputStream.write(content.getBytes()); -// bufferedOutputStream.close(); -// fileOutputStream.close(); -// } catch(IOException e) -// { -// e.printStackTrace(); -// } -// } -// -// -// /** -// * 指定编码按行读取文件到链表中 -// * -// * @param filePath 文件路径 -// * @param charsetName 编码格式 -// * @return 文件行链表 -// */ -// public static List readFile2List(String filePath, String charsetName) -// { -// return readFile2List(getFileByPath(filePath), charsetName); -// } -// -// /** -// * 指定编码按行读取文件到链表中 -// * -// * @param file 文件 -// * @param charsetName 编码格式 -// * @return 文件行链表 -// */ -// public static List readFile2List(File file, String charsetName) -// { -// return readFile2List(file, 0, 0x7FFFFFFF, charsetName); -// } -// -// /** -// * 指定编码按行读取文件到链表中 -// * -// * @param filePath 文件路径 -// * @param st 需要读取的开始行数 -// * @param end 需要读取的结束行数 -// * @param charsetName 编码格式 -// * @return 包含制定行的list -// */ -// public static List readFile2List(String filePath, int st, int end, String -// charsetName) -// { -// return readFile2List(getFileByPath(filePath), st, end, charsetName); -// } -// -// /** -// * 指定编码按行读取文件到链表中 -// * -// * @param file 文件 -// * @param st 需要读取的开始行数 -// * @param end 需要读取的结束行数 -// * @param charsetName 编码格式 -// * @return 包含从start行到end行的list -// */ -// public static List readFile2List(File file, int st, int end, String charsetName) -// { -// if(file == null) return null; -// if(st > end) return null; -// BufferedReader reader = null; -// try -// { -// String line; -// int curLine = 1; -// List list = new ArrayList<>(); -// if(StringUtils.isSpace(charsetName)) -// { -// reader = new BufferedReader(new FileReader(file)); -// } -// else -// { -// reader = new BufferedReader( -// new InputStreamReader(new FileInputStream(file), charsetName)); -// } -// while((line = reader.readLine()) != null) -// { -// if(curLine > end) break; -// if(st <= curLine && curLine <= end) list.add(line); -// ++curLine; -// } -// return list; -// } catch(IOException e) -// { -// e.printStackTrace(); -// return null; -// } finally -// { -// CloseUtils.closeIO(reader); -// } -// } -// -// /** -// * 指定编码按行读取文件到字符串中 -// * -// * @param filePath 文件路径 -// * @param charsetName 编码格式 -// * @return 字符串 -// */ -// public static String readFile2String(String filePath, String charsetName) -// { -// return readFile2String(getFileByPath(filePath), charsetName); -// } -// -// /** -// * 指定编码按行读取文件到字符串中 -// * -// * @param file 文件 -// * @param charsetName 编码格式 -// * @return 字符串 -// */ -// public static String readFile2String(File file, String charsetName) -// { -// if(file == null) return null; -// BufferedReader reader = null; -// try -// { -// StringBuilder sb = new StringBuilder(); -// if(StringUtils.isSpace(charsetName)) -// { -// reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); -// } -// else -// { -// reader = new BufferedReader( -// new InputStreamReader(new FileInputStream(file), charsetName)); -// } -// String line; -// while((line = reader.readLine()) != null) -// { -// sb.append(line).append("\r\n");// windows系统换行为\r\n,Linux为\n -// } -// // 要去除最后的换行符 -// return sb.delete(sb.length() - 2, sb.length()).toString(); -// } catch(IOException e) -// { -// e.printStackTrace(); -// return null; -// } finally -// { -// CloseUtils.closeIO(reader); -// } -// } -// -// /** -// * 读取文件到字符数组中 -// * -// * @param filePath 文件路径 -// * @return 字符数组 -// */ -// public static byte[] readFile2Bytes(String filePath) -// { -// return readFile2Bytes(getFileByPath(filePath)); -// } -// -// /** -// * 读取文件到字符数组中 -// * -// * @param file 文件 -// * @return 字符数组 -// */ -// public static byte[] readFile2Bytes(File file) -// { -// if(file == null) return null; -// try -// { -// return inputStream2Bytes(new FileInputStream(file)); -// } catch(FileNotFoundException e) -// { -// e.printStackTrace(); -// return null; -// } -// } -// -// /** -// * 获取文件最后修改的毫秒时间戳 -// * -// * @param filePath 文件路径 -// * @return 文件最后修改的毫秒时间戳 -// */ -// public static long getFileLastModified(String filePath) -// { -// return getFileLastModified(getFileByPath(filePath)); -// } -// -// /** -// * 获取文件最后修改的毫秒时间戳 -// * -// * @param file 文件 -// * @return 文件最后修改的毫秒时间戳 -// */ -// public static long getFileLastModified(File file) -// { -// if(file == null) return -1; -// return file.lastModified(); -// } -// -// /** -// * 简单获取文件编码格式 -// * -// * @param filePath 文件路径 -// * @return 文件编码 -// */ -// public static String getFileCharsetSimple(String filePath) -// { -// return getFileCharsetSimple(getFileByPath(filePath)); -// } -// -// /** -// * 简单获取文件编码格式 -// * -// * @param file 文件 -// * @return 文件编码 -// */ -// public static String getFileCharsetSimple(File file) -// { -// int p = 0; -// InputStream is = null; -// try -// { -// is = new BufferedInputStream(new FileInputStream(file)); -// p = (is.read() << 8) + is.read(); -// } catch(IOException e) -// { -// e.printStackTrace(); -// } finally -// { -// CloseUtils.closeIO(is); -// } -// switch(p) -// { -// case 0xefbb: -// return "UTF-8"; -// case 0xfffe: -// return "Unicode"; -// case 0xfeff: -// return "UTF-16BE"; -// default: -// return "GBK"; -// } -// } -// -// /** -// * 获取文件行数 -// * -// * @param filePath 文件路径 -// * @return 文件行数 -// */ -// public static int getFileLines(String filePath) -// { -// return getFileLines(getFileByPath(filePath)); -// } -// -// /** -// * 获取文件行数 -// * -// * @param file 文件 -// * @return 文件行数 -// */ -// public static int getFileLines(File file) -// { -// int count = 1; -// InputStream is = null; -// try -// { -// is = new BufferedInputStream(new FileInputStream(file)); -// byte[] buffer = new byte[1024]; -// int readChars; -// while((readChars = is.read(buffer, 0, 1024)) != -1) -// { -// for(int i = 0; i < readChars; ++i) -// { -// if(buffer[i] == '\n') ++count; -// } -// } -// } catch(IOException e) -// { -// e.printStackTrace(); -// } finally -// { -// CloseUtils.closeIO(is); -// } -// return count; -// } -// -// /** -// * 获取目录大小 -// * -// * @param dirPath 目录路径 -// * @return 文件大小 -// */ -// public static String getDirSize(String dirPath) -// { -// return getDirSize(getFileByPath(dirPath)); -// } -// -// /** -// * 获取目录大小 -// * -// * @param dir 目录 -// * @return 文件大小 -// */ -// public static String getDirSize(File dir) -// { -// long len = getDirLength(dir); -// return len == -1 ? "" : byte2FitMemorySize(len); -// } -// -// /** -// * 获取文件大小 -// * -// * @param filePath 文件路径 -// * @return 文件大小 -// */ -// public static String getFileSize(String filePath) -// { -// return getFileSize(getFileByPath(filePath)); -// } -// -// /** -// * 获取文件大小 -// * -// * @param file 文件 -// * @return 文件大小 -// */ -// public static String getFileSize(File file) -// { -// long len = getFileLength(file); -// return len == -1 ? "" : byte2FitMemorySize(len); -// } -// -// /** -// * 获取目录长度 -// * -// * @param dirPath 目录路径 -// * @return 文件大小 -// */ -// public static long getDirLength(String dirPath) -// { -// return getDirLength(getFileByPath(dirPath)); -// } -// -// /** -// * 获取目录长度 -// * -// * @param dir 目录 -// * @return 文件大小 -// */ -// public static long getDirLength(File dir) -// { -// if(!isDir(dir)) return -1; -// long len = 0; -// File[] files = dir.listFiles(); -// if(files != null && files.length != 0) -// { -// for(File file : files) -// { -// if(file.isDirectory()) -// { -// len += getDirLength(file); -// } -// else -// { -// len += file.length(); -// } -// } -// } -// return len; -// } -// -// /** -// * 获取文件长度 -// * -// * @param filePath 文件路径 -// * @return 文件大小 -// */ -// public static long getFileLength(String filePath) -// { -// return getFileLength(getFileByPath(filePath)); -// } -// -// /** -// * 获取文件长度 -// * -// * @param file 文件 -// * @return 文件大小 -// */ -// public static long getFileLength(File file) -// { -// if(!isFile(file)) return -1; -// return file.length(); -// } -// -// /** -// * 获取文件的MD5校验码 -// * -// * @param filePath 文件路径 -// * @return 文件的MD5校验码 -// */ -// public static String getFileMD5ToString(String filePath) -// { -// File file = StringUtils.isSpace(filePath) ? null : new File(filePath); -// return getFileMD5ToString(file); -// } -// -// /** -// * 获取文件的MD5校验码 -// * -// * @param filePath 文件路径 -// * @return 文件的MD5校验码 -// */ -// public static byte[] getFileMD5(String filePath) -// { -// File file = StringUtils.isSpace(filePath) ? null : new File(filePath); -// return getFileMD5(file); -// } -// -// /** -// * 获取文件的MD5校验码 -// * -// * @param file 文件 -// * @return 文件的MD5校验码 -// */ -// public static String getFileMD5ToString(File file) -// { -// return bytes2HexString(getFileMD5(file)); -// } -// -// /** -// * 获取文件的MD5校验码 -// * -// * @param file 文件 -// * @return 文件的MD5校验码 -// */ -// public static byte[] getFileMD5(File file) -// { -// if(file == null) return null; -// DigestInputStream dis = null; -// try -// { -// FileInputStream fis = new FileInputStream(file); -// MessageDigest md = MessageDigest.getInstance("MD5"); -// dis = new DigestInputStream(fis, md); -// byte[] buffer = new byte[1024 * 256]; -// while(dis.read(buffer) > 0) ; -// md = dis.getMessageDigest(); -// return md.digest(); -// } catch(NoSuchAlgorithmException | IOException e) -// { -// e.printStackTrace(); -// } finally -// { -// CloseUtils.closeIO(dis); -// } -// return null; -// } -// -// /** -// * 获取全路径中的最长目录 -// * -// * @param file 文件 -// * @return filePath最长目录 -// */ -// public static String getDirName(File file) -// { -// if(file == null) return null; -// return getDirName(file.getPath()); -// } -// -// /** -// * 获取全路径中的最长目录 -// * -// * @param filePath 文件路径 -// * @return filePath最长目录 -// */ -// public static String getDirName(String filePath) -// { -// if(StringUtils.isSpace(filePath)) return filePath; -// int lastSep = filePath.lastIndexOf(File.separator); -// return lastSep == -1 ? "" : filePath.substring(0, lastSep + 1); -// } -// -// /** -// * 获取全路径中的文件名 -// * -// * @param file 文件 -// * @return 文件名 -// */ -// public static String getFileName(File file) -// { -// if(file == null) return null; -// return getFileName(file.getPath()); -// } -// -// /** -// * 获取全路径中的文件名 -// * -// * @param filePath 文件路径 -// * @return 文件名 -// */ -// public static String getFileName(String filePath) -// { -// if(StringUtils.isSpace(filePath)) return filePath; -// int lastSep = filePath.lastIndexOf(File.separator); -// return lastSep == -1 ? filePath : filePath.substring(lastSep + 1); -// } -// -// /** -// * 获取全路径中的不带拓展名的文件名 -// * -// * @param file 文件 -// * @return 不带拓展名的文件名 -// */ -// public static String getFileNameNoExtension(File file) -// { -// if(file == null) return null; -// return getFileNameNoExtension(file.getPath()); -// } -// -// /** -// * 获取全路径中的不带拓展名的文件名 -// * -// * @param filePath 文件路径 -// * @return 不带拓展名的文件名 -// */ -// public static String getFileNameNoExtension(String filePath) -// { -// if(StringUtils.isSpace(filePath)) return filePath; -// int lastPoi = filePath.lastIndexOf('.'); -// int lastSep = filePath.lastIndexOf(File.separator); -// if(lastSep == -1) -// { -// return (lastPoi == -1 ? filePath : filePath.substring(0, lastPoi)); -// } -// if(lastPoi == -1 || lastSep > lastPoi) -// { -// return filePath.substring(lastSep + 1); -// } -// return filePath.substring(lastSep + 1, lastPoi); -// } -// -// /** -// * 获取全路径中的文件拓展名 -// * -// * @param file 文件 -// * @return 文件拓展名 -// */ -// public static String getFileExtension(File file) -// { -// if(file == null) return null; -// return getFileExtension(file.getPath()); -// } -// -// /** -// * 获取全路径中的文件拓展名 -// * -// * @param filePath 文件路径 -// * @return 文件拓展名 -// */ -// public static String getFileExtension(String filePath) -// { -// if(StringUtils.isSpace(filePath)) return filePath; -// int lastPoi = filePath.lastIndexOf('.'); -// int lastSep = filePath.lastIndexOf(File.separator); -// if(lastPoi == -1 || lastSep >= lastPoi) return ""; -// return filePath.substring(lastPoi + 1); -// } -// -// /** copy from ConvertUtils **/ -// -// /** -// * inputStream转byteArr -// * -// * @param is 输入流 -// * @return 字节数组 -// */ -// private static byte[] inputStream2Bytes(InputStream is) -// { -// if(is == null) return null; -// return input2OutputStream(is).toByteArray(); -// } -// -// /** -// * inputStream转outputStream -// * -// * @param is 输入流 -// * @return outputStream子类 -// */ -// private static ByteArrayOutputStream input2OutputStream(InputStream is) -// { -// if(is == null) return null; -// try -// { -// ByteArrayOutputStream os = new ByteArrayOutputStream(); -// byte[] b = new byte[MemoryConstant.KB]; -// int len; -// while((len = is.read(b, 0, MemoryConstant.KB)) != -1) -// { -// os.write(b, 0, len); -// } -// return os; -// } catch(IOException e) -// { -// e.printStackTrace(); -// return null; -// } finally -// { -// CloseUtils.closeIO(is); -// } -// } -// -// private static final char hexDigits[] = {'0', -// '1', -// '2', -// '3', -// '4', -// '5', -// '6', -// '7', -// '8', -// '9', -// 'A', -// 'B', -// 'C', -// 'D', -// 'E', -// 'F'}; -// -// /** -// * byteArr转hexString -// *

例如:

-// * bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns 00A8 -// * -// * @param bytes 字节数组 -// * @return 16进制大写字符串 -// */ -// private static String bytes2HexString(byte[] bytes) -// { -// if(bytes == null) return null; -// int len = bytes.length; -// if(len <= 0) return null; -// char[] ret = new char[len << 1]; -// for(int i = 0, j = 0; i < len; i++) -// { -// ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f]; -// ret[j++] = hexDigits[bytes[i] & 0x0f]; -// } -// return new String(ret); -// } -// -// /** -// * 字节数转合适内存大小 -// *

保留3位小数

-// * -// * @param byteNum 字节数 -// * @return 合适内存大小 -// */ -// @SuppressLint("DefaultLocale") -// private static String byte2FitMemorySize(long byteNum) -// { -// if(byteNum < 0) -// { -// return "shouldn't be less than zero!"; -// } -// else if(byteNum < MemoryConstant.KB) -// { -// return String.format("%.3fB", (double) byteNum + 0.0005); -// } -// else if(byteNum < MemoryConstant.MB) -// { -// return String.format("%.3fKB", (double) byteNum / MemoryConstant.KB + 0.0005); -// } -// else if(byteNum < MemoryConstant.GB) -// { -// return String.format("%.3fMB", (double) byteNum / MemoryConstant.MB + 0.0005); -// } -// else -// { -// return String.format("%.3fGB", (double) byteNum / MemoryConstant.GB + 0.0005); -// } -// } -} \ No newline at end of file diff --git a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/IntentUtils.java b/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/IntentUtils.java deleted file mode 100644 index ae78345..0000000 --- a/easydeveloper/src/main/java/com/ayvytr/easydeveloper/tools/withcontext/IntentUtils.java +++ /dev/null @@ -1,293 +0,0 @@ -package com.ayvytr.easydeveloper.tools.withcontext; - -/** - *
- *     author: Blankj
- *     blog  : http://blankj.com
- *     time  : 2016/9/23
- *     desc  : 意图相关工具类
- * 
- */ -public class IntentUtils { - -// private IntentUtils() { -// throw new UnsupportedOperationException("u can't fuck me..."); -// } -// -// /** -// * 获取安装App(支持6.0)的意图 -// * -// * @param filePath 文件路径 -// * @return intent -// */ -// public static Intent getInstallAppIntent(String filePath) { -// return getInstallAppIntent(FileUtils.getFileByPath(filePath)); -// } -// -// /** -// * 获取安装App(支持6.0)的意图 -// * -// * @param file 文件 -// * @return intent -// */ -// public static Intent getInstallAppIntent(File file) { -// if (file == null) return null; -// Intent intent = new Intent(Intent.ACTION_VIEW); -// String type; -// -// if (Build.VERSION.SDK_INT < 23) { -// type = "application/vnd.android.package-archive"; -// } else { -// type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FileUtils.getFileExtension(file)); -// } -// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { -// intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); -// Uri contentUri = FileProvider.getUriForFile(Easy.getContext(), "com.your.package.fileProvider", file); -// intent.setDataAndType(contentUri, type); -// } -// intent.setDataAndType(Uri.fromFile(file), type); -// return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// } -// -// /** -// * 获取卸载App的意图 -// * -// * @param packageName 包名 -// * @return intent -// */ -// public static Intent getUninstallAppIntent(String packageName) { -// Intent intent = new Intent(Intent.ACTION_DELETE); -// intent.setData(Uri.parse("package:" + packageName)); -// return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// } -// -// /** -// * 获取打开App的意图 -// * -// * @param packageName 包名 -// * @return intent -// */ -// public static Intent getLaunchAppIntent(String packageName) { -// return Easy.getContext().getPackageManager().getLaunchIntentForPackage(packageName); -// } -// -// /** -// * 获取App具体设置的意图 -// * -// * @param packageName 包名 -// * @return intent -// */ -// public static Intent getAppDetailsSettingsIntent(String packageName) { -// Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS"); -// intent.setData(Uri.parse("package:" + packageName)); -// return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// } -// -// /** -// * 获取分享文本的意图 -// * -// * @param content 分享文本 -// * @return intent -// */ -// public static Intent getShareTextIntent(String content) { -// Intent intent = new Intent(Intent.ACTION_SEND); -// intent.setType("text/plain"); -// intent.putExtra(Intent.EXTRA_TEXT, content); -// return intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// } -// -// /** -// * 获取分享图片的意图 -// * -// * @param content 文本 -// * @param imagePath 图片文件路径 -// * @return intent -// */ -// public static Intent getShareImageIntent(String content, String imagePath) { -// return getShareImageIntent(content, FileUtils.getFileByPath(imagePath)); -// } -// -// /** -// * 获取分享图片的意图 -// * -// * @param content 文本 -// * @param image 图片文件 -// * @return intent -// */ -// public static Intent getShareImageIntent(String content, File image) { -// if (!FileUtils.isFileExists(image)) return null; -// return getShareImageIntent(content, Uri.fromFile(image)); -// } -// -// /** -// * 获取分享图片的意图 -// * -// * @param content 分享文本 -// * @param uri 图片uri -// * @return intent -// */ -// public static Intent getShareImageIntent(String content, Uri uri) { -// Intent intent = new Intent(Intent.ACTION_SEND); -// intent.putExtra(Intent.EXTRA_TEXT, content); -// intent.putExtra(Intent.EXTRA_STREAM, uri); -// intent.setType("image/*"); -// return intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// } -// -// /** -// * 获取其他应用组件的意图 -// * -// * @param packageName 包名 -// * @param className 全类名 -// * @return intent -// */ -// public static Intent getComponentIntent(String packageName, String className) { -// return getComponentIntent(packageName, className, null); -// } -// -// /** -// * 获取其他应用组件的意图 -// * -// * @param packageName 包名 -// * @param className 全类名 -// * @param bundle bundle -// * @return intent -// */ -// public static Intent getComponentIntent(String packageName, String className, Bundle bundle) { -// Intent intent = new Intent(Intent.ACTION_VIEW); -// if (bundle != null) intent.putExtras(bundle); -// ComponentName cn = new ComponentName(packageName, className); -// intent.setComponent(cn); -// return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// } -// -// /** -// * 获取关机的意图 -// *

需添加权限 {@code }

-// * -// * @return intent -// */ -// public static Intent getShutdownIntent() { -// Intent intent = new Intent(Intent.ACTION_SHUTDOWN); -// return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// } -// -// /** -// * 获取跳至拨号界面意图 -// * -// * @param phoneNumber 电话号码 -// */ -// public static Intent getDialIntent(String phoneNumber) { -// Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)); -// return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// } -// -// /** -// * 获取拨打电话意图 -// *

需添加权限 {@code }

-// * -// * @param phoneNumber 电话号码 -// */ -// public static Intent getCallIntent(String phoneNumber) { -// Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phoneNumber)); -// return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// } -// -// /** -// * 获取跳至发送短信界面的意图 -// * -// * @param phoneNumber 接收号码 -// * @param content 短信内容 -// */ -// public static Intent getSendSmsIntent(String phoneNumber, String content) { -// Uri uri = Uri.parse("smsto:" + phoneNumber); -// Intent intent = new Intent(Intent.ACTION_SENDTO, uri); -// intent.putExtra("sms_body", content); -// return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// } -// -// -// /** -// * 获取拍照的意图 -// * -// * @param outUri 输出的uri -// * @return 拍照的意图 -// */ -// public static Intent getCaptureIntent(Uri outUri) { -// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); -// intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri); -// return intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK); -// } -///* -// *//** -// * 获取选择照片的Intent -// * -// * @return -// *//* -// public static Intent getPickIntentWithGallery() { -// Intent intent = new Intent(Intent.ACTION_PICK); -// return intent.setType("image*//*"); -// } -// -// *//** -// * 获取从文件中选择照片的Intent -// * -// * @return -// *//* -// public static Intent getPickIntentWithDocuments() { -// Intent intent = new Intent(Intent.ACTION_GET_CONTENT); -// return intent.setType("image*//*"); -// } -// -// -// public static Intent buildImageGetIntent(Uri saveTo, int outputX, int outputY, boolean returnData) { -// return buildImageGetIntent(saveTo, 1, 1, outputX, outputY, returnData); -// } -// -// public static Intent buildImageGetIntent(Uri saveTo, int aspectX, int aspectY, -// int outputX, int outputY, boolean returnData) { -// Intent intent = new Intent(); -// if (Build.VERSION.SDK_INT < 19) { -// intent.setAction(Intent.ACTION_GET_CONTENT); -// } else { -// intent.setAction(Intent.ACTION_OPEN_DOCUMENT); -// intent.addCategory(Intent.CATEGORY_OPENABLE); -// } -// intent.setType("image*//*"); -// intent.putExtra("output", saveTo); -// intent.putExtra("aspectX", aspectX); -// intent.putExtra("aspectY", aspectY); -// intent.putExtra("outputX", outputX); -// intent.putExtra("outputY", outputY); -// intent.putExtra("scale", true); -// intent.putExtra("return-data", returnData); -// intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); -// return intent; -// } -// -// public static Intent buildImageCropIntent(Uri uriFrom, Uri uriTo, int outputX, int outputY, boolean returnData) { -// return buildImageCropIntent(uriFrom, uriTo, 1, 1, outputX, outputY, returnData); -// } -// -// public static Intent buildImageCropIntent(Uri uriFrom, Uri uriTo, int aspectX, int aspectY, -// int outputX, int outputY, boolean returnData) { -// Intent intent = new Intent("com.android.camera.action.CROP"); -// intent.setDataAndType(uriFrom, "image*//*"); -// intent.putExtra("crop", "true"); -// intent.putExtra("output", uriTo); -// intent.putExtra("aspectX", aspectX); -// intent.putExtra("aspectY", aspectY); -// intent.putExtra("outputX", outputX); -// intent.putExtra("outputY", outputY); -// intent.putExtra("scale", true); -// intent.putExtra("return-data", returnData); -// intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); -// return intent; -// } -// -// public static Intent buildImageCaptureIntent(Uri uri) { -// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); -// intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); -// return intent; -// }*/ -} diff --git a/easydeveloper/src/main/res/values/strings.xml b/easydeveloper/src/main/res/values/strings.xml deleted file mode 100644 index ea3cd60..0000000 --- a/easydeveloper/src/main/res/values/strings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - EasyDeveloper - diff --git a/settings.gradle b/settings.gradle index 079a9e0..ad78d57 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1 @@ -include ':app', ':easydeveloper' +include ':app', ':easyAndroidLibrary' \ No newline at end of file