├── .gitignore ├── .idea ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── dictionaries │ └── gyf.xml ├── encodings.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── gyf │ │ └── toolutils │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── gyf │ │ │ └── toolutils │ │ │ └── MainActivity.java │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── gyf │ └── toolutils │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle ├── toolutils4a ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── gyf │ │ └── toolutils4a │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── gyf │ │ │ └── toolutils4a │ │ │ ├── AppUtils.java │ │ │ ├── CoordinateTransformUtil.java │ │ │ ├── DateUtil.java │ │ │ ├── DensityUtil.java │ │ │ ├── DeviceUtils.java │ │ │ ├── FileUtils.java │ │ │ ├── ImageUtils.java │ │ │ ├── JsonUtils.java │ │ │ ├── L.java │ │ │ ├── MathUtil.java │ │ │ ├── NetUtils.java │ │ │ ├── SPUtils.java │ │ │ ├── StringUtil.java │ │ │ ├── SystemUtils.java │ │ │ ├── VerificationUtils.java │ │ │ ├── ViewUtils.java │ │ │ ├── cipher │ │ │ ├── Md5.java │ │ │ ├── RSA.java │ │ │ ├── Sha1.java │ │ │ └── base64 │ │ │ │ ├── Base64.java │ │ │ │ ├── Base64Decoder.java │ │ │ │ ├── Base64Encoder.java │ │ │ │ ├── CharacterDecoder.java │ │ │ │ └── CharacterEncoder.java │ │ │ └── service │ │ │ └── DownloadService.java │ └── res │ │ └── values │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── gyf │ └── toolutils4a │ └── ExampleUnitTest.java └── toolutils4j ├── .gitignore ├── build.gradle └── src └── main └── java └── com └── gyf ├── cipher ├── Md5.java ├── RSA.java ├── Sha1.java └── base64 │ ├── Base64.java │ ├── Base64Decoder.java │ ├── Base64Encoder.java │ ├── CharacterDecoder.java │ └── CharacterEncoder.java └── tool ├── CoordinateTransformUtil.java ├── DateUtil.java └── StringUtil.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/dictionaries/gyf.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 20 | 21 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | 11 | 12 | 24 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | Android 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 67 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.0" 6 | defaultConfig { 7 | applicationId "com.gyf.toolutils" 8 | minSdkVersion 9 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(include: ['*.jar'], dir: 'libs') 24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 25 | exclude group: 'com.android.support', module: 'support-annotations' 26 | }) 27 | compile 'com.android.support:appcompat-v7:25.0.0' 28 | testCompile 'junit:junit:4.12' 29 | compile project(':toolutils4j') 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/gyf/toolutils/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.gyf.toolutils", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /app/src/main/java/com/gyf/toolutils/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils; 2 | 3 | import android.support.v7.app.AppCompatActivity; 4 | import android.os.Bundle; 5 | 6 | public class MainActivity extends AppCompatActivity { 7 | 8 | @Override 9 | protected void onCreate(Bundle savedInstanceState) { 10 | super.onCreate(savedInstanceState); 11 | setContentView(R.layout.activity_main); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gyf-dev/ToolUtils/fac3b344b18b62744cddcd739d484039347f0d84/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gyf-dev/ToolUtils/fac3b344b18b62744cddcd739d484039347f0d84/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gyf-dev/ToolUtils/fac3b344b18b62744cddcd739d484039347f0d84/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gyf-dev/ToolUtils/fac3b344b18b62744cddcd739d484039347f0d84/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gyf-dev/ToolUtils/fac3b344b18b62744cddcd739d484039347f0d84/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ToolUtils 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/gyf/toolutils/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * Example local unit test, which will execute on the development machine (host). 7 | * 8 | * @see Testing documentation 9 | */ 10 | public class ExampleUnitTest { 11 | @Test 12 | public void addition_isCorrect(){ 13 | } 14 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.2.2' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | } 19 | } 20 | 21 | task clean(type: Delete) { 22 | delete rootProject.buildDir 23 | } 24 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gyf-dev/ToolUtils/fac3b344b18b62744cddcd739d484039347f0d84/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':toolutils4j', ':toolutils4a' 2 | -------------------------------------------------------------------------------- /toolutils4a/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /toolutils4a/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.0" 6 | 7 | defaultConfig { 8 | minSdkVersion 9 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 14 | 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | compile fileTree(dir: 'libs', include: ['*.jar']) 26 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 27 | exclude group: 'com.android.support', module: 'support-annotations' 28 | }) 29 | compile 'com.android.support:appcompat-v7:25.0.0' 30 | testCompile 'junit:junit:4.12' 31 | } 32 | -------------------------------------------------------------------------------- /toolutils4a/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /toolutils4a/src/androidTest/java/com/gyf/toolutils4a/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.gyf.toolutils4a.test", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /toolutils4a/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/CoordinateTransformUtil.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | 4 | /** 5 | * CoordinateTransformUtil.java GPS坐标转换工具 6 | */ 7 | public class CoordinateTransformUtil { 8 | /** 9 | * The X pi. 10 | */ 11 | static double x_pi = 3.14159265358979324 * 3000.0 / 180.0; 12 | /** 13 | * The Pi. 14 | */ 15 | static double pi = 3.1415926535897932384626; 16 | /** 17 | * The A. 18 | */ 19 | static double a = 6378245.0; 20 | /** 21 | * The Ee. 22 | */ 23 | static double ee = 0.00669342162296594323; 24 | 25 | /** 26 | * 百度坐标系(BD-09)转WGS坐标(百度坐标纬度,百度坐标经度),WGS84坐标数组 27 | * 28 | * @param lng the lng 29 | * @param lat the lat 30 | * @return the double [ ] 31 | */ 32 | public static double[] bd09towgs84(double lng, double lat) { 33 | double[] gcj = bd09togcj02(lng, lat); 34 | double[] wgs84 = gcj02towgs84(gcj[0], gcj[1]); 35 | return wgs84; 36 | } 37 | 38 | /** 39 | * WGS坐标转百度坐标系(BD-09)(WGS84坐标系的经度,WGS84坐标系的纬度),百度坐标数组 40 | * 41 | * @param lng the lng 42 | * @param lat the lat 43 | * @return the double [ ] 44 | */ 45 | public static double[] wgs84tobd09(double lng, double lat) { 46 | double[] gcj = wgs84togcj02(lng, lat); 47 | double[] bd09 = gcj02tobd09(gcj[0], gcj[1]); 48 | return bd09; 49 | } 50 | 51 | /** 52 | * 火星坐标系(GCJ-02)转百度坐标系(BD-09)(火星坐标经度,火星坐标纬度),百度坐标数组 53 | * 54 | * @param lng the lng 55 | * @param lat the lat 56 | * @return the double [ ] 57 | */ 58 | public static double[] gcj02tobd09(double lng, double lat) { 59 | double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi); 60 | double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi); 61 | double bd_lng = z * Math.cos(theta) + 0.0065; 62 | double bd_lat = z * Math.sin(theta) + 0.006; 63 | return new double[]{bd_lng, bd_lat}; 64 | } 65 | 66 | /** 67 | * 百度坐标系(BD-09)转火星坐标系(GCJ-02)(百度坐标纬度,百度坐标经度),火星坐标数组 68 | * 69 | * @param bd_lon the bd lon 70 | * @param bd_lat the bd lat 71 | * @return the double [ ] 72 | */ 73 | public static double[] bd09togcj02(double bd_lon, double bd_lat) { 74 | double x = bd_lon - 0.0065; 75 | double y = bd_lat - 0.006; 76 | double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi); 77 | double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi); 78 | double gg_lng = z * Math.cos(theta); 79 | double gg_lat = z * Math.sin(theta); 80 | return new double[]{gg_lng, gg_lat}; 81 | } 82 | 83 | /** 84 | * WGS84转GCJ02(火星坐标系)(WGS84坐标系的经度,WGS84坐标系的纬度),火星坐标数组 85 | * 86 | * @param lng the lng 87 | * @param lat the lat 88 | * @return the double [ ] 89 | */ 90 | public static double[] wgs84togcj02(double lng, double lat) { 91 | if (out_of_china(lng, lat)) { 92 | return new double[]{lng, lat}; 93 | } 94 | double dlat = transformlat(lng - 105.0, lat - 35.0); 95 | double dlng = transformlng(lng - 105.0, lat - 35.0); 96 | double radlat = lat / 180.0 * pi; 97 | double magic = Math.sin(radlat); 98 | magic = 1 - ee * magic * magic; 99 | double sqrtmagic = Math.sqrt(magic); 100 | dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi); 101 | dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi); 102 | double mglat = lat + dlat; 103 | double mglng = lng + dlng; 104 | return new double[]{mglng, mglat}; 105 | } 106 | 107 | /** 108 | * GCJ02(火星坐标系)转GPS84(火星坐标系的经度,火星坐标系纬度),WGS84坐标数组 109 | * 110 | * @param lng the lng 111 | * @param lat the lat 112 | * @return the double [ ] 113 | */ 114 | public static double[] gcj02towgs84(double lng, double lat) { 115 | if (out_of_china(lng, lat)) { 116 | return new double[]{lng, lat}; 117 | } 118 | double dlat = transformlat(lng - 105.0, lat - 35.0); 119 | double dlng = transformlng(lng - 105.0, lat - 35.0); 120 | double radlat = lat / 180.0 * pi; 121 | double magic = Math.sin(radlat); 122 | magic = 1 - ee * magic * magic; 123 | double sqrtmagic = Math.sqrt(magic); 124 | dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi); 125 | dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi); 126 | double mglat = lat + dlat; 127 | double mglng = lng + dlng; 128 | return new double[]{lng * 2 - mglng, lat * 2 - mglat}; 129 | } 130 | 131 | /** 132 | * 纬度转换 133 | * 134 | * @param lng the lng 135 | * @param lat the lat 136 | * @return the double 137 | */ 138 | public static double transformlat(double lng, double lat) { 139 | double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)); 140 | ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0; 141 | ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0; 142 | ret += (160.0 * Math.sin(lat / 12.0 * pi) + 320 * Math.sin(lat * pi / 30.0)) * 2.0 / 3.0; 143 | return ret; 144 | } 145 | 146 | /** 147 | * 经度转换 148 | * 149 | * @param lng the lng 150 | * @param lat the lat 151 | * @return the double 152 | */ 153 | public static double transformlng(double lng, double lat) { 154 | double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)); 155 | ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0; 156 | ret += (20.0 * Math.sin(lng * pi) + 40.0 * Math.sin(lng / 3.0 * pi)) * 2.0 / 3.0; 157 | ret += (150.0 * Math.sin(lng / 12.0 * pi) + 300.0 * Math.sin(lng / 30.0 * pi)) * 2.0 / 3.0; 158 | return ret; 159 | } 160 | 161 | /** 162 | * 判断是否在国内,不在国内不做偏移 163 | * 164 | * @param lng the lng 165 | * @param lat the lat 166 | * @return the boolean 167 | */ 168 | public static boolean out_of_china(double lng, double lat) { 169 | if (lng < 72.004 || lng > 137.8347) { 170 | return true; 171 | } else if (lat < 0.8293 || lat > 55.8271) { 172 | return true; 173 | } 174 | return false; 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/DateUtil.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.ArrayList; 6 | import java.util.Calendar; 7 | import java.util.Date; 8 | import java.util.GregorianCalendar; 9 | import java.util.List; 10 | 11 | /** 12 | * 日期工具类 13 | */ 14 | public class DateUtil { 15 | /** 16 | * The constant DATE_FORMAT_DATETIME. 17 | */ 18 | private static final SimpleDateFormat DATE_FORMAT_DATETIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 19 | /** 20 | * The constant DATE_FORMAT_DATE. 21 | */ 22 | private static final SimpleDateFormat DATE_FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd"); 23 | /** 24 | * The constant DATE_FORMAT_TIME. 25 | */ 26 | private static final SimpleDateFormat DATE_FORMAT_TIME = new SimpleDateFormat("HH:mm:ss"); 27 | 28 | /** 29 | * Format data time string. 30 | * 格式化日期时间 31 | * 32 | * @param date the date 33 | * @return the string 34 | */ 35 | public static String formatDataTime(long date) { 36 | return DATE_FORMAT_DATETIME.format(new Date(date)); 37 | } 38 | 39 | /** 40 | * Format date string. 41 | * 格式化日期 42 | * 43 | * @param date the date 44 | * @return the string 45 | */ 46 | public static String formatDate(long date) { 47 | return DATE_FORMAT_DATE.format(new Date(date)); 48 | } 49 | 50 | /** 51 | * Format time string. 52 | * 格式化时间 53 | * 54 | * @param date the date 55 | * @return the string 56 | */ 57 | public static String formatTime(long date) { 58 | return DATE_FORMAT_TIME.format(new Date(date)); 59 | } 60 | 61 | /** 62 | * Format date custom string. 63 | * 自定义格式的格式化日期时间 64 | * 65 | * @param beginDate the begin date 66 | * @param format the format 67 | * @return the string 68 | */ 69 | public static String formatDateCustom(String beginDate, String format) { 70 | return new SimpleDateFormat(format).format(new Date(Long.parseLong(beginDate))); 71 | } 72 | 73 | /** 74 | * Format date custom string. 75 | * 自定义格式的格式化日期时间 76 | * 77 | * @param beginDate the begin date 78 | * @param format the format 79 | * @return the string 80 | */ 81 | public static String formatDateCustom(Date beginDate, String format) { 82 | return new SimpleDateFormat(format).format(beginDate); 83 | } 84 | 85 | /** 86 | * Gets time. 87 | * 获取系统日期 88 | * 89 | * @return the time 90 | */ 91 | public static String getTime() { 92 | Calendar cal = Calendar.getInstance(); 93 | cal.setTimeInMillis(System.currentTimeMillis()); 94 | return cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND); 95 | } 96 | 97 | /** 98 | * Gets date. 99 | * 获取系统时间 100 | * 101 | * @return the date 102 | */ 103 | public static String getDate() { 104 | return new SimpleDateFormat("yyyyMMdd").format(System.currentTimeMillis()); 105 | } 106 | 107 | /** 108 | * Get date time string. 109 | * 获取系统日期时间 110 | * 111 | * @return the string 112 | */ 113 | public static String getDateTime() { 114 | return DATE_FORMAT_DATETIME.format(System.currentTimeMillis()); 115 | } 116 | 117 | /** 118 | * Get date time string. 119 | * 获取系统日期时间 120 | * 121 | * @param format the format 122 | * @return the string 123 | */ 124 | public static String getDateTime(String format) { 125 | return new SimpleDateFormat(format).format(System.currentTimeMillis()); 126 | } 127 | 128 | 129 | /** 130 | * Subtract date long. 131 | * 计算两个时间差 132 | * 133 | * @param dateStart the date start 134 | * @param dateEnd the date end 135 | * @return the long 136 | */ 137 | public static long subtractDate(Date dateStart, Date dateEnd) { 138 | return dateEnd.getTime() - dateStart.getTime(); 139 | } 140 | 141 | /** 142 | * Gets date after. 143 | * 得到几天后的时间 144 | * 145 | * @param d the d 146 | * @param day the day 147 | * @return the date after 148 | */ 149 | public static Date getDateAfter(Date d, int day) { 150 | Calendar now = Calendar.getInstance(); 151 | now.setTime(d); 152 | now.set(Calendar.DATE, now.get(Calendar.DATE) + day); 153 | return now.getTime(); 154 | } 155 | 156 | /** 157 | * Gets date time after. 158 | * 得到当前时间指定毫秒后的时间 159 | * 160 | * @param mill the mill 161 | * @return the String 162 | */ 163 | public static String getDateTimeAfter(long mill) { 164 | return DATE_FORMAT_DATETIME.format(System.currentTimeMillis() + mill); 165 | } 166 | 167 | /** 168 | * Get week of year int. 169 | * 获取当前时间为本年的第几周 170 | * 171 | * @return the int 172 | */ 173 | public static int getWeekOfYear() { 174 | Calendar calendar = Calendar.getInstance(); 175 | calendar.setTime(new Date()); 176 | return calendar.get(Calendar.WEEK_OF_YEAR); 177 | } 178 | 179 | /** 180 | * Gets week of month. 181 | * 获取当前时间为本月的第几周 182 | * 183 | * @return the week of month 184 | */ 185 | public static int getWeekOfMonth() { 186 | Calendar calendar = Calendar.getInstance(); 187 | int week = calendar.get(Calendar.WEEK_OF_MONTH); 188 | return week - 1; 189 | } 190 | 191 | /** 192 | * Gets day of week. 193 | * 获取当前时间为本周的第几天 194 | * 195 | * @return the day of week 196 | */ 197 | public static int getDayOfWeek() { 198 | Calendar calendar = Calendar.getInstance(); 199 | int day = calendar.get(Calendar.DAY_OF_WEEK); 200 | if (day == 1) { 201 | day = 7; 202 | } else { 203 | day = day - 1; 204 | } 205 | return day; 206 | } 207 | 208 | /** 209 | * Gets start time of week. 210 | * 获取一周开始时间 211 | * 212 | * @return the start time of week 213 | * @throws ParseException the parse exception 214 | */ 215 | public static Date getStartTimeOfWeek() throws ParseException { 216 | Calendar c = Calendar.getInstance(); 217 | int day = c.get(Calendar.DAY_OF_WEEK); 218 | long time = System.currentTimeMillis(); 219 | if (day > 1) { 220 | time = time - (day - 2) * 24 * 60 * 60 * 1000L; 221 | } else { 222 | time = time - 6 * 24 * 60 * 60 * 1000L; 223 | } 224 | Date date = new Date(time); 225 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 226 | date = sdf.parse(sdf.format(date)); 227 | return date; 228 | } 229 | 230 | /** 231 | * Gets end time of week. 232 | * 获取一周结束时间 233 | * 234 | * @return the end time of week 235 | */ 236 | public static Date getEndTimeOfWeek() { 237 | Calendar c = Calendar.getInstance(); 238 | int day = c.get(Calendar.DAY_OF_WEEK); 239 | long time = System.currentTimeMillis(); 240 | if (day > 1) { 241 | time = time + (8 - day) * 24 * 60 * 60 * 1000L; 242 | } 243 | Date date = new Date(time); 244 | SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); 245 | SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 246 | try { 247 | date = sdf2.parse(sdf1.format(date) + " 23:59:59"); 248 | } catch (ParseException e) { 249 | e.printStackTrace(); 250 | } 251 | return date; 252 | } 253 | 254 | 255 | /** 256 | * Gets week of date. 257 | * 根据日期获取星期 258 | * 259 | * @param date the date 260 | * @return the week of date 261 | */ 262 | public static int getWeekOfDate(Date date) { 263 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 264 | Date currentDate = null; 265 | Date targetDate = null; 266 | try { 267 | currentDate = sdf.parse(sdf.format(new Date())); 268 | targetDate = sdf.parse(sdf.format(date)); 269 | } catch (ParseException e) { 270 | e.printStackTrace(); 271 | } 272 | if (currentDate.getTime() == targetDate.getTime()) { 273 | return getDayOfWeek(); 274 | } else if (currentDate.getTime() < targetDate.getTime()) { 275 | return (int) ((targetDate.getTime() - currentDate.getTime()) / (24 * 60 * 60 * 1000) 276 | + getDayOfWeek()) % 7; 277 | } else if (currentDate.getTime() > targetDate.getTime()) { 278 | return (int) (getDayOfWeek() + 7 279 | - (currentDate.getTime() - targetDate.getTime()) / (24 * 60 * 60 * 1000) % 7) % 7; 280 | } 281 | return 0; 282 | } 283 | 284 | /** 285 | * Gets date list of week. 286 | * 根据日期获取一周的日期(从周一到周日) 287 | * 288 | * @param date the date 289 | * @return the date list of week 290 | * @throws ParseException the parse exception 291 | */ 292 | public static List getDateListOfWeek(Date date) { 293 | List list = new ArrayList(); 294 | int weekOfDate = getWeekOfDate(date); 295 | Date firstDay = new Date(date.getTime() - (weekOfDate - 1) * 24 * 60 * 60 * 1000L); 296 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 297 | try { 298 | firstDay = sdf.parse(sdf.format(firstDay)); 299 | } catch (ParseException e) { 300 | e.printStackTrace(); 301 | } 302 | list.add(firstDay); 303 | for (int i = 1; i < 7; i++) { 304 | if (i == 1) { 305 | list.add(new Date(firstDay.getTime() + i * 24 * 60 * 60 * 1000L)); 306 | } else { 307 | list.add(new Date(firstDay.getTime() + (i + 1) * 24 * 60 * 60 * 1000L)); 308 | } 309 | } 310 | return list; 311 | } 312 | 313 | /** 314 | * Gets age. 315 | * 根据日期返回年龄 316 | * 317 | * @param birthDate the birth date 318 | * @return the age 319 | */ 320 | public static int getAge(Date birthDate) { 321 | 322 | if (birthDate == null) 323 | throw new RuntimeException("出生日期不能为null"); 324 | 325 | int age = 0; 326 | 327 | Date now = new Date(); 328 | 329 | SimpleDateFormat format_y = new SimpleDateFormat("yyyy"); 330 | SimpleDateFormat format_M = new SimpleDateFormat("MM"); 331 | 332 | String birth_year = format_y.format(birthDate); 333 | String this_year = format_y.format(now); 334 | 335 | String birth_month = format_M.format(birthDate); 336 | String this_month = format_M.format(now); 337 | // 初步,估算 338 | age = Integer.parseInt(this_year) - Integer.parseInt(birth_year); 339 | // 如果未到出生月份,则age - 1 340 | if (this_month.compareTo(birth_month) < 0) { 341 | age -= 1; 342 | } 343 | if (age < 0) { 344 | age = 0; 345 | } 346 | return age; 347 | } 348 | 349 | /** 350 | * Gets next date. 351 | * 获得第二条日期 352 | * 353 | * @return the next date 354 | * @throws Exception the exception 355 | */ 356 | public static Date getNextDate() throws Exception { 357 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 358 | Date date = new Date(); 359 | date.setDate(date.getDate() + 1); 360 | 361 | String str = format.format(date); 362 | return format.parse(str); 363 | } 364 | 365 | /** 366 | * Date to str string. 367 | * 日期转字符串 368 | * 369 | * @param date the date 370 | * @return the string 371 | */ 372 | public static String date2Str(Date date) { 373 | 374 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 375 | String str = format.format(date); 376 | return str; 377 | } 378 | 379 | /** 380 | * Str to date date. 381 | * 字符串转日期 382 | * 383 | * @param str the str 384 | * @return the date 385 | */ 386 | public static Date str2Date(String str) { 387 | return str2Date(str, "yyyy-MM-dd HH:mm:ss"); 388 | } 389 | 390 | /** 391 | * String 2 date date. 392 | * 字符串转换成Date 393 | * 394 | * @param s the s 395 | * @param style the style 396 | * @return the date 397 | */ 398 | public static Date str2Date(String s, String style) { 399 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); 400 | simpleDateFormat.applyPattern(style); 401 | Date date = null; 402 | if (s == null || s.length() < 6) { 403 | return null; 404 | } 405 | try { 406 | date = simpleDateFormat.parse(s); 407 | } catch (ParseException e) { 408 | e.printStackTrace(); 409 | } 410 | return date; 411 | } 412 | 413 | /** 414 | * Is ampm string. 415 | * 判断是上午还是下午 416 | * 417 | * @param date the date 418 | * @return the string 419 | */ 420 | public static String isAMPM(Date date) { 421 | GregorianCalendar ca = new GregorianCalendar(); 422 | ca.setTime(date); 423 | return GregorianCalendar.AM_PM == 0 ? "am" : "pm"; 424 | } 425 | 426 | 427 | /** 428 | * Time am pm night int. 429 | * 判断指定日期是上午,下午,晚上0-上午;1-下午;2-晚上;3-过期 430 | * 431 | * @param date the date 432 | * @return the int 433 | */ 434 | public static String isAmPmNight(Date date) { 435 | String start = "00:00:00"; 436 | String night = "23:59:59"; 437 | String am = "12:00:00"; 438 | String pm = "18:00:00"; 439 | 440 | SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss"); 441 | Date d_start = null; 442 | Date d_night = null; 443 | Date d_am = null; 444 | Date d_pm = null; 445 | try { 446 | d_start = s.parse(start); 447 | d_night = s.parse(night); 448 | d_am = s.parse(am); 449 | d_pm = s.parse(pm); 450 | } catch (ParseException e) { 451 | e.printStackTrace(); 452 | } 453 | 454 | Date paramsTime = str2Date(formatTime(date.getTime()), "HH:mm:ss"); 455 | 456 | if (paramsTime.after(d_start) && paramsTime.before(d_am)) { 457 | return "am"; 458 | } 459 | if (paramsTime.after(d_am) && paramsTime.before(d_pm)) { 460 | return "pm"; 461 | } 462 | if (paramsTime.after(d_pm) && paramsTime.before(d_night)) { 463 | return "night"; 464 | } 465 | return ""; 466 | } 467 | 468 | /** 469 | * Is leap year boolean. 470 | * 判断是否为闰年 471 | * @param date the date 472 | * @return the boolean 473 | */ 474 | public static boolean isLeapYear(Date date) { 475 | 476 | /** 477 | * 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年 478 | * 3.能被4整除同时能被100整除则不是闰年 479 | */ 480 | GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance(); 481 | gc.setTime(date); 482 | int year = gc.get(Calendar.YEAR); 483 | if ((year % 400) == 0) 484 | return true; 485 | else if ((year % 4) == 0) { 486 | if ((year % 100) == 0) 487 | return false; 488 | else 489 | return true; 490 | } else 491 | return false; 492 | } 493 | 494 | } 495 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/DensityUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 android@19code.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.gyf.toolutils4a; 18 | 19 | import android.annotation.TargetApi; 20 | import android.content.Context; 21 | import android.content.res.Resources; 22 | import android.os.Build; 23 | import android.util.DisplayMetrics; 24 | import android.util.TypedValue; 25 | import android.view.Display; 26 | import android.view.WindowManager; 27 | 28 | import java.lang.reflect.Field; 29 | import java.lang.reflect.Method; 30 | 31 | /** 32 | * 屏幕工具类 33 | */ 34 | public class DensityUtil { 35 | 36 | /** 37 | * dp转像素 38 | * 39 | * @param c the c 40 | * @param dpValue the dp value 41 | * @return the int 42 | */ 43 | public static int dip2px(Context c, float dpValue) { 44 | final float scale = c.getResources().getDisplayMetrics().density; 45 | return (int) (dpValue * scale + 0.5f); 46 | } 47 | 48 | /** 49 | * dip转sp 50 | * 51 | * @param c the c 52 | * @param dpValue the dp value 53 | * @return the int 54 | */ 55 | public static int dip2sp(Context c, float dpValue) { 56 | return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, c.getResources().getDisplayMetrics())); 57 | } 58 | 59 | /** 60 | * 像素转dp 61 | * 62 | * @param c the c 63 | * @param pxValue the px value 64 | * @return the int 65 | */ 66 | public static int px2dip(Context c, float pxValue) { 67 | final float scale = c.getResources().getDisplayMetrics().density; 68 | return (int) (pxValue / scale + 0.5f); 69 | } 70 | 71 | 72 | /** 73 | * 像素转sp 74 | * 75 | * @param c the c 76 | * @param pxValue the px value 77 | * @return the int 78 | */ 79 | public static int px2sp(Context c, float pxValue) { 80 | float fontScale = c.getResources().getDisplayMetrics().scaledDensity; 81 | return (int) (pxValue / fontScale + 0.5f); 82 | } 83 | 84 | 85 | /** 86 | * sp转像素 87 | * 88 | * @param c the c 89 | * @param spValue the sp value 90 | * @return the int 91 | */ 92 | public static int sp2px(Context c, float spValue) { 93 | float fontScale = c.getResources().getDisplayMetrics().scaledDensity; 94 | return (int) (spValue * fontScale + 0.5f); 95 | } 96 | 97 | /** 98 | * sp转dip 99 | * 100 | * @param c the c 101 | * @param spValue the sp value 102 | * @return the int 103 | */ 104 | public static int sp2dip(Context c, float spValue) { 105 | return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, c.getResources().getDisplayMetrics())); 106 | } 107 | 108 | /** 109 | * 获取屏幕宽度 110 | * 111 | * @param c the c 112 | * @return the screen w 113 | */ 114 | public static int getScreenW(Context c) { 115 | return c.getResources().getDisplayMetrics().widthPixels; 116 | } 117 | 118 | /** 119 | * 获取屏幕高度 120 | * 121 | * @param c the c 122 | * @return the screen h 123 | */ 124 | public static int getScreenH(Context c) { 125 | return c.getResources().getDisplayMetrics().heightPixels; 126 | } 127 | 128 | /** 129 | * 获取屏幕的真实高度 130 | * 131 | * @param context the context 132 | * @return the screen real h 133 | */ 134 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) 135 | public static int getScreenRealH(Context context) { 136 | int h; 137 | WindowManager winMgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 138 | Display display = winMgr.getDefaultDisplay(); 139 | DisplayMetrics dm = new DisplayMetrics(); 140 | if (Build.VERSION.SDK_INT >= 17) { 141 | display.getRealMetrics(dm); 142 | h = dm.heightPixels; 143 | } else { 144 | try { 145 | Method method = Class.forName("android.view.Display").getMethod("getRealMetrics", DisplayMetrics.class); 146 | method.invoke(display, dm); 147 | h = dm.heightPixels; 148 | } catch (Exception e) { 149 | display.getMetrics(dm); 150 | h = dm.heightPixels; 151 | } 152 | } 153 | return h; 154 | } 155 | 156 | /** 157 | * 获取状态栏高度 158 | * 159 | * @param context the context 160 | * @return the status bar h 161 | */ 162 | public static int getStatusBarH(Context context) { 163 | Class c; 164 | Object obj; 165 | Field field; 166 | int statusBarHeight = 0; 167 | try { 168 | c = Class.forName("com.android.internal.R$dimen"); 169 | obj = c.newInstance(); 170 | field = c.getField("status_bar_height"); 171 | int x = Integer.parseInt(field.get(obj).toString()); 172 | statusBarHeight = context.getResources().getDimensionPixelSize(x); 173 | } catch (Exception e1) { 174 | e1.printStackTrace(); 175 | } 176 | return statusBarHeight; 177 | } 178 | 179 | /** 180 | * 获取导航栏高度 181 | * 182 | * @param c the c 183 | * @return the navigation barr h 184 | */ 185 | public static int getNavigationBarrH(Context c) { 186 | Resources resources = c.getResources(); 187 | int identifier = resources.getIdentifier("navigation_bar_height", "dimen", "android"); 188 | return resources.getDimensionPixelOffset(identifier); 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/ImageUtils.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.graphics.Bitmap; 6 | import android.graphics.BitmapFactory; 7 | import android.graphics.Canvas; 8 | import android.graphics.Matrix; 9 | import android.graphics.Paint; 10 | import android.graphics.PorterDuff; 11 | import android.graphics.PorterDuffXfermode; 12 | import android.graphics.Rect; 13 | import android.graphics.RectF; 14 | import android.media.ExifInterface; 15 | import android.net.Uri; 16 | import android.provider.MediaStore; 17 | 18 | import java.io.ByteArrayInputStream; 19 | import java.io.ByteArrayOutputStream; 20 | import java.io.File; 21 | import java.io.FileNotFoundException; 22 | import java.io.FileOutputStream; 23 | import java.io.IOException; 24 | import java.io.OutputStream; 25 | 26 | /** 27 | * The type Image utils. 28 | */ 29 | public class ImageUtils { 30 | 31 | /** 32 | * 计算图片的压缩比率 33 | * 34 | * @param options the options 35 | * @param reqWidth the req width 36 | * @param reqHeight the req height 37 | * @return the int 38 | */ 39 | public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 40 | final int height = options.outHeight; 41 | final int width = options.outWidth; 42 | int inSampleSize = 1; 43 | if (height > reqHeight || width > reqWidth) { 44 | final int halfHeight = height / 2; 45 | final int halfWidth = width / 2; 46 | while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { 47 | inSampleSize *= 2; 48 | } 49 | } 50 | return inSampleSize; 51 | } 52 | 53 | /** 54 | * 获取图片的角度 55 | * 56 | * @param imagePath the image path 57 | * @return the picture degree 58 | */ 59 | public static int getPictureDegree(String imagePath) { 60 | int i = 0; 61 | try { 62 | ExifInterface localExifInterface = new ExifInterface(imagePath); 63 | int j = localExifInterface.getAttributeInt("Orientation", 1); 64 | switch (j) { 65 | case 6: 66 | i = 90; 67 | break; 68 | case 3: 69 | i = 180; 70 | break; 71 | case 8: 72 | i = 270; 73 | case 4: 74 | case 5: 75 | case 7: 76 | default: 77 | break; 78 | } 79 | } catch (IOException localIOException) { 80 | localIOException.printStackTrace(); 81 | } 82 | return i; 83 | } 84 | 85 | /** 86 | * 旋转图片 87 | * 88 | * @param paramInt the param int 89 | * @param paramBitmap the param bitmap 90 | * @return the bitmap 91 | */ 92 | public static Bitmap rotaingImageView(int paramInt, Bitmap paramBitmap) { 93 | Matrix localMatrix = new Matrix(); 94 | localMatrix.postRotate(paramInt); 95 | return Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(), paramBitmap.getHeight(), localMatrix, true); 96 | } 97 | 98 | /** 99 | * 加载图片并压缩 100 | * 101 | * @param imagePath the image path 102 | * @param outWidth the out width 103 | * @param outHeight the out height 104 | * @return the bitmap 105 | */ 106 | public static Bitmap decodeScaleImage(String imagePath, int outWidth, int outHeight) { 107 | BitmapFactory.Options localOptions = new BitmapFactory.Options(); 108 | localOptions.inJustDecodeBounds = true; 109 | BitmapFactory.decodeFile(imagePath, localOptions); 110 | int i = calculateInSampleSize(localOptions, outWidth, outHeight); 111 | localOptions.inSampleSize = i; 112 | localOptions.inJustDecodeBounds = false; 113 | Bitmap localBitmap1 = BitmapFactory.decodeFile(imagePath, localOptions); 114 | int j = getPictureDegree(imagePath); 115 | Bitmap localBitmap2 = null; 116 | if ((localBitmap1 != null) && (j != 0)) { 117 | localBitmap2 = rotaingImageView(j, localBitmap1); 118 | localBitmap1.recycle(); 119 | localBitmap1 = null; 120 | return localBitmap2; 121 | } 122 | return localBitmap1; 123 | } 124 | 125 | /** 126 | * 获取圆角图片 127 | * 128 | * @param bitmap the bitmap 129 | * @param roundPx the round px 130 | * @return the rounded corner bitmap 131 | */ 132 | public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) { 133 | if (bitmap == null) { 134 | return null; 135 | } 136 | Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); 137 | Canvas canvas = new Canvas(output); 138 | final int color = 0xff424242; 139 | final Paint paint = new Paint(); 140 | final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); 141 | final RectF rectF = new RectF(rect); 142 | paint.setAntiAlias(true); 143 | canvas.drawARGB(0, 0, 0, 0); 144 | paint.setColor(color); 145 | canvas.drawRoundRect(rectF, roundPx, roundPx, paint); 146 | paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); 147 | canvas.drawBitmap(bitmap, rect, rect, paint); 148 | return output; 149 | } 150 | 151 | /** 152 | * 将bitmap保存为文件 153 | * 154 | * @param bitmap the bitmap 155 | * @param imageFile the image file 156 | * @return the boolean 157 | */ 158 | public static boolean bitmap2File(Bitmap bitmap, File imageFile) { 159 | OutputStream os; 160 | try { 161 | os = new FileOutputStream(imageFile); 162 | boolean isOK = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); 163 | os.flush(); 164 | os.close(); 165 | return isOK; 166 | } catch (Exception e) { 167 | e.printStackTrace(); 168 | return false; 169 | } 170 | } 171 | 172 | 173 | /** 174 | * Bitmap 2 gallery boolean. 175 | * 176 | * @param context the context 177 | * @param bitmap the bitmap 178 | * @param filename the filename 179 | * @return the boolean 180 | */ 181 | public static boolean bitmap2gallery(Context context, Bitmap bitmap, String filename) { 182 | boolean saveSuccess; 183 | String extraPath = FileUtils.getExtraPath("19code"); 184 | File file = new File(extraPath, filename); 185 | try { 186 | FileOutputStream outputStream = new FileOutputStream(file); 187 | boolean compress = bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); 188 | outputStream.flush(); 189 | outputStream.close(); 190 | MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getPath(), filename, null); 191 | context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file))); 192 | saveSuccess = compress; 193 | } catch (FileNotFoundException e) { 194 | saveSuccess = false; 195 | e.printStackTrace(); 196 | } catch (IOException e) { 197 | saveSuccess = false; 198 | e.printStackTrace(); 199 | } 200 | return saveSuccess; 201 | } 202 | 203 | /** 204 | * 质量压缩 205 | * 206 | * @param image the image 207 | * @return the bitmap 208 | */ 209 | public static Bitmap compressImage(Bitmap image) { 210 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 211 | image.compress(Bitmap.CompressFormat.JPEG, 100, baos); 212 | int options = 100; 213 | while (baos.toByteArray().length / 1024 > 100) { 214 | options -= 10; 215 | if (options > 0) { 216 | baos.reset(); 217 | image.compress(Bitmap.CompressFormat.JPEG, options, baos); 218 | } 219 | } 220 | ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); 221 | return BitmapFactory.decodeStream(isBm, null, null); 222 | } 223 | 224 | /** 225 | * 固定大小压缩 226 | * 227 | * @param bitMap the bit map 228 | * @param outWidth the out width 229 | * @param outHeight the out height 230 | * @return the bitmap 231 | */ 232 | public static Bitmap compressFixBitmap(Bitmap bitMap, int outWidth, int outHeight) { 233 | int width = bitMap.getWidth(); 234 | int height = bitMap.getHeight(); 235 | float scaleWidth = ((float) outWidth) / width; 236 | float scaleHeight = ((float) outHeight) / height; 237 | Matrix matrix = new Matrix(); 238 | matrix.postScale(scaleWidth, scaleHeight); 239 | return Bitmap.createBitmap(bitMap, 0, 0, width, height, matrix, true); 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/JsonUtils.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import org.json.JSONArray; 4 | import org.json.JSONException; 5 | import org.json.JSONObject; 6 | import org.json.JSONTokener; 7 | 8 | import java.lang.reflect.Array; 9 | import java.util.Collection; 10 | import java.util.Map; 11 | 12 | /** 13 | * Msg: JSON处理类 1、Map转为JSONObject 2、集合转换为JSONArray 14 | * Created by gyf on 2016/11/15. 15 | */ 16 | 17 | public class JsonUtils { 18 | /** 19 | * Map转为JSON对象 20 | * 21 | * @param data Map数据 22 | * @return 23 | */ 24 | public static JSONObject mapToJson(Map data) { 25 | JSONObject object = new JSONObject(); 26 | 27 | for (Map.Entry entry : data.entrySet()) { 28 | String key = (String) entry.getKey(); 29 | if (key == null) { 30 | throw new NullPointerException("key == null"); 31 | } 32 | try { 33 | object.put(key, wrap(entry.getValue())); 34 | } catch (JSONException e) { 35 | e.printStackTrace(); 36 | } 37 | } 38 | 39 | return object; 40 | } 41 | 42 | /** 43 | * 集合转换为JSONArray 44 | * 45 | * @param data 集合对象 46 | * @return 47 | */ 48 | public static JSONArray collectionToJson(Collection data) { 49 | JSONArray jsonArray = new JSONArray(); 50 | if (data != null) { 51 | for (Object aData : data) { 52 | jsonArray.put(wrap(aData)); 53 | } 54 | } 55 | return jsonArray; 56 | } 57 | 58 | /** 59 | * Object对象转换为JSONArray 60 | * 61 | * @param data Object对象 62 | * @return 63 | * @throws JSONException Object非数组时,抛出异常 64 | */ 65 | public static JSONArray arrayToJson(Object data) throws JSONException { 66 | if (!data.getClass().isArray()) { 67 | throw new JSONException("Not a primitive data: " + data.getClass()); 68 | } 69 | final int length = Array.getLength(data); 70 | JSONArray jsonArray = new JSONArray(); 71 | for (int i = 0; i < length; ++i) { 72 | jsonArray.put(wrap(Array.get(data, i))); 73 | } 74 | 75 | return jsonArray; 76 | } 77 | 78 | private static Object wrap(Object o) { 79 | if (o == null) { 80 | return null; 81 | } 82 | if (o instanceof JSONArray || o instanceof JSONObject) { 83 | return o; 84 | } 85 | try { 86 | if (o instanceof Collection) { 87 | return collectionToJson((Collection) o); 88 | } else if (o.getClass().isArray()) { 89 | return arrayToJson(o); 90 | } 91 | if (o instanceof Map) { 92 | return mapToJson((Map) o); 93 | } 94 | 95 | if (o instanceof Boolean || o instanceof Byte || o instanceof Character || o instanceof Double || o instanceof Float || o instanceof Integer || o instanceof Long 96 | || o instanceof Short || o instanceof String) { 97 | return o; 98 | } 99 | if (o.getClass().getPackage().getName().startsWith("java.")) { 100 | return o.toString(); 101 | } 102 | } catch (Exception ignored) { 103 | } 104 | return null; 105 | } 106 | 107 | /** 108 | * 根据json字符串生成JSONObject对象 109 | * 110 | * @param json json字符串 111 | * @return 返回JSONObject对象或者空(null) 112 | */ 113 | public static JSONObject initJSONObject(String json) { 114 | 115 | JSONObject jsonObject = null; 116 | try { 117 | JSONTokener jsonParser = new JSONTokener(json); 118 | jsonObject = (JSONObject) jsonParser.nextValue(); 119 | } catch (Exception e) { 120 | } finally { 121 | return jsonObject; 122 | } 123 | 124 | } 125 | 126 | /** 127 | * 根据Key值相对应的Value值 128 | * 129 | * @param jsonObject Json对象 130 | * @param key 健值 131 | * @return 返回value值或空串("") 132 | */ 133 | public static String getString(JSONObject jsonObject, String key) { 134 | String value = ""; 135 | try { 136 | value = jsonObject.getString(key); 137 | } catch (Exception e) { 138 | } 139 | 140 | return value; 141 | } 142 | 143 | /** 144 | * 根据Key值相对应的Value值 145 | * 146 | * @param jsonObject Json对象 147 | * @param key 健值 148 | * @return 返回value值或-1 149 | */ 150 | public static int getInt(JSONObject jsonObject, String key) { 151 | int value = -1; 152 | try { 153 | value = jsonObject.getInt(key); 154 | } catch (Exception e) { 155 | } 156 | 157 | return value; 158 | } 159 | 160 | /** 161 | * 根据Key值相对应的Value值 162 | * 163 | * @param jsonObject Json对象 164 | * @param key 健值 165 | * @return 返回value值或-1 166 | */ 167 | public static long getLong(JSONObject jsonObject, String key) { 168 | long value = -1; 169 | try { 170 | value = jsonObject.getLong(key); 171 | } catch (Exception e) { 172 | } 173 | 174 | return value; 175 | } 176 | 177 | /** 178 | * 根据Key值相对应的Value值 179 | * 180 | * @param jsonObject Json对象 181 | * @param key 健值 182 | * @return 返回value值或null 183 | */ 184 | public static JSONArray getJSONArray(JSONObject jsonObject, String key) { 185 | JSONArray arrays = null; 186 | try { 187 | arrays = jsonObject.getJSONArray(key); 188 | } catch (Exception e) { 189 | } 190 | 191 | return arrays; 192 | } 193 | 194 | /** 195 | * 根据Key值相对应的Value值 196 | * 197 | * @param jsonArray JsonArray对象 198 | * @param index 索引 199 | * @return 返回value值或null 200 | */ 201 | public static JSONObject getJSONObject(JSONArray jsonArray, int index) { 202 | JSONObject jsonObject = null; 203 | try { 204 | jsonObject = jsonArray.getJSONObject(index); 205 | } catch (Exception e) { 206 | } 207 | return jsonObject; 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/L.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import android.text.TextUtils; 4 | import android.util.Log; 5 | 6 | import org.json.JSONArray; 7 | import org.json.JSONException; 8 | import org.json.JSONObject; 9 | 10 | import java.io.StringReader; 11 | import java.io.StringWriter; 12 | 13 | import javax.xml.transform.OutputKeys; 14 | import javax.xml.transform.Source; 15 | import javax.xml.transform.Transformer; 16 | import javax.xml.transform.TransformerFactory; 17 | import javax.xml.transform.stream.StreamResult; 18 | import javax.xml.transform.stream.StreamSource; 19 | 20 | /** 21 | * The type L. 22 | */ 23 | public class L { 24 | /** 25 | * The constant TAG. 26 | */ 27 | private static String TAG = "ghost"; 28 | /** 29 | * The constant LOG_DEBUG. 30 | */ 31 | private static boolean LOG_DEBUG = true; 32 | /** 33 | * The constant LINE_SEPARATOR. 34 | */ 35 | private static final String LINE_SEPARATOR = System.getProperty("line.separator"); 36 | /** 37 | * The constant VERBOSE. 38 | */ 39 | private static final int VERBOSE = 2; 40 | /** 41 | * The constant DEBUG. 42 | */ 43 | private static final int DEBUG = 3; 44 | /** 45 | * The constant INFO. 46 | */ 47 | private static final int INFO = 4; 48 | /** 49 | * The constant WARN. 50 | */ 51 | private static final int WARN = 5; 52 | /** 53 | * The constant ERROR. 54 | */ 55 | private static final int ERROR = 6; 56 | /** 57 | * The constant ASSERT. 58 | */ 59 | private static final int ASSERT = 7; 60 | /** 61 | * The constant JSON. 62 | */ 63 | private static final int JSON = 8; 64 | /** 65 | * The constant XML. 66 | */ 67 | private static final int XML = 9; 68 | 69 | /** 70 | * The constant JSON_INDENT. 71 | */ 72 | private static final int JSON_INDENT = 4; 73 | 74 | /** 75 | * init 初始化日志开关和TAG(默认日志为开,TAG为"ghost") 76 | * 77 | * @param isDebug the is debug 78 | * @param tag the tag 79 | */ 80 | public static void init(boolean isDebug, String tag) { 81 | TAG = tag; 82 | LOG_DEBUG = isDebug; 83 | } 84 | 85 | /** 86 | * V. 87 | * 88 | * @param msg the msg 89 | */ 90 | public static void v(String msg) { 91 | log(VERBOSE, null, msg); 92 | } 93 | 94 | /** 95 | * V. 96 | * 97 | * @param tag the tag 98 | * @param msg the msg 99 | */ 100 | public static void v(String tag, String msg) { 101 | log(VERBOSE, tag, msg); 102 | } 103 | 104 | /** 105 | * D. 106 | * 107 | * @param msg the msg 108 | */ 109 | public static void d(String msg) { 110 | log(DEBUG, null, msg); 111 | } 112 | 113 | /** 114 | * D. 115 | * 116 | * @param tag the tag 117 | * @param msg the msg 118 | */ 119 | public static void d(String tag, String msg) { 120 | log(DEBUG, tag, msg); 121 | } 122 | 123 | /** 124 | * . 125 | * 126 | * @param msg the msg 127 | */ 128 | public static void i(Object... msg) { 129 | StringBuilder sb = new StringBuilder(); 130 | for (Object obj : msg) { 131 | sb.append(obj); 132 | sb.append(","); 133 | } 134 | log(INFO, null, String.valueOf(sb)); 135 | } 136 | 137 | /** 138 | * W. 139 | * 140 | * @param msg the msg 141 | */ 142 | public static void w(String msg) { 143 | log(WARN, null, msg); 144 | } 145 | 146 | /** 147 | * W. 148 | * 149 | * @param tag the tag 150 | * @param msg the msg 151 | */ 152 | public static void w(String tag, String msg) { 153 | log(WARN, tag, msg); 154 | } 155 | 156 | /** 157 | * E. 158 | * 159 | * @param msg the msg 160 | */ 161 | public static void e(String msg) { 162 | log(ERROR, null, msg); 163 | } 164 | 165 | /** 166 | * E. 167 | * 168 | * @param tag the tag 169 | * @param msg the msg 170 | */ 171 | public static void e(String tag, String msg) { 172 | log(ERROR, tag, msg); 173 | } 174 | 175 | /** 176 | * A. 177 | * 178 | * @param msg the msg 179 | */ 180 | public static void a(String msg) { 181 | log(ASSERT, null, msg); 182 | } 183 | 184 | /** 185 | * A. 186 | * 187 | * @param tag the tag 188 | * @param msg the msg 189 | */ 190 | public static void a(String tag, String msg) { 191 | log(ASSERT, tag, msg); 192 | } 193 | 194 | /** 195 | * Json. 196 | * 197 | * @param json the json 198 | */ 199 | public static void json(String json) { 200 | log(JSON, null, json); 201 | } 202 | 203 | /** 204 | * 输出json 205 | * 206 | * @param tag the tag 207 | * @param json the json 208 | */ 209 | public static void json(String tag, String json) { 210 | log(JSON, tag, json); 211 | } 212 | 213 | /** 214 | * 输出xml 215 | * 216 | * @param xml the xml 217 | */ 218 | public static void xml(String xml) { 219 | log(XML, null, xml); 220 | } 221 | 222 | /** 223 | * Xml. 224 | * 225 | * @param tag the tag 226 | * @param xml the xml 227 | */ 228 | public static void xml(String tag, String xml) { 229 | log(XML, tag, xml); 230 | } 231 | 232 | private static void log(int logType, String tagStr, Object objects) { 233 | String[] contents = wrapperContent(tagStr, objects); 234 | String tag = contents[0]; 235 | String msg = contents[1]; 236 | String headString = contents[2]; 237 | if (LOG_DEBUG) { 238 | switch (logType) { 239 | case VERBOSE: 240 | case DEBUG: 241 | case INFO: 242 | case WARN: 243 | case ERROR: 244 | case ASSERT: 245 | printDefault(logType, tag, headString + msg); 246 | break; 247 | case JSON: 248 | printJson(tag, msg, headString); 249 | break; 250 | case XML: 251 | printXml(tag, msg, headString); 252 | break; 253 | default: 254 | break; 255 | } 256 | } 257 | } 258 | 259 | private static void printDefault(int type, String tag, String msg) { 260 | if (TextUtils.isEmpty(tag)) { 261 | tag = TAG; 262 | } 263 | int index = 0; 264 | int maxLength = 4000; 265 | int countOfSub = msg.length() / maxLength; 266 | 267 | if (countOfSub > 0) { // The log is so long 268 | for (int i = 0; i < countOfSub; i++) { 269 | String sub = msg.substring(index, index + maxLength); 270 | printSub(type, tag, sub); 271 | index += maxLength; 272 | } 273 | //printSub(type, msg.substring(index, msg.length())); 274 | } else { 275 | printSub(type, tag, msg); 276 | } 277 | 278 | } 279 | 280 | private static void printSub(int type, String tag, String sub) { 281 | if (tag == null) { 282 | tag = TAG; 283 | } 284 | printLine(tag, true); 285 | switch (type) { 286 | case VERBOSE: 287 | Log.v(tag, sub); 288 | break; 289 | case DEBUG: 290 | Log.d(tag, sub); 291 | break; 292 | case INFO: 293 | Log.i(tag, sub); 294 | break; 295 | case WARN: 296 | Log.w(tag, sub); 297 | break; 298 | case ERROR: 299 | Log.e(tag, sub); 300 | break; 301 | case ASSERT: 302 | Log.wtf(tag, sub); 303 | break; 304 | } 305 | printLine(tag, false); 306 | } 307 | 308 | private static void printJson(String tag, String json, String headString) { 309 | if (TextUtils.isEmpty(json)) { 310 | d("Empty/Null json content"); 311 | return; 312 | } 313 | if (TextUtils.isEmpty(tag)) { 314 | tag = TAG; 315 | } 316 | String message; 317 | 318 | try { 319 | if (json.startsWith("{")) { 320 | JSONObject jsonObject = new JSONObject(json); 321 | message = jsonObject.toString(JSON_INDENT); 322 | } else if (json.startsWith("[")) { 323 | JSONArray jsonArray = new JSONArray(json); 324 | message = jsonArray.toString(JSON_INDENT); 325 | } else { 326 | message = json; 327 | } 328 | } catch (JSONException e) { 329 | message = json; 330 | } 331 | 332 | printLine(tag, true); 333 | message = headString + LINE_SEPARATOR + message; 334 | String[] lines = message.split(LINE_SEPARATOR); 335 | for (String line : lines) { 336 | Log.d(tag, "|" + line); 337 | } 338 | printLine(tag, false); 339 | } 340 | 341 | private static void printXml(String tag, String xml, String headString) { 342 | if (TextUtils.isEmpty(tag)) { 343 | tag = TAG; 344 | } 345 | if (xml != null) { 346 | try { 347 | Source xmlInput = new StreamSource(new StringReader(xml)); 348 | StreamResult xmlOutput = new StreamResult(new StringWriter()); 349 | Transformer transformer = TransformerFactory.newInstance().newTransformer(); 350 | transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 351 | transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); 352 | transformer.transform(xmlInput, xmlOutput); 353 | xml = xmlOutput.getWriter().toString().replaceFirst(">", ">\n"); 354 | } catch (Exception e) { 355 | e.printStackTrace(); 356 | } 357 | xml = headString + "\n" + xml; 358 | } else { 359 | xml = headString + "Log with null object"; 360 | } 361 | 362 | printLine(tag, true); 363 | String[] lines = xml.split(LINE_SEPARATOR); 364 | for (String line : lines) { 365 | if (!TextUtils.isEmpty(line)) { 366 | Log.d(tag, "|" + line); 367 | } 368 | } 369 | printLine(tag, false); 370 | } 371 | 372 | private static String[] wrapperContent(String tag, Object... objects) { 373 | if (TextUtils.isEmpty(tag)) { 374 | tag = TAG; 375 | } 376 | StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); 377 | StackTraceElement targetElement = stackTrace[5]; 378 | String className = targetElement.getClassName(); 379 | String[] classNameInfo = className.split("\\."); 380 | if (classNameInfo.length > 0) { 381 | className = classNameInfo[classNameInfo.length - 1] + ".java"; 382 | } 383 | String methodName = targetElement.getMethodName(); 384 | int lineNumber = targetElement.getLineNumber(); 385 | if (lineNumber < 0) { 386 | lineNumber = 0; 387 | } 388 | String methodNameShort = methodName.substring(0, 1).toUpperCase() + methodName.substring(1); 389 | String msg = (objects == null) ? "Log with null object" : getObjectsString(objects); 390 | String headString = "[(" + className + ":" + lineNumber + ")#" + methodNameShort + " ] "; 391 | return new String[]{tag, msg, headString}; 392 | } 393 | 394 | private static String getObjectsString(Object... objects) { 395 | 396 | if (objects.length > 1) { 397 | StringBuilder stringBuilder = new StringBuilder(); 398 | stringBuilder.append("\n"); 399 | for (int i = 0; i < objects.length; i++) { 400 | Object object = objects[i]; 401 | if (object == null) { 402 | stringBuilder.append("param").append("[").append(i).append("]").append(" = ").append("null").append("\n"); 403 | } else { 404 | stringBuilder.append("param").append("[").append(i).append("]").append(" = ").append(object.toString()).append("\n"); 405 | } 406 | } 407 | return stringBuilder.toString(); 408 | } else { 409 | Object object = objects[0]; 410 | return object == null ? "null" : object.toString(); 411 | } 412 | } 413 | 414 | private static void printLine(String tag, boolean isTop) { 415 | if (isTop) { 416 | Log.d(tag, "╔═══════════════════════════════════════════════════════════════════════════════════════"); 417 | } else { 418 | Log.d(tag, "╚═══════════════════════════════════════════════════════════════════════════════════════"); 419 | } 420 | } 421 | } 422 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/MathUtil.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import java.math.BigDecimal; 4 | 5 | /** 6 | * Created by gyf on 2016/11/15. 7 | */ 8 | 9 | public class MathUtil { 10 | /** 11 | * 字符串转Integer 12 | * @param numStr 字符串数字 13 | * @return int.若为null表示字符串为空或者转换错误 14 | */ 15 | public static Integer str2Integer(String numStr){ 16 | if(StringUtil.isEmpty(numStr)){ 17 | return null; 18 | }else { 19 | try{ 20 | return Integer.parseInt(numStr); 21 | }catch (Exception e){ 22 | return null; 23 | } 24 | } 25 | } 26 | 27 | /** 28 | * 判断数值是否相等 29 | * @param num 数值 30 | * @param numStr 字符串数值 31 | * @return boolean:true相等,false否 32 | */ 33 | public static boolean numEqualsNumstr(int num, String numStr) { 34 | Integer num2 = str2Integer(numStr); 35 | return null != num2 && num == num2; 36 | } 37 | 38 | 39 | /** 40 | * 获取四舍五入的小数 41 | * @param num 数字字符串 42 | * @param scale 保留小数位 43 | */ 44 | public static String getScaleData(String num, int scale){ 45 | if(StringUtil.isEmpty(num)){ 46 | num= "0"; 47 | } 48 | BigDecimal mData = new BigDecimal(num) 49 | .setScale(scale, BigDecimal.ROUND_HALF_UP); //四舍五入,保留两位小数 50 | 51 | return ""+mData; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/NetUtils.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import android.app.Activity; 4 | import android.content.ComponentName; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.net.ConnectivityManager; 8 | import android.net.NetworkInfo; 9 | import android.net.wifi.ScanResult; 10 | import android.net.wifi.WifiInfo; 11 | import android.net.wifi.WifiManager; 12 | import android.telephony.TelephonyManager; 13 | import android.text.TextUtils; 14 | 15 | import java.lang.reflect.Field; 16 | import java.lang.reflect.InvocationTargetException; 17 | import java.lang.reflect.Method; 18 | import java.util.List; 19 | 20 | /** 21 | * The type Net utils. 22 | */ 23 | public class NetUtils { 24 | 25 | /** 26 | * The constant NETWORK_TYPE_WIFI. 27 | */ 28 | public static final String NETWORK_TYPE_WIFI = "wifi"; 29 | /** 30 | * The constant NETWORK_TYPE_3G. 31 | */ 32 | public static final String NETWORK_TYPE_3G = "3g"; 33 | /** 34 | * The constant NETWORK_TYPE_2G. 35 | */ 36 | public static final String NETWORK_TYPE_2G = "2g"; 37 | /** 38 | * The constant NETWORK_TYPE_WAP. 39 | */ 40 | public static final String NETWORK_TYPE_WAP = "wap"; 41 | /** 42 | * The constant NETWORK_TYPE_UNKNOWN. 43 | */ 44 | public static final String NETWORK_TYPE_UNKNOWN = "unknown"; 45 | /** 46 | * The constant NETWORK_TYPE_DISCONNECT. 47 | */ 48 | public static final String NETWORK_TYPE_DISCONNECT = "disconnect"; 49 | 50 | /** 51 | * 获取网络类型 52 | * 53 | * @param context the context 54 | * @return the network type 55 | */ 56 | public static int getNetworkType(Context context) { 57 | ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 58 | NetworkInfo networkInfo = connectivityManager == null ? null : connectivityManager.getActiveNetworkInfo(); 59 | return networkInfo == null ? -1 : networkInfo.getType(); 60 | } 61 | 62 | /** 63 | * 获取网络名称 64 | * 65 | * @param context the context 66 | * @return the network type name 67 | */ 68 | public static String getNetworkTypeName(Context context) { 69 | ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 70 | NetworkInfo networkInfo; 71 | String type = NETWORK_TYPE_DISCONNECT; 72 | if (manager == null || (networkInfo = manager.getActiveNetworkInfo()) == null) { 73 | return type; 74 | } 75 | 76 | if (networkInfo.isConnected()) { 77 | String typeName = networkInfo.getTypeName(); 78 | if ("WIFI".equalsIgnoreCase(typeName)) { 79 | type = NETWORK_TYPE_WIFI; 80 | } else if ("MOBILE".equalsIgnoreCase(typeName)) { 81 | //String proxyHost = android.net.Proxy.getDefaultHost();//deprecated 82 | String proxyHost = System.getProperty("http.proxyHost"); 83 | type = TextUtils.isEmpty(proxyHost) ? (isFastMobileNetwork(context) ? NETWORK_TYPE_3G : NETWORK_TYPE_2G) : NETWORK_TYPE_WAP; 84 | } else { 85 | type = NETWORK_TYPE_UNKNOWN; 86 | } 87 | } 88 | return type; 89 | } 90 | 91 | /** 92 | * 检查网络状态 93 | * 94 | * @param context the context 95 | * @return the boolean 96 | */ 97 | public static boolean isConnected(Context context) { 98 | ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 99 | NetworkInfo info = cm.getActiveNetworkInfo(); 100 | if (info != null && info.isConnected()) { 101 | if (info.getState() == NetworkInfo.State.CONNECTED) { 102 | return true; 103 | } 104 | } 105 | return false; 106 | } 107 | 108 | /** 109 | * 网络可用性 110 | * 111 | * @param context the context 112 | * @return the boolean 113 | */ 114 | public static boolean isNetworkAvailable(Context context) { 115 | if (context == null) { 116 | return false; 117 | } 118 | try { 119 | ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 120 | if (connectivity != null) { 121 | NetworkInfo info = connectivity.getActiveNetworkInfo(); 122 | return info.isAvailable(); 123 | } 124 | } catch (Exception e) { 125 | return false; 126 | } 127 | return false; 128 | } 129 | 130 | /** 131 | * 是否wifi 132 | * 133 | * @param cxt the cxt 134 | * @return the boolean 135 | */ 136 | public static boolean isWiFi(Context cxt) { 137 | ConnectivityManager cm = (ConnectivityManager) cxt.getSystemService(Context.CONNECTIVITY_SERVICE); 138 | // wifi的状态:ConnectivityManager.TYPE_WIFI 139 | // 3G的状态:ConnectivityManager.TYPE_MOBILE 140 | return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; 141 | } 142 | 143 | /** 144 | * 打开网络设置界面 145 | * 146 | * @param act the act 147 | */ 148 | //unchecked 149 | public static void openNetSetting(Activity act) { 150 | Intent intent = new Intent(); 151 | ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings"); 152 | intent.setComponent(cm); 153 | intent.setAction("android.intent.action.VIEW"); 154 | act.startActivityForResult(intent, 0); 155 | } 156 | 157 | 158 | /** 159 | * Whether is fast mobile network 160 | */ 161 | 162 | private static boolean isFastMobileNetwork(Context context) { 163 | TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 164 | if (telephonyManager == null) { 165 | return false; 166 | } 167 | 168 | switch (telephonyManager.getNetworkType()) { 169 | case TelephonyManager.NETWORK_TYPE_1xRTT: 170 | return false; 171 | case TelephonyManager.NETWORK_TYPE_CDMA: 172 | return false; 173 | case TelephonyManager.NETWORK_TYPE_EDGE: 174 | return false; 175 | case TelephonyManager.NETWORK_TYPE_EVDO_0: 176 | return true; 177 | case TelephonyManager.NETWORK_TYPE_EVDO_A: 178 | return true; 179 | case TelephonyManager.NETWORK_TYPE_GPRS: 180 | return false; 181 | case TelephonyManager.NETWORK_TYPE_HSDPA: 182 | return true; 183 | case TelephonyManager.NETWORK_TYPE_HSPA: 184 | return true; 185 | case TelephonyManager.NETWORK_TYPE_HSUPA: 186 | return true; 187 | case TelephonyManager.NETWORK_TYPE_UMTS: 188 | return true; 189 | case TelephonyManager.NETWORK_TYPE_EHRPD: 190 | return true; 191 | case TelephonyManager.NETWORK_TYPE_EVDO_B: 192 | return true; 193 | case TelephonyManager.NETWORK_TYPE_HSPAP: 194 | return true; 195 | case TelephonyManager.NETWORK_TYPE_IDEN: 196 | return false; 197 | case TelephonyManager.NETWORK_TYPE_LTE: 198 | return true; 199 | case TelephonyManager.NETWORK_TYPE_UNKNOWN: 200 | return false; 201 | default: 202 | return false; 203 | } 204 | } 205 | 206 | /** 207 | * 设置wifi状态 208 | * 209 | * @param context the context 210 | * @param enabled the enabled 211 | */ 212 | public static void setWifiEnabled(Context context, boolean enabled) { 213 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 214 | wifiManager.setWifiEnabled(enabled); 215 | } 216 | 217 | /** 218 | * 设置数据流量状态 219 | * 220 | * @param context the context 221 | * @param enabled the enabled 222 | */ 223 | public static void setDataEnabled(Context context, boolean enabled) { 224 | ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 225 | Class conMgrClass = null; 226 | Field iConMgrField = null; 227 | Object iConMgr = null; 228 | Class iConMgrClass = null; 229 | Method setMobileDataEnabledMethod = null; 230 | try { 231 | conMgrClass = Class.forName(conMgr.getClass().getName()); 232 | iConMgrField = conMgrClass.getDeclaredField("mService"); 233 | iConMgrField.setAccessible(true); 234 | iConMgr = iConMgrField.get(conMgr); 235 | iConMgrClass = Class.forName(iConMgr.getClass().getName()); 236 | setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); 237 | setMobileDataEnabledMethod.setAccessible(true); 238 | setMobileDataEnabledMethod.invoke(iConMgr, enabled); 239 | } catch (Exception e) { 240 | e.printStackTrace(); 241 | } 242 | } 243 | 244 | /** 245 | * 获取wifi列表 246 | * 247 | * @param context the context 248 | * @return the wifi scan results 249 | */ 250 | public static List getWifiScanResults(Context context) { 251 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 252 | return wifiManager.startScan() ? wifiManager.getScanResults() : null; 253 | } 254 | 255 | /** 256 | * 过滤扫描结果 257 | * 258 | * @param context the context 259 | * @param bssid the bssid 260 | * @return the scan results by bssid 261 | */ 262 | public static ScanResult getScanResultsByBSSID(Context context, String bssid) { 263 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 264 | ScanResult scanResult = null; 265 | boolean f = wifiManager.startScan(); 266 | if (!f) { 267 | getScanResultsByBSSID(context, bssid); 268 | } 269 | List list = wifiManager.getScanResults(); 270 | if (list != null) { 271 | for (int i = 0; i < list.size(); i++) { 272 | scanResult = list.get(i); 273 | if (scanResult.BSSID.equals(bssid)) { 274 | break; 275 | } 276 | } 277 | } 278 | return scanResult; 279 | } 280 | 281 | /** 282 | * 获取wifi连接信息 283 | * 284 | * @param context the context 285 | * @return the wifi connection info 286 | */ 287 | public static WifiInfo getWifiConnectionInfo(Context context) { 288 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 289 | return wifiManager.getConnectionInfo(); 290 | } 291 | } 292 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/SPUtils.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | import android.content.SharedPreferences.Editor; 6 | 7 | /** 8 | * The type Sp utils. 9 | */ 10 | public class SPUtils { 11 | 12 | /** 13 | * 存储SharedPreferences值 14 | * 15 | * @param context the context 16 | * @param filename the filename 17 | * @param key the key 18 | * @param object the object 19 | */ 20 | public static void setSP(Context context, String filename, String key, Object object) { 21 | String type = object.getClass().getSimpleName(); 22 | String packageName = context.getPackageName(); 23 | SharedPreferences sp = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); 24 | Editor edit = sp.edit(); 25 | if ("String".equals(type)) { 26 | edit.putString(key, (String) object); 27 | } else if ("Integer".equals(type)) { 28 | edit.putInt(key, (Integer) object); 29 | } else if ("Boolean".equals(type)) { 30 | edit.putBoolean(key, (Boolean) object); 31 | } else if ("Float".equals(type)) { 32 | edit.putFloat(key, (Float) object); 33 | } else if ("Long".equals(type)) { 34 | edit.putLong(key, (Long) object); 35 | } 36 | edit.apply(); 37 | } 38 | 39 | /** 40 | * 获取SharedPreferences值 41 | * 42 | * @param context the context 43 | * @param key the key 44 | * @param defaultObject the default object 45 | * @return the sp 46 | */ 47 | public static Object getSp(Context context, String key, Object defaultObject) { 48 | String type = defaultObject.getClass().getSimpleName(); 49 | String packageName = context.getPackageName(); 50 | SharedPreferences sp = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); 51 | if ("String".equals(type)) { 52 | return sp.getString(key, (String) defaultObject); 53 | } else if ("Integer".equals(type)) { 54 | return sp.getInt(key, (Integer) defaultObject); 55 | } else if ("Boolean".equals(type)) { 56 | return sp.getBoolean(key, (Boolean) defaultObject); 57 | } else if ("Float".equals(type)) { 58 | return sp.getFloat(key, (Float) defaultObject); 59 | } else if ("Long".equals(type)) { 60 | return sp.getLong(key, (Long) defaultObject); 61 | } 62 | return null; 63 | } 64 | 65 | /** 66 | * 清除所有的SP值 67 | * 68 | * @param context the context 69 | */ 70 | public static void cleanAllSP(Context context) { 71 | String packageName = context.getPackageName(); 72 | SharedPreferences sp = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); 73 | Editor editor = sp.edit(); 74 | editor.clear(); 75 | editor.apply(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/VerificationUtils.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import android.text.TextUtils; 4 | 5 | import java.text.SimpleDateFormat; 6 | import java.util.regex.Pattern; 7 | 8 | /** 9 | * https://github.com/sharinghuang/ASRabbit/blob/7350ea1c212946633316d36760c7088728dc2730/baselib/src/main/java/com/ht/baselib/utils/FormatVerificationUtils.java 10 | */ 11 | public class VerificationUtils { 12 | /** 13 | * 判断真实姓名是否格式正确 14 | *

15 | * 要求:真实姓名可以是汉字,也可以是字母,但是不能两者都有,也不能包含任何符号和数字 16 | * 注意:1.如果是英文名,可以允许英文名字中出现空格 17 | * 2.英文名的空格可以是多个,但是不能连续出现多个 18 | * 3.汉字不能出现空格 19 | *

20 | * 21 | * @param value 真实姓名字符串 22 | * @return true为正确,false为错误 23 | */ 24 | public static boolean matcherRealName(String value) { 25 | String regex = "^([\\u4e00-\\u9fa5]+|([a-zA-Z]+\\s?)+)$"; 26 | return testRegex(regex, value); 27 | } 28 | 29 | /** 30 | * 判断手机号码是否格式正确 31 | * 32 | * @param value 手机号码字符串 33 | * @return true为正确,false为错误 34 | */ 35 | public static boolean matcherPhoneNum(String value) { 36 | // 匹配11数字,并且13-19开头 37 | String regex = "^((13[0-9])|(14[57])|(15[^4])|(17[013678])|(18[0-9]))\\d{8}$"; 38 | return testRegex(regex, value); 39 | } 40 | 41 | /** 42 | * 判断密码格式正确(必须输入6-12位非纯数字、英文的密码) 43 | * 44 | * @param value 密码字符串 45 | * @return true为正确,false为错误 46 | */ 47 | public static boolean matcherPassword(String value) { 48 | // String regex = "^[a-zA-Z0-9]{6,12}$";// (6-12位字母或数字) 49 | String regex = "(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}";//(6-12位字母或数字,必须同时包含字母和数字) 50 | return testRegex(regex, value); 51 | } 52 | 53 | /** 54 | * 判断注册账号格式正确 55 | * 56 | * @param value 账号字符串 57 | * @return true为正确,false为错误 58 | */ 59 | public static boolean matcherAccount(String value) { 60 | // (4-20位字符) 61 | String regex = "[\\u4e00-\\u9fa5a-zA-Z0-9\\-]{4,20}"; 62 | return testRegex(regex, value); 63 | } 64 | 65 | /** 66 | * 判断邮箱格式正确 67 | * 68 | * @param value 邮箱字符串 69 | * @return true为正确,false为错误 70 | */ 71 | public static boolean matcherEmail(String value) { 72 | // String regex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)" + 73 | // "+[a-zA-Z]{2,}$"; 74 | String regex = "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+" + 75 | "(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+" + 76 | "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"; 77 | return testRegex(regex, value); 78 | } 79 | 80 | /** 81 | * 判断IP地址格式正确 82 | * 83 | * @param value IP字符串 84 | * @return true为正确,false为错误 85 | */ 86 | public static boolean matcherIP(String value) { 87 | String regex = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\" + 88 | "d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\" + 89 | "d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b"; 90 | return testRegex(regex, value.toLowerCase()); 91 | } 92 | 93 | /** 94 | * 判断身份证格式正确性 95 | * 96 | * @param value 身份证字符串 97 | * @return true为正确,false为错误 98 | */ 99 | 100 | public static boolean matcherIdentityCard(String value) { 101 | // String regex = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|" + 102 | // "(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|" + 103 | // "\\d{3}[Xx])$)$"; 104 | // return testRegex(regex, value); 105 | IDCardTester idCardTester = new IDCardTester(); 106 | return idCardTester.test(value); 107 | } 108 | 109 | /** 110 | * 判断网址格式正确性 支持http,https,ftp 111 | * 112 | * @param value 网址字符串 113 | * @return true为正确,false为错误 114 | */ 115 | public static boolean matcherUrl(String value) { 116 | String regex = "^(([hH][tT]{2}[pP][sS]?)|([fF][tT][pP]))\\:\\/\\/[wW]{3}\\.[\\w-]+\\.\\w{2,4}(\\/.*)?$"; 117 | return testRegex(regex, value.toLowerCase()); 118 | } 119 | 120 | 121 | /** 122 | * 中国民用车辆号牌 123 | * 124 | * @param value 车牌号码 125 | * @return true为正确,false为错误 126 | */ 127 | public static boolean matcherVehicleNumber(String value) { 128 | String regex = "^[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云藏陕甘青宁新渝]?[A-Z][A-HJ-NP-Z0-9学挂港澳练]{5}$"; 129 | return testRegex(regex, value.toLowerCase()); 130 | } 131 | // 公用方法 132 | //============================================================ 133 | 134 | /** 135 | * 身份证校验 136 | *

137 | * 根据〖中华人民共和国国家标准 GB 11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。 138 | * 地址码表示编码对象常住户口所在县(市、旗、区)的行政区划代码。 139 | * 出生日期码表示编码对象出生的年、月、日,其中年份用四位数字表示,年、月、日之间不用分隔符。 140 | * 顺序码表示同一地址码所标识的区域范围内,对同年、月、日出生的人员编定的顺序号。顺序码的奇数分给男性,偶数分给女性。 141 | * 校验码是根据前面十七位数字码,按照ISO 7064:1983.MOD 11-2校验码计算出来的检验码。 142 | * 出生日期计算方法。 143 | * 15位的身份证编码首先把出生年扩展为4位,简单的就是增加一个19或18,这样就包含了所有1800-1999年出生的人; 144 | * 2000年后出生的肯定都是18位的了没有这个烦恼,至于1800年前出生的,那啥那时应该还没身份证号这个东东,⊙﹏⊙b汗... 145 | * 下面是正则表达式: 146 | * 出生日期1800-2099 /(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])/ 147 | * 身份证正则表达式 /^[1-9]\d{5}((1[89]|20)\d{2})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dx]$/i 148 | * 15位校验规则 6位地址编码+6位出生日期+3位顺序号 149 | * 18位校验规则 6位地址编码+8位出生日期+3位顺序号+1位校验位 150 | * 校验位规则 公式:∑(ai×Wi)(mod 11)……………………………………(1) 151 | * 公式(1)中: 152 | * i----表示号码字符从由至左包括校验码在内的位置序号; 153 | * ai----表示第i位置上的号码字符值; 154 | * Wi----示第i位置上的加权因子,其数值依据公式Wi=2^(n-1)(mod 11)计算得出。 155 | * i 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 156 | * Wi 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 1 157 | *

158 | * 159 | * @author Yoojia.Chen (yoojia.chen@gmail.com) 160 | * @version version 2015-05-21 161 | * @since 2.0 162 | */ 163 | private static class IDCardTester { 164 | public boolean test(String content) { 165 | if (TextUtils.isEmpty(content)) { 166 | return false; 167 | } 168 | final int length = content.length(); 169 | if (15 == length) { 170 | try { 171 | return isOldCNIDCard(content); 172 | } catch (NumberFormatException e) { 173 | e.printStackTrace(); 174 | return false; 175 | } 176 | } else if (18 == length) { 177 | return isNewCNIDCard(content); 178 | } else { 179 | return false; 180 | } 181 | } 182 | 183 | final int[] WEIGHT = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; 184 | 185 | final char[] VALID = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}; 186 | 187 | public boolean isNewCNIDCard(String numbers) { 188 | //转换字符串中的字母为大写字母 189 | numbers = numbers.toUpperCase(); 190 | int sum = 0; 191 | for (int i = 0; i < WEIGHT.length; i++) { 192 | final int cell = Character.getNumericValue(numbers.charAt(i)); 193 | sum += WEIGHT[i] * cell; 194 | } 195 | int index = sum % 11; 196 | return VALID[index] == numbers.charAt(17); 197 | } 198 | 199 | public boolean isOldCNIDCard(String numbers) { 200 | //ABCDEFYYMMDDXXX 201 | String yymmdd = numbers.substring(6, 11); 202 | boolean aPass = numbers.equals(String.valueOf(Long.parseLong(numbers))); 203 | boolean yPass = true; 204 | try { 205 | new SimpleDateFormat("yyMMdd").parse(yymmdd); 206 | } catch (Exception e) { 207 | e.printStackTrace(); 208 | yPass = false; 209 | } 210 | return aPass && yPass; 211 | } 212 | } 213 | 214 | /** 215 | * 是否数值型 216 | *
implements commit apache common utils 217 | * 218 | * @param input 校验内容 219 | * @return true为正确,false为错误 220 | */ 221 | public static boolean isNumeric(String input) { 222 | if (TextUtils.isEmpty(input)) { 223 | return false; 224 | } 225 | char[] chars = input.toCharArray(); 226 | int sz = chars.length; 227 | boolean hasExp = false; 228 | boolean hasDecPoint = false; 229 | boolean allowSigns = false; 230 | boolean foundDigit = false; 231 | // deal loader any possible sign up front 232 | int start = (chars[0] == '-' || chars[0] == '+') ? 1 : 0; 233 | if (sz > start + 1) { 234 | if (chars[start] == '0' && chars[start + 1] == 'x') { 235 | int i = start + 2; 236 | if (i == sz) { 237 | return false; // str == "0x" 238 | } 239 | // checking hex (it can't be anything else) 240 | for (; i < chars.length; i++) { 241 | if ((chars[i] < '0' || chars[i] > '9') 242 | && (chars[i] < 'a' || chars[i] > 'f') 243 | && (chars[i] < 'A' || chars[i] > 'F')) { 244 | return false; 245 | } 246 | } 247 | return true; 248 | } 249 | } 250 | sz--; // don't want to loop to the last char, check it afterwords 251 | // for build qualifiers 252 | int i = start; 253 | // loop to the next to last char or to the last char if we need another digit to 254 | // make a valid numeric (e.g. chars[0..5] = "1234E") 255 | while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { 256 | if (chars[i] >= '0' && chars[i] <= '9') { 257 | foundDigit = true; 258 | allowSigns = false; 259 | 260 | } else if (chars[i] == '.') { 261 | if (hasDecPoint || hasExp) { 262 | // two decimal points or dec in exponent 263 | return false; 264 | } 265 | hasDecPoint = true; 266 | } else if (chars[i] == 'e' || chars[i] == 'E') { 267 | // we've already taken care of hex. 268 | if (hasExp) { 269 | // two E's 270 | return false; 271 | } 272 | if (!foundDigit) { 273 | return false; 274 | } 275 | hasExp = true; 276 | allowSigns = true; 277 | } else if (chars[i] == '+' || chars[i] == '-') { 278 | if (!allowSigns) { 279 | return false; 280 | } 281 | allowSigns = false; 282 | foundDigit = false; // we need a digit after the E 283 | } else { 284 | return false; 285 | } 286 | i++; 287 | } 288 | if (i < chars.length) { 289 | if (chars[i] >= '0' && chars[i] <= '9') { 290 | // no build qualifier, OK 291 | return true; 292 | } 293 | if (chars[i] == 'e' || chars[i] == 'E') { 294 | // can't have an E at the last byte 295 | return false; 296 | } 297 | if (!allowSigns 298 | && (chars[i] == 'd' 299 | || chars[i] == 'D' 300 | || chars[i] == 'f' 301 | || chars[i] == 'F')) { 302 | return foundDigit; 303 | } 304 | if (chars[i] == 'l' 305 | || chars[i] == 'L') { 306 | // not allowing L loader an exponent 307 | return foundDigit && !hasExp; 308 | } 309 | // last character is illegal 310 | return false; 311 | } 312 | // allowSigns is true iff the val ends in 'E' 313 | // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass 314 | return !allowSigns && foundDigit; 315 | } 316 | 317 | /** 318 | * 校验内容是否匹配指定正则表达式 319 | * 320 | * @param regex 正则表达式 321 | * @param inputValue 内容 322 | * @return 是否匹配 true为匹配,false为不匹配 323 | */ 324 | public static boolean testRegex(String regex, String inputValue) { 325 | return Pattern.compile(regex).matcher(inputValue).matches(); 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/ViewUtils.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.ContextWrapper; 6 | import android.content.res.Resources; 7 | import android.content.res.TypedArray; 8 | import android.graphics.Bitmap; 9 | import android.graphics.Canvas; 10 | import android.graphics.Matrix; 11 | import android.graphics.Paint; 12 | import android.graphics.drawable.BitmapDrawable; 13 | import android.view.LayoutInflater; 14 | import android.view.MotionEvent; 15 | import android.view.View; 16 | import android.view.View.MeasureSpec; 17 | import android.view.ViewGroup; 18 | import android.view.ViewParent; 19 | import android.widget.PopupWindow; 20 | import android.widget.TextView; 21 | import android.widget.Toast; 22 | 23 | 24 | /** 25 | * The type View utils. 26 | */ 27 | public class ViewUtils { 28 | 29 | /** 30 | * Remove self from parent. 31 | * 32 | * @param view the view 33 | */ 34 | public static void removeSelfFromParent(View view) { 35 | if (view != null) { 36 | ViewParent parent = view.getParent(); 37 | if (parent != null && parent instanceof ViewGroup) { 38 | ViewGroup group = (ViewGroup) parent; 39 | group.removeView(view); 40 | } 41 | } 42 | } 43 | 44 | 45 | /** 46 | * Request layout parent. 47 | * 48 | * @param view the view 49 | * @param isAll the is all 50 | */ 51 | public static void requestLayoutParent(View view, boolean isAll) { 52 | ViewParent parent = view.getParent(); 53 | while (parent != null && parent instanceof View) { 54 | if (!parent.isLayoutRequested()) { 55 | parent.requestLayout(); 56 | if (!isAll) { 57 | break; 58 | } 59 | } 60 | parent = parent.getParent(); 61 | } 62 | } 63 | 64 | 65 | /** 66 | * Is touch in view boolean. 67 | * 68 | * @param ev the ev 69 | * @param v the v 70 | * @return the boolean 71 | */ 72 | public static boolean isTouchInView(MotionEvent ev, View v) { 73 | int[] vLoc = new int[2]; 74 | v.getLocationOnScreen(vLoc); 75 | float motionX = ev.getRawX(); 76 | float motionY = ev.getRawY(); 77 | return motionX >= vLoc[0] && motionX <= (vLoc[0] + v.getWidth()) && motionY >= vLoc[1] && motionY <= (vLoc[1] + v.getHeight()); 78 | } 79 | 80 | /** 81 | * Big image bitmap. 82 | * 83 | * @param bmp the bmp 84 | * @param big the big 85 | * @return the bitmap 86 | */ 87 | public static Bitmap bigImage(Bitmap bmp, float big) { 88 | int bmpWidth = bmp.getWidth(); 89 | int bmpHeight = bmp.getHeight(); 90 | Matrix matrix = new Matrix(); 91 | matrix.postScale(big, big); 92 | return Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeight, matrix, true); 93 | } 94 | 95 | 96 | /** 97 | * 给TextView设置下划线 98 | * 99 | * @param textView the text view 100 | */ 101 | public static void setTVUnderLine(TextView textView) { 102 | textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); 103 | textView.getPaint().setAntiAlias(true); 104 | } 105 | 106 | 107 | /** 108 | * The Popup window. 109 | */ 110 | static PopupWindow popupWindow; 111 | 112 | /** 113 | * Show popup window view. 114 | * 115 | * @param context the context 116 | * @param resId the res id 117 | * @param root the root 118 | * @param paramsType the params type 119 | * @return the view 120 | */ 121 | public static View showPopupWindow(Context context, int resId, View root, int paramsType) { 122 | View popupView; 123 | popupView = LayoutInflater.from(context).inflate(resId, null); 124 | 125 | switch (paramsType) { 126 | case 1: 127 | popupWindow = new PopupWindow(popupView, 128 | ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true); 129 | break; 130 | case 2: 131 | popupWindow = new PopupWindow(popupView, 132 | ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true); 133 | break; 134 | case 3: 135 | popupWindow = new PopupWindow(popupView, 136 | ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, true); 137 | break; 138 | case 4: 139 | popupWindow = new PopupWindow(popupView, 140 | ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true); 141 | break; 142 | default: 143 | popupWindow = new PopupWindow(popupView, 144 | ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true); 145 | break; 146 | } 147 | popupWindow.setFocusable(true); 148 | popupWindow.setOutsideTouchable(true); 149 | popupWindow.setTouchable(true); 150 | popupWindow.setBackgroundDrawable(new BitmapDrawable()); 151 | popupWindow.showAsDropDown(root); 152 | return popupView; 153 | } 154 | 155 | 156 | /** 157 | * Dismiss popup. 158 | */ 159 | public static void dismissPopup() { 160 | if (popupWindow != null && popupWindow.isShowing()) { 161 | popupWindow.dismiss(); 162 | popupWindow = null; 163 | } 164 | } 165 | 166 | /** 167 | * 截图 168 | * 169 | * @param v the v 170 | * @return the bitmap 171 | */ 172 | public static Bitmap captureView(View v) { 173 | v.setDrawingCacheEnabled(true); 174 | v.buildDrawingCache(); 175 | return v.getDrawingCache(); 176 | } 177 | 178 | 179 | /** 180 | * 截图 181 | * 182 | * @param v the v 183 | * @return the bitmap 184 | */ 185 | public static Bitmap createViewBitmap(View v) { 186 | Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); 187 | Canvas canvas = new Canvas(bitmap); 188 | v.draw(canvas); 189 | return bitmap; 190 | } 191 | 192 | 193 | /** 194 | * 截图 195 | * 196 | * @param view the view 197 | * @return the bitmap 198 | */ 199 | public static Bitmap convertViewToBitmap(View view) { 200 | view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); 201 | view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 202 | view.buildDrawingCache(); 203 | return view.getDrawingCache(); 204 | } 205 | 206 | 207 | /** 208 | * 获取Activity的截图 209 | * 210 | * @param activity the activity 211 | * @return the activity bitmap 212 | */ 213 | public static Bitmap getActivityBitmap(Activity activity) { 214 | View view = activity.getWindow().getDecorView().findViewById(android.R.id.content); 215 | view.setDrawingCacheEnabled(true); 216 | return view.getDrawingCache(); 217 | } 218 | 219 | 220 | /** 221 | * 获取状态栏高度 222 | * 223 | * @param context the context 224 | * @return the status bar height 225 | */ 226 | public static int getStatusBarHeight(Context context) { 227 | int result = 0; 228 | int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); 229 | if (resourceId > 0) { 230 | result = context.getResources().getDimensionPixelSize(resourceId); 231 | } 232 | return result; 233 | } 234 | 235 | 236 | /** 237 | * 获取工具栏高度 238 | * 239 | * @param context the context 240 | * @return the toolbar height 241 | */ 242 | public static int getToolbarHeight(Context context) { 243 | final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(new int[]{R.attr.actionBarSize}); 244 | int toolbarHeight = (int) styledAttributes.getDimension(0, 0); 245 | styledAttributes.recycle(); 246 | return toolbarHeight; 247 | } 248 | 249 | /** 250 | * 获取导航栏高度 251 | * 252 | * @param activity the activity 253 | * @return the navigation bar height 254 | */ 255 | public static int getNavigationBarHeight(Activity activity) { 256 | Resources resources = activity.getResources(); 257 | int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); 258 | if (resourceId > 0) { 259 | return resources.getDimensionPixelSize(resourceId); 260 | } 261 | return 0; 262 | } 263 | 264 | /** 265 | * 测量view 266 | * 267 | * @param view the view 268 | */ 269 | public static void measureView(View view) { 270 | ViewGroup.LayoutParams p = view.getLayoutParams(); 271 | if (p == null) { 272 | p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); 273 | } 274 | 275 | int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width); 276 | int lpHeight = p.height; 277 | int childHeightSpec; 278 | if (lpHeight > 0) { 279 | childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); 280 | } else { 281 | childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 282 | } 283 | view.measure(childWidthSpec, childHeightSpec); 284 | } 285 | 286 | /** 287 | * 获取view的宽度 288 | * 289 | * @param view the view 290 | * @return the view width 291 | */ 292 | public static int getViewWidth(View view) { 293 | measureView(view); 294 | return view.getMeasuredWidth(); 295 | } 296 | 297 | /** 298 | * 获取view的高度 299 | * 300 | * @param view the view 301 | * @return the view height 302 | */ 303 | public static int getViewHeight(View view) { 304 | measureView(view); 305 | return view.getMeasuredHeight(); 306 | } 307 | 308 | /** 309 | * 获取view的上下文 310 | * 311 | * @param view the view 312 | * @return the activity 313 | */ 314 | public static Activity getActivity(View view) { 315 | Context context = view.getContext(); 316 | while (context instanceof ContextWrapper) { 317 | if (context instanceof Activity) { 318 | return (Activity) context; 319 | } 320 | context = ((ContextWrapper) context).getBaseContext(); 321 | } 322 | throw new IllegalStateException("View " + view + " is not attached to an Activity"); 323 | } 324 | } 325 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/Md5.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a.cipher; 2 | 3 | import com.gyf.toolutils4a.StringUtil; 4 | 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.FileNotFoundException; 8 | import java.io.InputStream; 9 | import java.security.MessageDigest; 10 | import java.security.NoSuchAlgorithmException; 11 | 12 | /** 13 | * MD5 加密工具类 14 | * Created by gyf on 2016/11/14. 15 | */ 16 | public class Md5 { 17 | private Md5(){} 18 | /** 19 | * Md 5 string. 20 | * md5加密通过String 21 | * 22 | * @param str the str 23 | * @return the string 24 | */ 25 | public static String MD5(String str) { 26 | try { 27 | // 获得MD5摘要算法的 MessageDigest 对象 28 | MessageDigest mdInst = MessageDigest.getInstance("Md5"); 29 | // 使用指定的字节更新摘要 30 | mdInst.update(str.getBytes()); 31 | // 获得密文 32 | byte[] md = mdInst.digest(); 33 | // 字节数组转换为 十六进制 数并返回 34 | return StringUtil.byte2Hex(md); 35 | } catch (NoSuchAlgorithmException e) { 36 | return ""; 37 | } 38 | } 39 | 40 | /** 41 | * Md 5 string. 42 | * md5加密通过字节数组 43 | * 44 | * @param bytes the bytes 45 | * @return the string 46 | */ 47 | public static String MD5(byte[] bytes) { 48 | try { 49 | MessageDigest mdInst = MessageDigest.getInstance("Md5"); 50 | mdInst.update(bytes); 51 | byte[] md = mdInst.digest(); 52 | return StringUtil.byte2Hex(md); 53 | } catch (NoSuchAlgorithmException e) { 54 | return ""; 55 | } 56 | } 57 | 58 | /** 59 | * Md 5 string. 60 | * md5加密通过输入流 61 | * 62 | * @param is the is 63 | * @return the string 64 | */ 65 | public static String MD5(InputStream is) { 66 | byte[] dataBytes = new byte[1024]; 67 | int read; 68 | try { 69 | MessageDigest mdInst = MessageDigest.getInstance("Md5"); 70 | while ((read = is.read(dataBytes)) != -1) { 71 | mdInst.update(dataBytes, 0, read); 72 | } 73 | byte[] md = mdInst.digest(); 74 | return StringUtil.byte2Hex(md); 75 | } catch (Exception e) { 76 | return ""; 77 | } 78 | } 79 | 80 | /** 81 | * Md 5 string. 82 | * md5加密通过文件 83 | * 84 | * @param file the file 85 | * @return the string 86 | */ 87 | public static String MD5(File file) { 88 | try { 89 | FileInputStream fis = new FileInputStream(file); 90 | return MD5(fis); 91 | } catch (FileNotFoundException e) { 92 | return ""; 93 | } 94 | 95 | } 96 | 97 | /** 98 | * Md 5 by path string. 99 | * md5加密通过文件路径 100 | * 101 | * @param path the path 102 | * @return the string 103 | */ 104 | public static String MD5ByPath(String path) { 105 | try { 106 | FileInputStream fis = new FileInputStream(path); 107 | return MD5(fis); 108 | } catch (FileNotFoundException e) { 109 | return ""; 110 | } 111 | } 112 | 113 | 114 | /** 115 | * Md 5 check boolean. 116 | * md5检验通过字符串 117 | * 118 | * @param str the str 119 | * @param toBeCheckSum the to be check sum 120 | * @return the boolean 121 | */ 122 | public static boolean MD5Check(String str, String toBeCheckSum) { 123 | return MD5(str).equals(toBeCheckSum); 124 | } 125 | 126 | /** 127 | * Md 5 check boolean. 128 | * md5检验通过字节数组 129 | * 130 | * @param bytes the bytes 131 | * @param toBeCheckSum the to be check sum 132 | * @return the boolean 133 | */ 134 | public static boolean MD5Check(byte[] bytes, String toBeCheckSum) { 135 | return MD5(bytes).equals(toBeCheckSum); 136 | } 137 | 138 | /** 139 | * Md 5 check boolean. 140 | * md5检验通过输入流 141 | * 142 | * @param is the is 143 | * @param toBeCheckSum the to be check sum 144 | * @return the boolean 145 | */ 146 | public static boolean MD5Check(InputStream is, String toBeCheckSum) { 147 | return MD5(is).equals(toBeCheckSum); 148 | } 149 | 150 | /** 151 | * Md 5 check boolean. 152 | * md5检验通过文件 153 | * 154 | * @param file the file 155 | * @param toBeCheckSum the to be check sum 156 | * @return the boolean 157 | */ 158 | public static boolean MD5Check(File file, String toBeCheckSum) { 159 | return MD5(file).equals(toBeCheckSum); 160 | } 161 | 162 | /** 163 | * Md 5 check boolean. 164 | * md5检验通过文件路径 165 | * 166 | * @param path the path 167 | * @param toBeCheckSum the to be check sum 168 | * @return the boolean 169 | */ 170 | public static boolean MD5CheckByPath(String path, String toBeCheckSum) { 171 | return MD5ByPath(path).equals(toBeCheckSum); 172 | } 173 | 174 | } 175 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/Sha1.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a.cipher; 2 | 3 | import com.gyf.toolutils4a.StringUtil; 4 | 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.FileNotFoundException; 8 | import java.io.InputStream; 9 | import java.security.MessageDigest; 10 | import java.security.NoSuchAlgorithmException; 11 | 12 | /** 13 | * SHA1 加密工具类 14 | * Created by gyf on 2016/11/14. 15 | */ 16 | public class Sha1 { 17 | 18 | private Sha1(){} 19 | /** 20 | * Sha 1 string. 21 | * sha1加密通过字符串 22 | * 23 | * @param str the str 24 | * @return the string 25 | */ 26 | public static String SHA1(String str) { 27 | try { 28 | MessageDigest digest = MessageDigest.getInstance("SHA-1"); 29 | digest.update(str.getBytes()); 30 | byte md[] = digest.digest(); 31 | return StringUtil.byte2Hex(md); 32 | 33 | } catch (NoSuchAlgorithmException e) { 34 | return ""; 35 | } 36 | } 37 | 38 | /** 39 | * Sha 1 string. 40 | * sha1加密通过字节数组 41 | * 42 | * @param bytes the bytes 43 | * @return the string 44 | */ 45 | public static String SHA1(byte[] bytes) { 46 | try { 47 | MessageDigest digest = MessageDigest.getInstance("SHA-1"); 48 | digest.update(bytes); 49 | byte md[] = digest.digest(); 50 | return StringUtil.byte2Hex(md); 51 | } catch (NoSuchAlgorithmException e) { 52 | return ""; 53 | } 54 | } 55 | 56 | /** 57 | * Sha 1 string. 58 | * sha1加密通过输入流 59 | * 60 | * @param is the is 61 | * @return the string 62 | */ 63 | public static String SHA1(InputStream is) { 64 | byte[] dataBytes = new byte[1024]; 65 | int read; 66 | try { 67 | MessageDigest mdInst = MessageDigest.getInstance("SHA-1"); 68 | while ((read = is.read(dataBytes)) != -1) { 69 | mdInst.update(dataBytes, 0, read); 70 | } 71 | byte[] md = mdInst.digest(); 72 | return StringUtil.byte2Hex(md); 73 | } catch (Exception e) { 74 | return ""; 75 | } 76 | } 77 | 78 | /** 79 | * Sha 1 string. 80 | * sha1加密通过文件 81 | * 82 | * @param file the file 83 | * @return the string 84 | */ 85 | public static String SHA1(File file) { 86 | try { 87 | FileInputStream fis = new FileInputStream(file); 88 | return SHA1(fis); 89 | } catch (FileNotFoundException e) { 90 | return ""; 91 | } 92 | 93 | } 94 | 95 | /** 96 | * Sha 1 by path string. 97 | * sha1加密通过路径 98 | * 99 | * @param path the path 100 | * @return the string 101 | */ 102 | public static String SHA1ByPath(String path) { 103 | try { 104 | FileInputStream fis = new FileInputStream(path); 105 | return SHA1(fis); 106 | } catch (FileNotFoundException e) { 107 | return ""; 108 | } 109 | } 110 | 111 | /** 112 | * Sha 1 check boolean. 113 | * sha1检验通过字符串 114 | * 115 | * @param str the str 116 | * @param toBeCheckSum the to be check sum 117 | * @return the boolean 118 | */ 119 | public static boolean SHA1Check(String str, String toBeCheckSum) { 120 | return SHA1(str).equals(toBeCheckSum); 121 | } 122 | 123 | /** 124 | * Sha 1 check boolean. 125 | * sha1检验通过字节数组 126 | * 127 | * @param bytes the bytes 128 | * @param toBeCheckSum the to be check sum 129 | * @return the boolean 130 | */ 131 | public static boolean SHA1Check(byte[] bytes, String toBeCheckSum) { 132 | return SHA1(bytes).equals(toBeCheckSum); 133 | } 134 | 135 | /** 136 | * Sha 1 check boolean. 137 | * sha1检验通过输入流 138 | * 139 | * @param is the is 140 | * @param toBeCheckSum the to be check sum 141 | * @return the boolean 142 | */ 143 | public static boolean SHA1Check(InputStream is, String toBeCheckSum) { 144 | return SHA1(is).equals(toBeCheckSum); 145 | } 146 | 147 | /** 148 | * Sha 1 check boolean. 149 | * sha1检验通过文件 150 | * 151 | * @param file the file 152 | * @param toBeCheckSum the to be check sum 153 | * @return the boolean 154 | */ 155 | public static boolean SHA1Check(File file, String toBeCheckSum) { 156 | return SHA1(file).equals(toBeCheckSum); 157 | } 158 | 159 | /** 160 | * Sha 1 check boolean. 161 | * sha1检验通过文件路径 162 | * 163 | * @param path the path 164 | * @param toBeCheckSum the to be check sum 165 | * @return the boolean 166 | */ 167 | public static boolean SHA1CheckByPath(String path, String toBeCheckSum) { 168 | return SHA1ByPath(path).equals(toBeCheckSum); 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/base64/Base64.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a.cipher.base64; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.OutputStream; 6 | 7 | /** 8 | * Base64 加密解密工具类 9 | * Created by gyf on 2016/11/8. 10 | */ 11 | public class Base64 { 12 | 13 | /** 14 | * Instantiates a new Base 64. 15 | */ 16 | private Base64() { 17 | } 18 | 19 | static { 20 | encoder = new Base64Encoder(); 21 | decoder = new Base64Decoder(); 22 | } 23 | 24 | /** 25 | * The constant encoder. 26 | */ 27 | private static Base64Encoder encoder; 28 | /** 29 | * The constant decoder. 30 | */ 31 | private static Base64Decoder decoder; 32 | 33 | /** 34 | * base64加密 35 | * 36 | * @param str the str 37 | * @return the string 38 | */ 39 | public static String encode(String str) { 40 | return encoder.encode(str.getBytes()); 41 | } 42 | 43 | /** 44 | * base64加密 45 | * 46 | * @param bytes the bytes 47 | * @return the string 48 | */ 49 | public static String encode(byte[] bytes) { 50 | return encoder.encode(bytes); 51 | } 52 | 53 | /** 54 | * base64加密. 55 | * 56 | * @param bytes the bytes 57 | * @param out the out 58 | */ 59 | public static void encode(byte[] bytes, OutputStream out) { 60 | try { 61 | encoder.encode(bytes, out); 62 | } catch (IOException e) { 63 | e.printStackTrace(); 64 | } 65 | } 66 | 67 | /** 68 | * base64加密. 69 | * 70 | * @param str the str 71 | * @param out the out 72 | */ 73 | public static void encode(String str, OutputStream out) { 74 | try { 75 | encoder.encode(str.getBytes(), out); 76 | } catch (IOException e) { 77 | e.printStackTrace(); 78 | } 79 | } 80 | 81 | /** 82 | * 对输入流的加密 83 | * 84 | * @param in the in 85 | * @param out the out 86 | * @throws IOException the io exception 87 | */ 88 | public static void encode(InputStream in, OutputStream out) { 89 | try { 90 | encoder.encode(in, out); 91 | } catch (IOException e) { 92 | e.printStackTrace(); 93 | } 94 | } 95 | 96 | /** 97 | * base64解密 98 | * 99 | * @param str the str 100 | * @return the byte [ ] 101 | */ 102 | public static byte[] decode(String str) { 103 | try { 104 | return decoder.decodeBuffer(str); 105 | } catch (IOException e) { 106 | e.printStackTrace(); 107 | } 108 | return null; 109 | } 110 | 111 | /** 112 | * base64对输入流解密. 113 | * 114 | * @param in the in 115 | * @param out the out 116 | */ 117 | public static void decode(InputStream in, OutputStream out) { 118 | try { 119 | decoder.decodeBuffer(in, out); 120 | } catch (IOException e) { 121 | e.printStackTrace(); 122 | } 123 | } 124 | 125 | /** 126 | * base64对输入流解密. 127 | * 128 | * @param in the in 129 | * @return the byte [ ] 130 | */ 131 | public static byte[] decode(InputStream in) { 132 | try { 133 | return decoder.decodeBuffer(in); 134 | } catch (IOException e) { 135 | e.printStackTrace(); 136 | } 137 | return null; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/base64/Base64Decoder.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a.cipher.base64; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | import java.io.PushbackInputStream; 6 | 7 | /** 8 | * Created by gyf on 2016/11/14. 9 | */ 10 | 11 | public class Base64Decoder extends CharacterDecoder{ 12 | private static final char[] pem_array = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; 13 | private static final byte[] pem_convert_array = new byte[256]; 14 | byte[] decode_buffer = new byte[4]; 15 | 16 | public Base64Decoder() { 17 | } 18 | 19 | protected int bytesPerAtom() { 20 | return 4; 21 | } 22 | 23 | protected int bytesPerLine() { 24 | return 72; 25 | } 26 | 27 | protected void decodeAtom(PushbackInputStream var1, OutputStream var2, int var3) throws IOException { 28 | byte var5 = -1; 29 | byte var6 = -1; 30 | byte var7 = -1; 31 | byte var8 = -1; 32 | if(var3 < 2) { 33 | throw new IOException("Base64Decoder: Not enough bytes for an atom."); 34 | } else { 35 | int var4; 36 | do { 37 | var4 = var1.read(); 38 | if(var4 == -1) { 39 | throw new IOException(); 40 | } 41 | } while(var4 == 10 || var4 == 13); 42 | 43 | this.decode_buffer[0] = (byte)var4; 44 | var4 = this.readFully(var1, this.decode_buffer, 1, var3 - 1); 45 | if(var4 == -1) { 46 | throw new IOException(); 47 | } else { 48 | if(var3 > 3 && this.decode_buffer[3] == 61) { 49 | var3 = 3; 50 | } 51 | 52 | if(var3 > 2 && this.decode_buffer[2] == 61) { 53 | var3 = 2; 54 | } 55 | 56 | switch(var3) { 57 | case 4: 58 | var8 = pem_convert_array[this.decode_buffer[3] & 255]; 59 | case 3: 60 | var7 = pem_convert_array[this.decode_buffer[2] & 255]; 61 | case 2: 62 | var6 = pem_convert_array[this.decode_buffer[1] & 255]; 63 | var5 = pem_convert_array[this.decode_buffer[0] & 255]; 64 | default: 65 | switch(var3) { 66 | case 2: 67 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3)); 68 | break; 69 | case 3: 70 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3)); 71 | var2.write((byte)(var6 << 4 & 240 | var7 >>> 2 & 15)); 72 | break; 73 | case 4: 74 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3)); 75 | var2.write((byte)(var6 << 4 & 240 | var7 >>> 2 & 15)); 76 | var2.write((byte)(var7 << 6 & 192 | var8 & 63)); 77 | } 78 | 79 | } 80 | } 81 | } 82 | } 83 | 84 | static { 85 | int var0; 86 | for(var0 = 0; var0 < 255; ++var0) { 87 | pem_convert_array[var0] = -1; 88 | } 89 | 90 | for(var0 = 0; var0 < pem_array.length; ++var0) { 91 | pem_convert_array[pem_array[var0]] = (byte)var0; 92 | } 93 | 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/base64/Base64Encoder.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a.cipher.base64; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | 6 | /** 7 | * Created by gyf on 2016/11/14. 8 | */ 9 | 10 | public class Base64Encoder extends CharacterEncoder{ 11 | private static final char[] pem_array = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; 12 | 13 | public Base64Encoder() { 14 | } 15 | 16 | protected int bytesPerAtom() { 17 | return 3; 18 | } 19 | 20 | protected int bytesPerLine() { 21 | return 57; 22 | } 23 | 24 | protected void encodeAtom(OutputStream var1, byte[] var2, int var3, int var4) throws IOException { 25 | byte var5; 26 | if(var4 == 1) { 27 | var5 = var2[var3]; 28 | byte var6 = 0; 29 | boolean var7 = false; 30 | var1.write(pem_array[var5 >>> 2 & 63]); 31 | var1.write(pem_array[(var5 << 4 & 48) + (var6 >>> 4 & 15)]); 32 | var1.write(61); 33 | var1.write(61); 34 | } else { 35 | byte var8; 36 | if(var4 == 2) { 37 | var5 = var2[var3]; 38 | var8 = var2[var3 + 1]; 39 | byte var9 = 0; 40 | var1.write(pem_array[var5 >>> 2 & 63]); 41 | var1.write(pem_array[(var5 << 4 & 48) + (var8 >>> 4 & 15)]); 42 | var1.write(pem_array[(var8 << 2 & 60) + (var9 >>> 6 & 3)]); 43 | var1.write(61); 44 | } else { 45 | var5 = var2[var3]; 46 | var8 = var2[var3 + 1]; 47 | byte var10 = var2[var3 + 2]; 48 | var1.write(pem_array[var5 >>> 2 & 63]); 49 | var1.write(pem_array[(var5 << 4 & 48) + (var8 >>> 4 & 15)]); 50 | var1.write(pem_array[(var8 << 2 & 60) + (var10 >>> 6 & 3)]); 51 | var1.write(pem_array[var10 & 63]); 52 | } 53 | } 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/base64/CharacterDecoder.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a.cipher.base64; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.OutputStream; 8 | import java.io.PushbackInputStream; 9 | import java.nio.ByteBuffer; 10 | 11 | /** 12 | * Created by gyf on 2016/11/14. 13 | */ 14 | 15 | public abstract class CharacterDecoder { 16 | public CharacterDecoder() { 17 | } 18 | 19 | protected abstract int bytesPerAtom(); 20 | 21 | protected abstract int bytesPerLine(); 22 | 23 | protected void decodeBufferPrefix(PushbackInputStream var1, OutputStream var2) throws IOException { 24 | } 25 | 26 | protected void decodeBufferSuffix(PushbackInputStream var1, OutputStream var2) throws IOException { 27 | } 28 | 29 | protected int decodeLinePrefix(PushbackInputStream var1, OutputStream var2) throws IOException { 30 | return this.bytesPerLine(); 31 | } 32 | 33 | protected void decodeLineSuffix(PushbackInputStream var1, OutputStream var2) throws IOException { 34 | } 35 | 36 | protected void decodeAtom(PushbackInputStream var1, OutputStream var2, int var3) throws IOException { 37 | throw new IOException(); 38 | } 39 | 40 | protected int readFully(InputStream var1, byte[] var2, int var3, int var4) throws IOException { 41 | for(int var5 = 0; var5 < var4; ++var5) { 42 | int var6 = var1.read(); 43 | if(var6 == -1) { 44 | return var5 == 0?-1:var5; 45 | } 46 | 47 | var2[var5 + var3] = (byte)var6; 48 | } 49 | 50 | return var4; 51 | } 52 | 53 | public void decodeBuffer(InputStream var1, OutputStream var2) throws IOException { 54 | int var4 = 0; 55 | PushbackInputStream var5 = new PushbackInputStream(var1); 56 | this.decodeBufferPrefix(var5, var2); 57 | 58 | while(true) { 59 | try { 60 | int var6 = this.decodeLinePrefix(var5, var2); 61 | 62 | int var3; 63 | for(var3 = 0; var3 + this.bytesPerAtom() < var6; var3 += this.bytesPerAtom()) { 64 | this.decodeAtom(var5, var2, this.bytesPerAtom()); 65 | var4 += this.bytesPerAtom(); 66 | } 67 | 68 | if(var3 + this.bytesPerAtom() == var6) { 69 | this.decodeAtom(var5, var2, this.bytesPerAtom()); 70 | var4 += this.bytesPerAtom(); 71 | } else { 72 | this.decodeAtom(var5, var2, var6 - var3); 73 | var4 += var6 - var3; 74 | } 75 | 76 | this.decodeLineSuffix(var5, var2); 77 | } catch (IOException var8) { 78 | this.decodeBufferSuffix(var5, var2); 79 | return; 80 | } 81 | } 82 | } 83 | 84 | public byte[] decodeBuffer(String var1) throws IOException { 85 | byte[] var2 = new byte[var1.length()]; 86 | var1.getBytes(0, var1.length(), var2, 0); 87 | ByteArrayInputStream var3 = new ByteArrayInputStream(var2); 88 | ByteArrayOutputStream var4 = new ByteArrayOutputStream(); 89 | this.decodeBuffer(var3, var4); 90 | return var4.toByteArray(); 91 | } 92 | 93 | public byte[] decodeBuffer(InputStream var1) throws IOException { 94 | ByteArrayOutputStream var2 = new ByteArrayOutputStream(); 95 | this.decodeBuffer(var1, var2); 96 | return var2.toByteArray(); 97 | } 98 | 99 | public ByteBuffer decodeBufferToByteBuffer(String var1) throws IOException { 100 | return ByteBuffer.wrap(this.decodeBuffer(var1)); 101 | } 102 | 103 | public ByteBuffer decodeBufferToByteBuffer(InputStream var1) throws IOException { 104 | return ByteBuffer.wrap(this.decodeBuffer(var1)); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/base64/CharacterEncoder.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a.cipher.base64; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.OutputStream; 8 | import java.io.PrintStream; 9 | import java.nio.ByteBuffer; 10 | 11 | /** 12 | * Created by gyf on 2016/11/14. 13 | */ 14 | 15 | public abstract class CharacterEncoder { 16 | protected PrintStream pStream; 17 | 18 | public CharacterEncoder() { 19 | } 20 | 21 | protected abstract int bytesPerAtom(); 22 | 23 | protected abstract int bytesPerLine(); 24 | 25 | protected void encodeBufferPrefix(OutputStream var1) throws IOException { 26 | this.pStream = new PrintStream(var1); 27 | } 28 | 29 | protected void encodeBufferSuffix(OutputStream var1) throws IOException { 30 | } 31 | 32 | protected void encodeLinePrefix(OutputStream var1, int var2) throws IOException { 33 | } 34 | 35 | protected void encodeLineSuffix(OutputStream var1) throws IOException { 36 | this.pStream.println(); 37 | } 38 | 39 | protected abstract void encodeAtom(OutputStream var1, byte[] var2, int var3, int var4) throws IOException; 40 | 41 | protected int readFully(InputStream var1, byte[] var2) throws IOException { 42 | for(int var3 = 0; var3 < var2.length; ++var3) { 43 | int var4 = var1.read(); 44 | if(var4 == -1) { 45 | return var3; 46 | } 47 | 48 | var2[var3] = (byte)var4; 49 | } 50 | 51 | return var2.length; 52 | } 53 | 54 | public void encode(InputStream var1, OutputStream var2) throws IOException { 55 | byte[] var5 = new byte[this.bytesPerLine()]; 56 | this.encodeBufferPrefix(var2); 57 | 58 | while(true) { 59 | int var4 = this.readFully(var1, var5); 60 | if(var4 == 0) { 61 | break; 62 | } 63 | 64 | this.encodeLinePrefix(var2, var4); 65 | 66 | for(int var3 = 0; var3 < var4; var3 += this.bytesPerAtom()) { 67 | if(var3 + this.bytesPerAtom() <= var4) { 68 | this.encodeAtom(var2, var5, var3, this.bytesPerAtom()); 69 | } else { 70 | this.encodeAtom(var2, var5, var3, var4 - var3); 71 | } 72 | } 73 | 74 | if(var4 < this.bytesPerLine()) { 75 | break; 76 | } 77 | 78 | this.encodeLineSuffix(var2); 79 | } 80 | 81 | this.encodeBufferSuffix(var2); 82 | } 83 | 84 | public void encode(byte[] var1, OutputStream var2) throws IOException { 85 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1); 86 | this.encode((InputStream)var3, var2); 87 | } 88 | 89 | public String encode(byte[] var1) { 90 | ByteArrayOutputStream var2 = new ByteArrayOutputStream(); 91 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1); 92 | String var4 = null; 93 | 94 | try { 95 | this.encode((InputStream)var3, var2); 96 | var4 = var2.toString("8859_1"); 97 | return var4; 98 | } catch (Exception var6) { 99 | throw new Error("CharacterEncoder.encode internal error"); 100 | } 101 | } 102 | 103 | private byte[] getBytes(ByteBuffer var1) { 104 | byte[] var2 = null; 105 | if(var1.hasArray()) { 106 | byte[] var3 = var1.array(); 107 | if(var3.length == var1.capacity() && var3.length == var1.remaining()) { 108 | var2 = var3; 109 | var1.position(var1.limit()); 110 | } 111 | } 112 | 113 | if(var2 == null) { 114 | var2 = new byte[var1.remaining()]; 115 | var1.get(var2); 116 | } 117 | 118 | return var2; 119 | } 120 | 121 | public void encode(ByteBuffer var1, OutputStream var2) throws IOException { 122 | byte[] var3 = this.getBytes(var1); 123 | this.encode(var3, var2); 124 | } 125 | 126 | public String encode(ByteBuffer var1) { 127 | byte[] var2 = this.getBytes(var1); 128 | return this.encode(var2); 129 | } 130 | 131 | public void encodeBuffer(InputStream var1, OutputStream var2) throws IOException { 132 | byte[] var5 = new byte[this.bytesPerLine()]; 133 | this.encodeBufferPrefix(var2); 134 | 135 | int var4; 136 | do { 137 | var4 = this.readFully(var1, var5); 138 | if(var4 == 0) { 139 | break; 140 | } 141 | 142 | this.encodeLinePrefix(var2, var4); 143 | 144 | for(int var3 = 0; var3 < var4; var3 += this.bytesPerAtom()) { 145 | if(var3 + this.bytesPerAtom() <= var4) { 146 | this.encodeAtom(var2, var5, var3, this.bytesPerAtom()); 147 | } else { 148 | this.encodeAtom(var2, var5, var3, var4 - var3); 149 | } 150 | } 151 | 152 | this.encodeLineSuffix(var2); 153 | } while(var4 >= this.bytesPerLine()); 154 | 155 | this.encodeBufferSuffix(var2); 156 | } 157 | 158 | public void encodeBuffer(byte[] var1, OutputStream var2) throws IOException { 159 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1); 160 | this.encodeBuffer((InputStream)var3, var2); 161 | } 162 | 163 | public String encodeBuffer(byte[] var1) { 164 | ByteArrayOutputStream var2 = new ByteArrayOutputStream(); 165 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1); 166 | 167 | try { 168 | this.encodeBuffer((InputStream)var3, var2); 169 | } catch (Exception var5) { 170 | throw new Error("CharacterEncoder.encodeBuffer internal error"); 171 | } 172 | 173 | return var2.toString(); 174 | } 175 | 176 | public void encodeBuffer(ByteBuffer var1, OutputStream var2) throws IOException { 177 | byte[] var3 = this.getBytes(var1); 178 | this.encodeBuffer(var3, var2); 179 | } 180 | 181 | public String encodeBuffer(ByteBuffer var1) { 182 | byte[] var2 = this.getBytes(var1); 183 | return this.encodeBuffer(var2); 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /toolutils4a/src/main/java/com/gyf/toolutils4a/service/DownloadService.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a.service; 2 | 3 | import android.app.DownloadManager; 4 | import android.app.Service; 5 | import android.content.BroadcastReceiver; 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.content.IntentFilter; 9 | import android.database.Cursor; 10 | import android.net.Uri; 11 | import android.os.IBinder; 12 | 13 | import com.gyf.toolutils4a.AppUtils; 14 | import com.gyf.toolutils4a.L; 15 | 16 | public class DownloadService extends Service { 17 | 18 | private long mTaskId; 19 | private DownloadManager mDownloadManager; 20 | private String filePath; 21 | 22 | public DownloadService() { 23 | } 24 | 25 | @Override 26 | public void onCreate() { 27 | super.onCreate(); 28 | } 29 | 30 | @Override 31 | public int onStartCommand(Intent intent, int flags, int startId) { 32 | L.w("onStartCommand:" + intent.getStringExtra("fileurl")); 33 | String fileurl = intent.getStringExtra("fileurl"); 34 | downloadFile(fileurl); 35 | return super.onStartCommand(intent, flags, startId); 36 | } 37 | 38 | @Override 39 | public IBinder onBind(Intent intent) { 40 | return null; 41 | } 42 | 43 | private void downloadFile(String fileurl) { 44 | filePath = "/sdcard/Download/" + fileurl.substring(fileurl.lastIndexOf("/") + 1); 45 | DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileurl)); 46 | request.setDestinationInExternalPublicDir("/Download/", fileurl.substring(fileurl.lastIndexOf("/") + 1)); 47 | mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 48 | mTaskId = mDownloadManager.enqueue(request); 49 | registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 50 | } 51 | 52 | private BroadcastReceiver mReceiver = new BroadcastReceiver() { 53 | @Override 54 | public void onReceive(Context context, Intent intent) { 55 | checkDownloadStatus(); 56 | } 57 | }; 58 | 59 | private void checkDownloadStatus() { 60 | DownloadManager.Query query = new DownloadManager.Query(); 61 | query.setFilterById(mTaskId); 62 | Cursor c = mDownloadManager.query(query); 63 | if (c.moveToFirst()) { 64 | int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); 65 | switch (status) { 66 | /* case DownloadManager.STATUS_PAUSED: 67 | break; 68 | case DownloadManager.STATUS_FAILED: 69 | break; 70 | case DownloadManager.STATUS_PENDING: 71 | break; 72 | case DownloadManager.STATUS_RUNNING: 73 | break;*/ 74 | case DownloadManager.STATUS_SUCCESSFUL: 75 | AppUtils.installApk(this, filePath); 76 | break; 77 | } 78 | } 79 | 80 | 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /toolutils4a/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ToolUtils4a 3 | 无法跳转到微信,请检查您是否安装了微信! 4 | 无法跳转到支付宝,请检查您是否安装了支付宝! 5 | 6 | -------------------------------------------------------------------------------- /toolutils4a/src/test/java/com/gyf/toolutils4a/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.gyf.toolutils4a; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | int i = 0; 16 | while (i < 10000){ 17 | i++; 18 | System.out.println(StringUtil.randomFor6()); 19 | } 20 | 21 | //assertEquals(4, 2 + 2); 22 | } 23 | } -------------------------------------------------------------------------------- /toolutils4j/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /toolutils4j/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | 3 | dependencies { 4 | compile fileTree(include: ['*.jar'], dir: 'libs') 5 | } 6 | tasks.withType(JavaCompile) { 7 | options.encoding = "UTF-8" 8 | } 9 | sourceCompatibility = "1.7" 10 | targetCompatibility = "1.7" 11 | -------------------------------------------------------------------------------- /toolutils4j/src/main/java/com/gyf/cipher/Md5.java: -------------------------------------------------------------------------------- 1 | package com.gyf.cipher; 2 | 3 | import com.gyf.tool.StringUtil; 4 | 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.FileNotFoundException; 8 | import java.io.InputStream; 9 | import java.security.MessageDigest; 10 | import java.security.NoSuchAlgorithmException; 11 | 12 | /** 13 | * MD5 加密工具类 14 | * Created by gyf on 2016/11/14. 15 | */ 16 | public class Md5 { 17 | private Md5(){} 18 | /** 19 | * Md 5 string. 20 | * md5加密通过String 21 | * 22 | * @param str the str 23 | * @return the string 24 | */ 25 | public static String MD5(String str) { 26 | try { 27 | // 获得MD5摘要算法的 MessageDigest 对象 28 | MessageDigest mdInst = MessageDigest.getInstance("Md5"); 29 | // 使用指定的字节更新摘要 30 | mdInst.update(str.getBytes()); 31 | // 获得密文 32 | byte[] md = mdInst.digest(); 33 | // 字节数组转换为 十六进制 数并返回 34 | return StringUtil.byte2Hex(md); 35 | } catch (NoSuchAlgorithmException e) { 36 | return ""; 37 | } 38 | } 39 | 40 | /** 41 | * Md 5 string. 42 | * md5加密通过字节数组 43 | * 44 | * @param bytes the bytes 45 | * @return the string 46 | */ 47 | public static String MD5(byte[] bytes) { 48 | try { 49 | MessageDigest mdInst = MessageDigest.getInstance("Md5"); 50 | mdInst.update(bytes); 51 | byte[] md = mdInst.digest(); 52 | return StringUtil.byte2Hex(md); 53 | } catch (NoSuchAlgorithmException e) { 54 | return ""; 55 | } 56 | } 57 | 58 | /** 59 | * Md 5 string. 60 | * md5加密通过输入流 61 | * 62 | * @param is the is 63 | * @return the string 64 | */ 65 | public static String MD5(InputStream is) { 66 | byte[] dataBytes = new byte[1024]; 67 | int read; 68 | try { 69 | MessageDigest mdInst = MessageDigest.getInstance("Md5"); 70 | while ((read = is.read(dataBytes)) != -1) { 71 | mdInst.update(dataBytes, 0, read); 72 | } 73 | byte[] md = mdInst.digest(); 74 | return StringUtil.byte2Hex(md); 75 | } catch (Exception e) { 76 | return ""; 77 | } 78 | } 79 | 80 | /** 81 | * Md 5 string. 82 | * md5加密通过文件 83 | * 84 | * @param file the file 85 | * @return the string 86 | */ 87 | public static String MD5(File file) { 88 | try { 89 | FileInputStream fis = new FileInputStream(file); 90 | return MD5(fis); 91 | } catch (FileNotFoundException e) { 92 | return ""; 93 | } 94 | 95 | } 96 | 97 | /** 98 | * Md 5 by path string. 99 | * md5加密通过文件路径 100 | * 101 | * @param path the path 102 | * @return the string 103 | */ 104 | public static String MD5ByPath(String path) { 105 | try { 106 | FileInputStream fis = new FileInputStream(path); 107 | return MD5(fis); 108 | } catch (FileNotFoundException e) { 109 | return ""; 110 | } 111 | } 112 | 113 | 114 | /** 115 | * Md 5 check boolean. 116 | * md5检验通过字符串 117 | * 118 | * @param str the str 119 | * @param toBeCheckSum the to be check sum 120 | * @return the boolean 121 | */ 122 | public static boolean MD5Check(String str, String toBeCheckSum) { 123 | return MD5(str).equals(toBeCheckSum); 124 | } 125 | 126 | /** 127 | * Md 5 check boolean. 128 | * md5检验通过字节数组 129 | * 130 | * @param bytes the bytes 131 | * @param toBeCheckSum the to be check sum 132 | * @return the boolean 133 | */ 134 | public static boolean MD5Check(byte[] bytes, String toBeCheckSum) { 135 | return MD5(bytes).equals(toBeCheckSum); 136 | } 137 | 138 | /** 139 | * Md 5 check boolean. 140 | * md5检验通过输入流 141 | * 142 | * @param is the is 143 | * @param toBeCheckSum the to be check sum 144 | * @return the boolean 145 | */ 146 | public static boolean MD5Check(InputStream is, String toBeCheckSum) { 147 | return MD5(is).equals(toBeCheckSum); 148 | } 149 | 150 | /** 151 | * Md 5 check boolean. 152 | * md5检验通过文件 153 | * 154 | * @param file the file 155 | * @param toBeCheckSum the to be check sum 156 | * @return the boolean 157 | */ 158 | public static boolean MD5Check(File file, String toBeCheckSum) { 159 | return MD5(file).equals(toBeCheckSum); 160 | } 161 | 162 | /** 163 | * Md 5 check boolean. 164 | * md5检验通过文件路径 165 | * 166 | * @param path the path 167 | * @param toBeCheckSum the to be check sum 168 | * @return the boolean 169 | */ 170 | public static boolean MD5CheckByPath(String path, String toBeCheckSum) { 171 | return MD5ByPath(path).equals(toBeCheckSum); 172 | } 173 | 174 | } 175 | -------------------------------------------------------------------------------- /toolutils4j/src/main/java/com/gyf/cipher/RSA.java: -------------------------------------------------------------------------------- 1 | package com.gyf.cipher; 2 | 3 | 4 | import com.gyf.cipher.base64.Base64; 5 | 6 | import javax.crypto.BadPaddingException; 7 | import javax.crypto.Cipher; 8 | import javax.crypto.IllegalBlockSizeException; 9 | import javax.crypto.NoSuchPaddingException; 10 | 11 | import java.io.*; 12 | import java.security.*; 13 | import java.security.interfaces.RSAPrivateKey; 14 | import java.security.interfaces.RSAPublicKey; 15 | import java.security.spec.InvalidKeySpecException; 16 | import java.security.spec.PKCS8EncodedKeySpec; 17 | import java.security.spec.X509EncodedKeySpec; 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | 21 | 22 | /** 23 | * RSA 加密解密工具类 24 | * Created by gyf on 2016/11/14. 25 | */ 26 | public class RSA { 27 | 28 | private RSA(){} 29 | /** 30 | * 加密算法RSA 31 | */ 32 | public static final String KEY_ALGORITHM = "RSA"; 33 | 34 | /** 35 | * 字节数据转字符串专用集合 36 | */ 37 | public static final String MD5_SIGN = "MD5WithRSA"; 38 | public static final String SHA1_SIGN = "SHA1WithRSA"; 39 | 40 | /** 41 | * 存储名称 42 | */ 43 | public static final String PUBLIC_KEY_PATH = "/publicKey.RSA"; 44 | public static final String PRIVATE_KEY_PATH = "/privateKey.RSA"; 45 | 46 | /** 47 | * 公钥的key 48 | */ 49 | private static final String PUBLIC_KEY = "RSAPublicKey"; 50 | 51 | /** 52 | * 私钥的key 53 | */ 54 | private static final String PRIVATE_KEY = "RSAPrivateKey"; 55 | 56 | /** 57 | * 生成秘钥对 58 | * 59 | * @return the map 60 | * @throws Exception the exception 61 | */ 62 | public static Map genKeyPair() throws Exception { 63 | KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); 64 | keyPairGen.initialize(1024, new SecureRandom()); 65 | KeyPair keyPair = keyPairGen.generateKeyPair(); 66 | RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); 67 | RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); 68 | Map keyMap = new HashMap<>(); 69 | keyMap.put(PUBLIC_KEY, publicKey); 70 | keyMap.put(PRIVATE_KEY, privateKey); 71 | return keyMap; 72 | } 73 | 74 | /** 75 | * 生成秘钥对 76 | * 77 | * @param filePath 指定存储路径 78 | * @throws NoSuchAlgorithmException the no such algorithm exception 79 | */ 80 | public static void genKeyPair(String filePath) throws Exception { 81 | // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象 82 | KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); 83 | // 初始化密钥对生成器,密钥大小为96-1024位 84 | keyPairGen.initialize(1024, new SecureRandom()); 85 | // 生成一个密钥对,保存在keyPair中 86 | KeyPair keyPair = keyPairGen.generateKeyPair(); 87 | // 得到私钥 88 | RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); 89 | // 得到公钥 90 | RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); 91 | try { 92 | // 得到公钥字符串 93 | String publicKeyString = Base64.encode(publicKey.getEncoded()); 94 | // 得到私钥字符串 95 | String privateKeyString = Base64.encode(privateKey.getEncoded()); 96 | 97 | // 将密钥对写入到文件 98 | FileWriter pubfw = new FileWriter(filePath + PUBLIC_KEY_PATH); 99 | FileWriter prifw = new FileWriter(filePath + PRIVATE_KEY_PATH); 100 | BufferedWriter pubbw = new BufferedWriter(pubfw); 101 | BufferedWriter pribw = new BufferedWriter(prifw); 102 | pubbw.write(publicKeyString); 103 | pribw.write(privateKeyString); 104 | pubbw.flush(); 105 | pubbw.close(); 106 | pubfw.close(); 107 | pribw.flush(); 108 | pribw.close(); 109 | prifw.close(); 110 | } catch (Exception e) { 111 | e.printStackTrace(); 112 | } 113 | } 114 | 115 | /** 116 | * 从文件中输入流中加载公钥 117 | * 118 | * @param path 地址 119 | * @return 公钥字符串 string 120 | * @throws Exception 加载公钥时产生的异常 121 | */ 122 | public static String loadPublicKeyByFile(String path) throws Exception { 123 | try { 124 | BufferedReader br = new BufferedReader(new FileReader(path + PUBLIC_KEY_PATH)); 125 | String readLine = null; 126 | StringBuilder sb = new StringBuilder(); 127 | while ((readLine = br.readLine()) != null) { 128 | sb.append(readLine); 129 | } 130 | br.close(); 131 | return sb.toString(); 132 | } catch (IOException e) { 133 | throw new Exception("公钥数据流读取错误"); 134 | } catch (NullPointerException e) { 135 | throw new Exception("公钥输入流为空"); 136 | } 137 | } 138 | 139 | /** 140 | * 从字符串中加载公钥 141 | * 142 | * @param publicKeyStr 公钥数据字符串 143 | * @return the rsa public key 144 | * @throws Exception 加载公钥时产生的异常 145 | */ 146 | public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) 147 | throws Exception { 148 | try { 149 | byte[] buffer = Base64.decode(publicKeyStr); 150 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); 151 | X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); 152 | return (RSAPublicKey) keyFactory.generatePublic(keySpec); 153 | } catch (NoSuchAlgorithmException e) { 154 | throw new Exception("无此算法"); 155 | } catch (InvalidKeySpecException e) { 156 | throw new Exception("公钥非法"); 157 | } catch (NullPointerException e) { 158 | throw new Exception("公钥数据为空"); 159 | } 160 | } 161 | 162 | /** 163 | * 从文件中加载私钥 164 | * 165 | * @param path 地址 166 | * @return 私钥字符串 string 167 | * @throws Exception the exception 168 | */ 169 | public static String loadPrivateKeyByFile(String path) throws Exception { 170 | try { 171 | BufferedReader br = new BufferedReader(new FileReader(path + PRIVATE_KEY_PATH)); 172 | String readLine; 173 | StringBuilder sb = new StringBuilder(); 174 | while ((readLine = br.readLine()) != null) { 175 | sb.append(readLine); 176 | } 177 | br.close(); 178 | return sb.toString(); 179 | } catch (IOException e) { 180 | throw new Exception("私钥数据读取错误"); 181 | } catch (NullPointerException e) { 182 | throw new Exception("私钥输入流为空"); 183 | } 184 | } 185 | 186 | /** 187 | * 从字符串中加载私钥 188 | * 189 | * @param privateKeyStr 私钥数据字符串 190 | * @return the rsa private key 191 | * @throws Exception 加载公钥时产生的异常 192 | */ 193 | public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws Exception { 194 | try { 195 | byte[] buffer = Base64.decode(privateKeyStr); 196 | PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer); 197 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); 198 | return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); 199 | } catch (NoSuchAlgorithmException e) { 200 | throw new Exception("无此算法"); 201 | } catch (InvalidKeySpecException e) { 202 | throw new Exception("私钥非法"); 203 | } catch (NullPointerException e) { 204 | throw new Exception("私钥数据为空"); 205 | } 206 | } 207 | 208 | /** 209 | * 公钥加密过程 210 | * 211 | * @param publicKey 公钥 212 | * @param plainTextData 明文数据 213 | * @return 密文字节数组 byte [ ] 214 | * @throws Exception 加密过程中的异常信息 215 | */ 216 | public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception { 217 | if (publicKey == null) { 218 | throw new Exception("加密公钥为空, 请设置"); 219 | } 220 | Cipher cipher = null; 221 | try { 222 | // 使用默认RSA 223 | cipher = Cipher.getInstance(KEY_ALGORITHM); 224 | // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 225 | cipher.init(Cipher.ENCRYPT_MODE, publicKey); 226 | byte[] output = cipher.doFinal(plainTextData); 227 | return output; 228 | } catch (NoSuchAlgorithmException e) { 229 | throw new Exception("无此加密算法"); 230 | } catch (NoSuchPaddingException e) { 231 | e.printStackTrace(); 232 | return null; 233 | } catch (InvalidKeyException e) { 234 | throw new Exception("加密公钥非法,请检查"); 235 | } catch (IllegalBlockSizeException e) { 236 | throw new Exception("明文长度非法"); 237 | } catch (BadPaddingException e) { 238 | throw new Exception("明文数据已损坏"); 239 | } 240 | } 241 | 242 | /** 243 | * 私钥加密过程 244 | * 245 | * @param privateKey 私钥 246 | * @param plainTextData 明文数据 247 | * @return 密文字节数组 byte [ ] 248 | * @throws Exception 加密过程中的异常信息 249 | */ 250 | public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) 251 | throws Exception { 252 | if (privateKey == null) { 253 | throw new Exception("加密私钥为空, 请设置"); 254 | } 255 | Cipher cipher = null; 256 | try { 257 | // 使用默认RSA 258 | cipher = Cipher.getInstance(KEY_ALGORITHM); 259 | cipher.init(Cipher.ENCRYPT_MODE, privateKey); 260 | byte[] output = cipher.doFinal(plainTextData); 261 | return output; 262 | } catch (NoSuchAlgorithmException e) { 263 | throw new Exception("无此加密算法"); 264 | } catch (NoSuchPaddingException e) { 265 | e.printStackTrace(); 266 | return null; 267 | } catch (InvalidKeyException e) { 268 | throw new Exception("加密私钥非法,请检查"); 269 | } catch (IllegalBlockSizeException e) { 270 | throw new Exception("明文长度非法"); 271 | } catch (BadPaddingException e) { 272 | throw new Exception("明文数据已损坏"); 273 | } 274 | } 275 | 276 | /** 277 | * 私钥解密过程 278 | * 279 | * @param privateKey 私钥 280 | * @param cipherData 密文数据 281 | * @return 明文 byte [ ] 282 | * @throws Exception 解密过程中的异常信息 283 | */ 284 | public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) 285 | throws Exception { 286 | if (privateKey == null) { 287 | throw new Exception("解密私钥为空, 请设置"); 288 | } 289 | Cipher cipher = null; 290 | try { 291 | // 使用默认RSA 292 | cipher = Cipher.getInstance(KEY_ALGORITHM); 293 | // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 294 | cipher.init(Cipher.DECRYPT_MODE, privateKey); 295 | byte[] output = cipher.doFinal(cipherData); 296 | return output; 297 | } catch (NoSuchAlgorithmException e) { 298 | throw new Exception("无此解密算法"); 299 | } catch (NoSuchPaddingException e) { 300 | e.printStackTrace(); 301 | return null; 302 | } catch (InvalidKeyException e) { 303 | throw new Exception("解密私钥非法,请检查"); 304 | } catch (IllegalBlockSizeException e) { 305 | throw new Exception("密文长度非法"); 306 | } catch (BadPaddingException e) { 307 | throw new Exception("密文数据已损坏"); 308 | } 309 | } 310 | 311 | /** 312 | * 公钥解密过程 313 | * 314 | * @param publicKey 公钥 315 | * @param cipherData 密文数据 316 | * @return 明文 byte [ ] 317 | * @throws Exception 解密过程中的异常信息 318 | */ 319 | public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) 320 | throws Exception { 321 | if (publicKey == null) { 322 | throw new Exception("解密公钥为空, 请设置"); 323 | } 324 | Cipher cipher = null; 325 | try { 326 | // 使用默认RSA 327 | cipher = Cipher.getInstance(KEY_ALGORITHM); 328 | // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 329 | cipher.init(Cipher.DECRYPT_MODE, publicKey); 330 | byte[] output = cipher.doFinal(cipherData); 331 | return output; 332 | } catch (NoSuchAlgorithmException e) { 333 | throw new Exception("无此解密算法"); 334 | } catch (NoSuchPaddingException e) { 335 | e.printStackTrace(); 336 | return null; 337 | } catch (InvalidKeyException e) { 338 | throw new Exception("解密公钥非法,请检查"); 339 | } catch (IllegalBlockSizeException e) { 340 | throw new Exception("密文长度非法"); 341 | } catch (BadPaddingException e) { 342 | throw new Exception("密文数据已损坏"); 343 | } 344 | } 345 | 346 | /** 347 | * 私钥签名 348 | * 349 | * @param rsaPrivateKey 私钥 350 | * @param cipherData 待签名加密后的数据 351 | * @return 签名后的byte[] 352 | * @throws Exception 签名过程中的异常信息 353 | */ 354 | public static byte[] sign(RSAPrivateKey rsaPrivateKey, byte[] cipherData) throws Exception { 355 | try { 356 | Signature signature = Signature.getInstance(MD5_SIGN); 357 | signature.initSign(rsaPrivateKey); 358 | signature.update(cipherData); 359 | byte[] output = signature.sign(); 360 | return output; 361 | } catch (NoSuchAlgorithmException e) { 362 | throw new Exception("无此解密算法"); 363 | } catch (InvalidKeyException e) { 364 | throw new Exception("解密非法,请检查"); 365 | } catch (SignatureException e) { 366 | throw new Exception("签名异常"); 367 | } 368 | } 369 | 370 | /** 371 | * 私钥签名 372 | * 373 | * @param privateKey 私钥字符串 374 | * @param cipherData 加密后的数据 375 | * @return 签名后的byte[] 376 | * @throws Exception 签名过程中的异常信息 377 | */ 378 | public static byte[] sign(String privateKey, byte[] cipherData) throws Exception { 379 | return sign(loadPrivateKeyByStr(privateKey), cipherData); 380 | } 381 | 382 | /** 383 | * 公钥验签 384 | * 385 | * @param rsaPublicKey 公钥 386 | * @param cipherData 加密后的数据 387 | * @param sign 签名后的数据(base64加密) 388 | * @return the boolean 389 | * @throws Exception the exception 390 | */ 391 | public static boolean verify(RSAPublicKey rsaPublicKey, byte[] cipherData, String sign) throws Exception { 392 | try { 393 | Signature signature = Signature.getInstance(MD5_SIGN); 394 | signature.initVerify(rsaPublicKey); 395 | signature.update(cipherData); 396 | return signature.verify(Base64.decode(sign)); 397 | } catch (NoSuchAlgorithmException e) { 398 | throw new Exception("无此解密算法"); 399 | } catch (InvalidKeyException e) { 400 | throw new Exception("解密非法,请检查"); 401 | } catch (SignatureException e) { 402 | throw new Exception("签名异常"); 403 | } 404 | } 405 | 406 | /** 407 | * 公钥验签 408 | * 409 | * @param publicKey 公钥字符串 410 | * @param cipherData 加密后的数据 411 | * @param sign 签名后的数据(base64加密) 412 | * @return the boolean 413 | * @throws Exception the exception 414 | */ 415 | public static boolean verify(String publicKey, byte[] cipherData, String sign) throws Exception { 416 | return verify(loadPublicKeyByStr(publicKey), cipherData, sign); 417 | } 418 | 419 | /** 420 | * 获取私钥 421 | * 422 | * @param keyMap 密钥对 423 | * @return string 424 | */ 425 | public static String getPrivateKey(Map keyMap) { 426 | Key key = (Key) keyMap.get(PRIVATE_KEY); 427 | return Base64.encode(key.getEncoded()); 428 | } 429 | 430 | /** 431 | * 获取公钥 432 | * 433 | * @param keyMap 密钥对 434 | * @return string 435 | */ 436 | public static String getPublicKey(Map keyMap) { 437 | Key key = (Key) keyMap.get(PUBLIC_KEY); 438 | return Base64.encode(key.getEncoded()); 439 | } 440 | } 441 | -------------------------------------------------------------------------------- /toolutils4j/src/main/java/com/gyf/cipher/Sha1.java: -------------------------------------------------------------------------------- 1 | package com.gyf.cipher; 2 | 3 | import com.gyf.tool.StringUtil; 4 | 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.FileNotFoundException; 8 | import java.io.InputStream; 9 | import java.security.MessageDigest; 10 | import java.security.NoSuchAlgorithmException; 11 | 12 | /** 13 | * SHA1 加密工具类 14 | * Created by gyf on 2016/11/14. 15 | */ 16 | public class Sha1 { 17 | 18 | private Sha1(){} 19 | /** 20 | * Sha 1 string. 21 | * sha1加密通过字符串 22 | * 23 | * @param str the str 24 | * @return the string 25 | */ 26 | public static String SHA1(String str) { 27 | try { 28 | MessageDigest digest = MessageDigest.getInstance("SHA-1"); 29 | digest.update(str.getBytes()); 30 | byte md[] = digest.digest(); 31 | return StringUtil.byte2Hex(md); 32 | 33 | } catch (NoSuchAlgorithmException e) { 34 | return ""; 35 | } 36 | } 37 | 38 | /** 39 | * Sha 1 string. 40 | * sha1加密通过字节数组 41 | * 42 | * @param bytes the bytes 43 | * @return the string 44 | */ 45 | public static String SHA1(byte[] bytes) { 46 | try { 47 | MessageDigest digest = MessageDigest.getInstance("SHA-1"); 48 | digest.update(bytes); 49 | byte md[] = digest.digest(); 50 | return StringUtil.byte2Hex(md); 51 | } catch (NoSuchAlgorithmException e) { 52 | return ""; 53 | } 54 | } 55 | 56 | /** 57 | * Sha 1 string. 58 | * sha1加密通过输入流 59 | * 60 | * @param is the is 61 | * @return the string 62 | */ 63 | public static String SHA1(InputStream is) { 64 | byte[] dataBytes = new byte[1024]; 65 | int read; 66 | try { 67 | MessageDigest mdInst = MessageDigest.getInstance("SHA-1"); 68 | while ((read = is.read(dataBytes)) != -1) { 69 | mdInst.update(dataBytes, 0, read); 70 | } 71 | byte[] md = mdInst.digest(); 72 | return StringUtil.byte2Hex(md); 73 | } catch (Exception e) { 74 | return ""; 75 | } 76 | } 77 | 78 | /** 79 | * Sha 1 string. 80 | * sha1加密通过文件 81 | * 82 | * @param file the file 83 | * @return the string 84 | */ 85 | public static String SHA1(File file) { 86 | try { 87 | FileInputStream fis = new FileInputStream(file); 88 | return SHA1(fis); 89 | } catch (FileNotFoundException e) { 90 | return ""; 91 | } 92 | 93 | } 94 | 95 | /** 96 | * Sha 1 by path string. 97 | * sha1加密通过路径 98 | * 99 | * @param path the path 100 | * @return the string 101 | */ 102 | public static String SHA1ByPath(String path) { 103 | try { 104 | FileInputStream fis = new FileInputStream(path); 105 | return SHA1(fis); 106 | } catch (FileNotFoundException e) { 107 | return ""; 108 | } 109 | } 110 | 111 | /** 112 | * Sha 1 check boolean. 113 | * sha1检验通过字符串 114 | * 115 | * @param str the str 116 | * @param toBeCheckSum the to be check sum 117 | * @return the boolean 118 | */ 119 | public static boolean SHA1Check(String str, String toBeCheckSum) { 120 | return SHA1(str).equals(toBeCheckSum); 121 | } 122 | 123 | /** 124 | * Sha 1 check boolean. 125 | * sha1检验通过字节数组 126 | * 127 | * @param bytes the bytes 128 | * @param toBeCheckSum the to be check sum 129 | * @return the boolean 130 | */ 131 | public static boolean SHA1Check(byte[] bytes, String toBeCheckSum) { 132 | return SHA1(bytes).equals(toBeCheckSum); 133 | } 134 | 135 | /** 136 | * Sha 1 check boolean. 137 | * sha1检验通过输入流 138 | * 139 | * @param is the is 140 | * @param toBeCheckSum the to be check sum 141 | * @return the boolean 142 | */ 143 | public static boolean SHA1Check(InputStream is, String toBeCheckSum) { 144 | return SHA1(is).equals(toBeCheckSum); 145 | } 146 | 147 | /** 148 | * Sha 1 check boolean. 149 | * sha1检验通过文件 150 | * 151 | * @param file the file 152 | * @param toBeCheckSum the to be check sum 153 | * @return the boolean 154 | */ 155 | public static boolean SHA1Check(File file, String toBeCheckSum) { 156 | return SHA1(file).equals(toBeCheckSum); 157 | } 158 | 159 | /** 160 | * Sha 1 check boolean. 161 | * sha1检验通过文件路径 162 | * 163 | * @param path the path 164 | * @param toBeCheckSum the to be check sum 165 | * @return the boolean 166 | */ 167 | public static boolean SHA1CheckByPath(String path, String toBeCheckSum) { 168 | return SHA1ByPath(path).equals(toBeCheckSum); 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /toolutils4j/src/main/java/com/gyf/cipher/base64/Base64.java: -------------------------------------------------------------------------------- 1 | package com.gyf.cipher.base64; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.OutputStream; 6 | 7 | /** 8 | * Base64 加密解密工具类 9 | * Created by gyf on 2016/11/8. 10 | */ 11 | public class Base64 { 12 | 13 | /** 14 | * Instantiates a new Base 64. 15 | */ 16 | private Base64() { 17 | } 18 | 19 | static { 20 | encoder = new Base64Encoder(); 21 | decoder = new Base64Decoder(); 22 | } 23 | 24 | /** 25 | * The constant encoder. 26 | */ 27 | private static Base64Encoder encoder; 28 | /** 29 | * The constant decoder. 30 | */ 31 | private static Base64Decoder decoder; 32 | 33 | /** 34 | * base64加密 35 | * 36 | * @param str the str 37 | * @return the string 38 | */ 39 | public static String encode(String str) { 40 | return encoder.encode(str.getBytes()); 41 | } 42 | 43 | /** 44 | * base64加密 45 | * 46 | * @param bytes the bytes 47 | * @return the string 48 | */ 49 | public static String encode(byte[] bytes) { 50 | return encoder.encode(bytes); 51 | } 52 | 53 | /** 54 | * base64加密. 55 | * 56 | * @param bytes the bytes 57 | * @param out the out 58 | */ 59 | public static void encode(byte[] bytes, OutputStream out) { 60 | try { 61 | encoder.encode(bytes, out); 62 | } catch (IOException e) { 63 | e.printStackTrace(); 64 | } 65 | } 66 | 67 | /** 68 | * base64加密. 69 | * 70 | * @param str the str 71 | * @param out the out 72 | */ 73 | public static void encode(String str, OutputStream out) { 74 | try { 75 | encoder.encode(str.getBytes(), out); 76 | } catch (IOException e) { 77 | e.printStackTrace(); 78 | } 79 | } 80 | 81 | /** 82 | * 对输入流的加密 83 | * 84 | * @param in the in 85 | * @param out the out 86 | * @throws IOException the io exception 87 | */ 88 | public static void encode(InputStream in, OutputStream out) { 89 | try { 90 | encoder.encode(in, out); 91 | } catch (IOException e) { 92 | e.printStackTrace(); 93 | } 94 | } 95 | 96 | /** 97 | * base64解密 98 | * 99 | * @param str the str 100 | * @return the byte [ ] 101 | */ 102 | public static byte[] decode(String str) { 103 | try { 104 | return decoder.decodeBuffer(str); 105 | } catch (IOException e) { 106 | e.printStackTrace(); 107 | } 108 | return null; 109 | } 110 | 111 | /** 112 | * base64对输入流解密. 113 | * 114 | * @param in the in 115 | * @param out the out 116 | */ 117 | public static void decode(InputStream in, OutputStream out) { 118 | try { 119 | decoder.decodeBuffer(in, out); 120 | } catch (IOException e) { 121 | e.printStackTrace(); 122 | } 123 | } 124 | 125 | /** 126 | * base64对输入流解密. 127 | * 128 | * @param in the in 129 | * @return the byte [ ] 130 | */ 131 | public static byte[] decode(InputStream in) { 132 | try { 133 | return decoder.decodeBuffer(in); 134 | } catch (IOException e) { 135 | e.printStackTrace(); 136 | } 137 | return null; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /toolutils4j/src/main/java/com/gyf/cipher/base64/Base64Decoder.java: -------------------------------------------------------------------------------- 1 | package com.gyf.cipher.base64; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | import java.io.PushbackInputStream; 6 | 7 | /** 8 | * Created by gyf on 2016/11/14. 9 | */ 10 | 11 | public class Base64Decoder extends CharacterDecoder{ 12 | private static final char[] pem_array = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; 13 | private static final byte[] pem_convert_array = new byte[256]; 14 | byte[] decode_buffer = new byte[4]; 15 | 16 | public Base64Decoder() { 17 | } 18 | 19 | protected int bytesPerAtom() { 20 | return 4; 21 | } 22 | 23 | protected int bytesPerLine() { 24 | return 72; 25 | } 26 | 27 | protected void decodeAtom(PushbackInputStream var1, OutputStream var2, int var3) throws IOException { 28 | byte var5 = -1; 29 | byte var6 = -1; 30 | byte var7 = -1; 31 | byte var8 = -1; 32 | if(var3 < 2) { 33 | throw new IOException("Base64Decoder: Not enough bytes for an atom."); 34 | } else { 35 | int var4; 36 | do { 37 | var4 = var1.read(); 38 | if(var4 == -1) { 39 | throw new IOException(); 40 | } 41 | } while(var4 == 10 || var4 == 13); 42 | 43 | this.decode_buffer[0] = (byte)var4; 44 | var4 = this.readFully(var1, this.decode_buffer, 1, var3 - 1); 45 | if(var4 == -1) { 46 | throw new IOException(); 47 | } else { 48 | if(var3 > 3 && this.decode_buffer[3] == 61) { 49 | var3 = 3; 50 | } 51 | 52 | if(var3 > 2 && this.decode_buffer[2] == 61) { 53 | var3 = 2; 54 | } 55 | 56 | switch(var3) { 57 | case 4: 58 | var8 = pem_convert_array[this.decode_buffer[3] & 255]; 59 | case 3: 60 | var7 = pem_convert_array[this.decode_buffer[2] & 255]; 61 | case 2: 62 | var6 = pem_convert_array[this.decode_buffer[1] & 255]; 63 | var5 = pem_convert_array[this.decode_buffer[0] & 255]; 64 | default: 65 | switch(var3) { 66 | case 2: 67 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3)); 68 | break; 69 | case 3: 70 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3)); 71 | var2.write((byte)(var6 << 4 & 240 | var7 >>> 2 & 15)); 72 | break; 73 | case 4: 74 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3)); 75 | var2.write((byte)(var6 << 4 & 240 | var7 >>> 2 & 15)); 76 | var2.write((byte)(var7 << 6 & 192 | var8 & 63)); 77 | } 78 | 79 | } 80 | } 81 | } 82 | } 83 | 84 | static { 85 | int var0; 86 | for(var0 = 0; var0 < 255; ++var0) { 87 | pem_convert_array[var0] = -1; 88 | } 89 | 90 | for(var0 = 0; var0 < pem_array.length; ++var0) { 91 | pem_convert_array[pem_array[var0]] = (byte)var0; 92 | } 93 | 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /toolutils4j/src/main/java/com/gyf/cipher/base64/Base64Encoder.java: -------------------------------------------------------------------------------- 1 | package com.gyf.cipher.base64; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | 6 | /** 7 | * Created by gyf on 2016/11/14. 8 | */ 9 | 10 | public class Base64Encoder extends CharacterEncoder{ 11 | private static final char[] pem_array = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; 12 | 13 | public Base64Encoder() { 14 | } 15 | 16 | protected int bytesPerAtom() { 17 | return 3; 18 | } 19 | 20 | protected int bytesPerLine() { 21 | return 57; 22 | } 23 | 24 | protected void encodeAtom(OutputStream var1, byte[] var2, int var3, int var4) throws IOException { 25 | byte var5; 26 | if(var4 == 1) { 27 | var5 = var2[var3]; 28 | byte var6 = 0; 29 | boolean var7 = false; 30 | var1.write(pem_array[var5 >>> 2 & 63]); 31 | var1.write(pem_array[(var5 << 4 & 48) + (var6 >>> 4 & 15)]); 32 | var1.write(61); 33 | var1.write(61); 34 | } else { 35 | byte var8; 36 | if(var4 == 2) { 37 | var5 = var2[var3]; 38 | var8 = var2[var3 + 1]; 39 | byte var9 = 0; 40 | var1.write(pem_array[var5 >>> 2 & 63]); 41 | var1.write(pem_array[(var5 << 4 & 48) + (var8 >>> 4 & 15)]); 42 | var1.write(pem_array[(var8 << 2 & 60) + (var9 >>> 6 & 3)]); 43 | var1.write(61); 44 | } else { 45 | var5 = var2[var3]; 46 | var8 = var2[var3 + 1]; 47 | byte var10 = var2[var3 + 2]; 48 | var1.write(pem_array[var5 >>> 2 & 63]); 49 | var1.write(pem_array[(var5 << 4 & 48) + (var8 >>> 4 & 15)]); 50 | var1.write(pem_array[(var8 << 2 & 60) + (var10 >>> 6 & 3)]); 51 | var1.write(pem_array[var10 & 63]); 52 | } 53 | } 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /toolutils4j/src/main/java/com/gyf/cipher/base64/CharacterDecoder.java: -------------------------------------------------------------------------------- 1 | package com.gyf.cipher.base64; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.OutputStream; 8 | import java.io.PushbackInputStream; 9 | import java.nio.ByteBuffer; 10 | 11 | /** 12 | * Created by gyf on 2016/11/14. 13 | */ 14 | 15 | public abstract class CharacterDecoder { 16 | public CharacterDecoder() { 17 | } 18 | 19 | protected abstract int bytesPerAtom(); 20 | 21 | protected abstract int bytesPerLine(); 22 | 23 | protected void decodeBufferPrefix(PushbackInputStream var1, OutputStream var2) throws IOException { 24 | } 25 | 26 | protected void decodeBufferSuffix(PushbackInputStream var1, OutputStream var2) throws IOException { 27 | } 28 | 29 | protected int decodeLinePrefix(PushbackInputStream var1, OutputStream var2) throws IOException { 30 | return this.bytesPerLine(); 31 | } 32 | 33 | protected void decodeLineSuffix(PushbackInputStream var1, OutputStream var2) throws IOException { 34 | } 35 | 36 | protected void decodeAtom(PushbackInputStream var1, OutputStream var2, int var3) throws IOException { 37 | throw new IOException(); 38 | } 39 | 40 | protected int readFully(InputStream var1, byte[] var2, int var3, int var4) throws IOException { 41 | for(int var5 = 0; var5 < var4; ++var5) { 42 | int var6 = var1.read(); 43 | if(var6 == -1) { 44 | return var5 == 0?-1:var5; 45 | } 46 | 47 | var2[var5 + var3] = (byte)var6; 48 | } 49 | 50 | return var4; 51 | } 52 | 53 | public void decodeBuffer(InputStream var1, OutputStream var2) throws IOException { 54 | int var4 = 0; 55 | PushbackInputStream var5 = new PushbackInputStream(var1); 56 | this.decodeBufferPrefix(var5, var2); 57 | 58 | while(true) { 59 | try { 60 | int var6 = this.decodeLinePrefix(var5, var2); 61 | 62 | int var3; 63 | for(var3 = 0; var3 + this.bytesPerAtom() < var6; var3 += this.bytesPerAtom()) { 64 | this.decodeAtom(var5, var2, this.bytesPerAtom()); 65 | var4 += this.bytesPerAtom(); 66 | } 67 | 68 | if(var3 + this.bytesPerAtom() == var6) { 69 | this.decodeAtom(var5, var2, this.bytesPerAtom()); 70 | var4 += this.bytesPerAtom(); 71 | } else { 72 | this.decodeAtom(var5, var2, var6 - var3); 73 | var4 += var6 - var3; 74 | } 75 | 76 | this.decodeLineSuffix(var5, var2); 77 | } catch (IOException var8) { 78 | this.decodeBufferSuffix(var5, var2); 79 | return; 80 | } 81 | } 82 | } 83 | 84 | public byte[] decodeBuffer(String var1) throws IOException { 85 | byte[] var2 = new byte[var1.length()]; 86 | var1.getBytes(0, var1.length(), var2, 0); 87 | ByteArrayInputStream var3 = new ByteArrayInputStream(var2); 88 | ByteArrayOutputStream var4 = new ByteArrayOutputStream(); 89 | this.decodeBuffer(var3, var4); 90 | return var4.toByteArray(); 91 | } 92 | 93 | public byte[] decodeBuffer(InputStream var1) throws IOException { 94 | ByteArrayOutputStream var2 = new ByteArrayOutputStream(); 95 | this.decodeBuffer(var1, var2); 96 | return var2.toByteArray(); 97 | } 98 | 99 | public ByteBuffer decodeBufferToByteBuffer(String var1) throws IOException { 100 | return ByteBuffer.wrap(this.decodeBuffer(var1)); 101 | } 102 | 103 | public ByteBuffer decodeBufferToByteBuffer(InputStream var1) throws IOException { 104 | return ByteBuffer.wrap(this.decodeBuffer(var1)); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /toolutils4j/src/main/java/com/gyf/cipher/base64/CharacterEncoder.java: -------------------------------------------------------------------------------- 1 | package com.gyf.cipher.base64; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.OutputStream; 8 | import java.io.PrintStream; 9 | import java.nio.ByteBuffer; 10 | 11 | /** 12 | * Created by gyf on 2016/11/14. 13 | */ 14 | 15 | public abstract class CharacterEncoder { 16 | protected PrintStream pStream; 17 | 18 | public CharacterEncoder() { 19 | } 20 | 21 | protected abstract int bytesPerAtom(); 22 | 23 | protected abstract int bytesPerLine(); 24 | 25 | protected void encodeBufferPrefix(OutputStream var1) throws IOException { 26 | this.pStream = new PrintStream(var1); 27 | } 28 | 29 | protected void encodeBufferSuffix(OutputStream var1) throws IOException { 30 | } 31 | 32 | protected void encodeLinePrefix(OutputStream var1, int var2) throws IOException { 33 | } 34 | 35 | protected void encodeLineSuffix(OutputStream var1) throws IOException { 36 | this.pStream.println(); 37 | } 38 | 39 | protected abstract void encodeAtom(OutputStream var1, byte[] var2, int var3, int var4) throws IOException; 40 | 41 | protected int readFully(InputStream var1, byte[] var2) throws IOException { 42 | for(int var3 = 0; var3 < var2.length; ++var3) { 43 | int var4 = var1.read(); 44 | if(var4 == -1) { 45 | return var3; 46 | } 47 | 48 | var2[var3] = (byte)var4; 49 | } 50 | 51 | return var2.length; 52 | } 53 | 54 | public void encode(InputStream var1, OutputStream var2) throws IOException { 55 | byte[] var5 = new byte[this.bytesPerLine()]; 56 | this.encodeBufferPrefix(var2); 57 | 58 | while(true) { 59 | int var4 = this.readFully(var1, var5); 60 | if(var4 == 0) { 61 | break; 62 | } 63 | 64 | this.encodeLinePrefix(var2, var4); 65 | 66 | for(int var3 = 0; var3 < var4; var3 += this.bytesPerAtom()) { 67 | if(var3 + this.bytesPerAtom() <= var4) { 68 | this.encodeAtom(var2, var5, var3, this.bytesPerAtom()); 69 | } else { 70 | this.encodeAtom(var2, var5, var3, var4 - var3); 71 | } 72 | } 73 | 74 | if(var4 < this.bytesPerLine()) { 75 | break; 76 | } 77 | 78 | this.encodeLineSuffix(var2); 79 | } 80 | 81 | this.encodeBufferSuffix(var2); 82 | } 83 | 84 | public void encode(byte[] var1, OutputStream var2) throws IOException { 85 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1); 86 | this.encode((InputStream)var3, var2); 87 | } 88 | 89 | public String encode(byte[] var1) { 90 | ByteArrayOutputStream var2 = new ByteArrayOutputStream(); 91 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1); 92 | String var4 = null; 93 | 94 | try { 95 | this.encode((InputStream)var3, var2); 96 | var4 = var2.toString("8859_1"); 97 | return var4; 98 | } catch (Exception var6) { 99 | throw new Error("CharacterEncoder.encode internal error"); 100 | } 101 | } 102 | 103 | private byte[] getBytes(ByteBuffer var1) { 104 | byte[] var2 = null; 105 | if(var1.hasArray()) { 106 | byte[] var3 = var1.array(); 107 | if(var3.length == var1.capacity() && var3.length == var1.remaining()) { 108 | var2 = var3; 109 | var1.position(var1.limit()); 110 | } 111 | } 112 | 113 | if(var2 == null) { 114 | var2 = new byte[var1.remaining()]; 115 | var1.get(var2); 116 | } 117 | 118 | return var2; 119 | } 120 | 121 | public void encode(ByteBuffer var1, OutputStream var2) throws IOException { 122 | byte[] var3 = this.getBytes(var1); 123 | this.encode(var3, var2); 124 | } 125 | 126 | public String encode(ByteBuffer var1) { 127 | byte[] var2 = this.getBytes(var1); 128 | return this.encode(var2); 129 | } 130 | 131 | public void encodeBuffer(InputStream var1, OutputStream var2) throws IOException { 132 | byte[] var5 = new byte[this.bytesPerLine()]; 133 | this.encodeBufferPrefix(var2); 134 | 135 | int var4; 136 | do { 137 | var4 = this.readFully(var1, var5); 138 | if(var4 == 0) { 139 | break; 140 | } 141 | 142 | this.encodeLinePrefix(var2, var4); 143 | 144 | for(int var3 = 0; var3 < var4; var3 += this.bytesPerAtom()) { 145 | if(var3 + this.bytesPerAtom() <= var4) { 146 | this.encodeAtom(var2, var5, var3, this.bytesPerAtom()); 147 | } else { 148 | this.encodeAtom(var2, var5, var3, var4 - var3); 149 | } 150 | } 151 | 152 | this.encodeLineSuffix(var2); 153 | } while(var4 >= this.bytesPerLine()); 154 | 155 | this.encodeBufferSuffix(var2); 156 | } 157 | 158 | public void encodeBuffer(byte[] var1, OutputStream var2) throws IOException { 159 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1); 160 | this.encodeBuffer((InputStream)var3, var2); 161 | } 162 | 163 | public String encodeBuffer(byte[] var1) { 164 | ByteArrayOutputStream var2 = new ByteArrayOutputStream(); 165 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1); 166 | 167 | try { 168 | this.encodeBuffer((InputStream)var3, var2); 169 | } catch (Exception var5) { 170 | throw new Error("CharacterEncoder.encodeBuffer internal error"); 171 | } 172 | 173 | return var2.toString(); 174 | } 175 | 176 | public void encodeBuffer(ByteBuffer var1, OutputStream var2) throws IOException { 177 | byte[] var3 = this.getBytes(var1); 178 | this.encodeBuffer(var3, var2); 179 | } 180 | 181 | public String encodeBuffer(ByteBuffer var1) { 182 | byte[] var2 = this.getBytes(var1); 183 | return this.encodeBuffer(var2); 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /toolutils4j/src/main/java/com/gyf/tool/CoordinateTransformUtil.java: -------------------------------------------------------------------------------- 1 | package com.gyf.tool; 2 | 3 | 4 | /** 5 | * CoordinateTransformUtil.java GPS坐标转换工具 6 | */ 7 | public class CoordinateTransformUtil { 8 | /** 9 | * The X pi. 10 | */ 11 | static double x_pi = 3.14159265358979324 * 3000.0 / 180.0; 12 | /** 13 | * The Pi. 14 | */ 15 | static double pi = 3.1415926535897932384626; 16 | /** 17 | * The A. 18 | */ 19 | static double a = 6378245.0; 20 | /** 21 | * The Ee. 22 | */ 23 | static double ee = 0.00669342162296594323; 24 | 25 | /** 26 | * 百度坐标系(BD-09)转WGS坐标(百度坐标纬度,百度坐标经度),WGS84坐标数组 27 | * 28 | * @param lng the lng 29 | * @param lat the lat 30 | * @return the double [ ] 31 | */ 32 | public static double[] bd09towgs84(double lng, double lat) { 33 | double[] gcj = bd09togcj02(lng, lat); 34 | double[] wgs84 = gcj02towgs84(gcj[0], gcj[1]); 35 | return wgs84; 36 | } 37 | 38 | /** 39 | * WGS坐标转百度坐标系(BD-09)(WGS84坐标系的经度,WGS84坐标系的纬度),百度坐标数组 40 | * 41 | * @param lng the lng 42 | * @param lat the lat 43 | * @return the double [ ] 44 | */ 45 | public static double[] wgs84tobd09(double lng, double lat) { 46 | double[] gcj = wgs84togcj02(lng, lat); 47 | double[] bd09 = gcj02tobd09(gcj[0], gcj[1]); 48 | return bd09; 49 | } 50 | 51 | /** 52 | * 火星坐标系(GCJ-02)转百度坐标系(BD-09)(火星坐标经度,火星坐标纬度),百度坐标数组 53 | * 54 | * @param lng the lng 55 | * @param lat the lat 56 | * @return the double [ ] 57 | */ 58 | public static double[] gcj02tobd09(double lng, double lat) { 59 | double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi); 60 | double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi); 61 | double bd_lng = z * Math.cos(theta) + 0.0065; 62 | double bd_lat = z * Math.sin(theta) + 0.006; 63 | return new double[]{bd_lng, bd_lat}; 64 | } 65 | 66 | /** 67 | * 百度坐标系(BD-09)转火星坐标系(GCJ-02)(百度坐标纬度,百度坐标经度),火星坐标数组 68 | * 69 | * @param bd_lon the bd lon 70 | * @param bd_lat the bd lat 71 | * @return the double [ ] 72 | */ 73 | public static double[] bd09togcj02(double bd_lon, double bd_lat) { 74 | double x = bd_lon - 0.0065; 75 | double y = bd_lat - 0.006; 76 | double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi); 77 | double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi); 78 | double gg_lng = z * Math.cos(theta); 79 | double gg_lat = z * Math.sin(theta); 80 | return new double[]{gg_lng, gg_lat}; 81 | } 82 | 83 | /** 84 | * WGS84转GCJ02(火星坐标系)(WGS84坐标系的经度,WGS84坐标系的纬度),火星坐标数组 85 | * 86 | * @param lng the lng 87 | * @param lat the lat 88 | * @return the double [ ] 89 | */ 90 | public static double[] wgs84togcj02(double lng, double lat) { 91 | if (out_of_china(lng, lat)) { 92 | return new double[]{lng, lat}; 93 | } 94 | double dlat = transformlat(lng - 105.0, lat - 35.0); 95 | double dlng = transformlng(lng - 105.0, lat - 35.0); 96 | double radlat = lat / 180.0 * pi; 97 | double magic = Math.sin(radlat); 98 | magic = 1 - ee * magic * magic; 99 | double sqrtmagic = Math.sqrt(magic); 100 | dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi); 101 | dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi); 102 | double mglat = lat + dlat; 103 | double mglng = lng + dlng; 104 | return new double[]{mglng, mglat}; 105 | } 106 | 107 | /** 108 | * GCJ02(火星坐标系)转GPS84(火星坐标系的经度,火星坐标系纬度),WGS84坐标数组 109 | * 110 | * @param lng the lng 111 | * @param lat the lat 112 | * @return the double [ ] 113 | */ 114 | public static double[] gcj02towgs84(double lng, double lat) { 115 | if (out_of_china(lng, lat)) { 116 | return new double[]{lng, lat}; 117 | } 118 | double dlat = transformlat(lng - 105.0, lat - 35.0); 119 | double dlng = transformlng(lng - 105.0, lat - 35.0); 120 | double radlat = lat / 180.0 * pi; 121 | double magic = Math.sin(radlat); 122 | magic = 1 - ee * magic * magic; 123 | double sqrtmagic = Math.sqrt(magic); 124 | dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi); 125 | dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi); 126 | double mglat = lat + dlat; 127 | double mglng = lng + dlng; 128 | return new double[]{lng * 2 - mglng, lat * 2 - mglat}; 129 | } 130 | 131 | /** 132 | * 纬度转换 133 | * 134 | * @param lng the lng 135 | * @param lat the lat 136 | * @return the double 137 | */ 138 | public static double transformlat(double lng, double lat) { 139 | double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)); 140 | ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0; 141 | ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0; 142 | ret += (160.0 * Math.sin(lat / 12.0 * pi) + 320 * Math.sin(lat * pi / 30.0)) * 2.0 / 3.0; 143 | return ret; 144 | } 145 | 146 | /** 147 | * 经度转换 148 | * 149 | * @param lng the lng 150 | * @param lat the lat 151 | * @return the double 152 | */ 153 | public static double transformlng(double lng, double lat) { 154 | double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)); 155 | ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0; 156 | ret += (20.0 * Math.sin(lng * pi) + 40.0 * Math.sin(lng / 3.0 * pi)) * 2.0 / 3.0; 157 | ret += (150.0 * Math.sin(lng / 12.0 * pi) + 300.0 * Math.sin(lng / 30.0 * pi)) * 2.0 / 3.0; 158 | return ret; 159 | } 160 | 161 | /** 162 | * 判断是否在国内,不在国内不做偏移 163 | * 164 | * @param lng the lng 165 | * @param lat the lat 166 | * @return the boolean 167 | */ 168 | public static boolean out_of_china(double lng, double lat) { 169 | if (lng < 72.004 || lng > 137.8347) { 170 | return true; 171 | } else if (lat < 0.8293 || lat > 55.8271) { 172 | return true; 173 | } 174 | return false; 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /toolutils4j/src/main/java/com/gyf/tool/DateUtil.java: -------------------------------------------------------------------------------- 1 | package com.gyf.tool; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.*; 6 | 7 | /** 8 | * The type Date utils. 9 | */ 10 | public class DateUtil { 11 | /** 12 | * The constant DATE_FORMAT_DATETIME. 13 | */ 14 | private static final SimpleDateFormat DATE_FORMAT_DATETIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 15 | /** 16 | * The constant DATE_FORMAT_DATE. 17 | */ 18 | private static final SimpleDateFormat DATE_FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd"); 19 | /** 20 | * The constant DATE_FORMAT_TIME. 21 | */ 22 | private static final SimpleDateFormat DATE_FORMAT_TIME = new SimpleDateFormat("HH:mm:ss"); 23 | 24 | /** 25 | * Format data time string. 26 | * 格式化日期时间 27 | * 28 | * @param date the date 29 | * @return the string 30 | */ 31 | public static String formatDataTime(long date) { 32 | return DATE_FORMAT_DATETIME.format(new Date(date)); 33 | } 34 | 35 | /** 36 | * Format date string. 37 | * 格式化日期 38 | * 39 | * @param date the date 40 | * @return the string 41 | */ 42 | public static String formatDate(long date) { 43 | return DATE_FORMAT_DATE.format(new Date(date)); 44 | } 45 | 46 | /** 47 | * Format time string. 48 | * 格式化时间 49 | * 50 | * @param date the date 51 | * @return the string 52 | */ 53 | public static String formatTime(long date) { 54 | return DATE_FORMAT_TIME.format(new Date(date)); 55 | } 56 | 57 | /** 58 | * Format date custom string. 59 | * 自定义格式的格式化日期时间 60 | * 61 | * @param beginDate the begin date 62 | * @param format the format 63 | * @return the string 64 | */ 65 | public static String formatDateCustom(String beginDate, String format) { 66 | return new SimpleDateFormat(format).format(new Date(Long.parseLong(beginDate))); 67 | } 68 | 69 | /** 70 | * Format date custom string. 71 | * 自定义格式的格式化日期时间 72 | * 73 | * @param beginDate the begin date 74 | * @param format the format 75 | * @return the string 76 | */ 77 | public static String formatDateCustom(Date beginDate, String format) { 78 | return new SimpleDateFormat(format).format(beginDate); 79 | } 80 | 81 | /** 82 | * Gets time. 83 | * 获取系统日期 84 | * 85 | * @return the time 86 | */ 87 | public static String getTime() { 88 | Calendar cal = Calendar.getInstance(); 89 | cal.setTimeInMillis(System.currentTimeMillis()); 90 | return cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND); 91 | } 92 | 93 | /** 94 | * Gets date. 95 | * 获取系统时间 96 | * 97 | * @return the date 98 | */ 99 | public static String getDate() { 100 | return new SimpleDateFormat("yyyyMMdd").format(System.currentTimeMillis()); 101 | } 102 | 103 | /** 104 | * Get date time string. 105 | * 获取系统日期时间 106 | * 107 | * @return the string 108 | */ 109 | public static String getDateTime() { 110 | return DATE_FORMAT_DATETIME.format(System.currentTimeMillis()); 111 | } 112 | 113 | /** 114 | * Get date time string. 115 | * 获取系统日期时间 116 | * 117 | * @param format the format 118 | * @return the string 119 | */ 120 | public static String getDateTime(String format) { 121 | return new SimpleDateFormat(format).format(System.currentTimeMillis()); 122 | } 123 | 124 | 125 | /** 126 | * Subtract date long. 127 | * 计算两个时间差 128 | * 129 | * @param dateStart the date start 130 | * @param dateEnd the date end 131 | * @return the long 132 | */ 133 | public static long subtractDate(Date dateStart, Date dateEnd) { 134 | return dateEnd.getTime() - dateStart.getTime(); 135 | } 136 | 137 | /** 138 | * Gets date after. 139 | * 得到几天后的时间 140 | * 141 | * @param d the d 142 | * @param day the day 143 | * @return the date after 144 | */ 145 | public static Date getDateAfter(Date d, int day) { 146 | Calendar now = Calendar.getInstance(); 147 | now.setTime(d); 148 | now.set(Calendar.DATE, now.get(Calendar.DATE) + day); 149 | return now.getTime(); 150 | } 151 | 152 | /** 153 | * Gets date time after. 154 | * 得到当前时间指定毫秒后的时间 155 | * 156 | * @param mill the mill 157 | * @return the String 158 | */ 159 | public static String getDateTimeAfter(long mill) { 160 | return DATE_FORMAT_DATETIME.format(System.currentTimeMillis() + mill); 161 | } 162 | 163 | /** 164 | * Get week of year int. 165 | * 获取当前时间为本年的第几周 166 | * 167 | * @return the int 168 | */ 169 | public static int getWeekOfYear() { 170 | Calendar calendar = Calendar.getInstance(); 171 | calendar.setTime(new Date()); 172 | return calendar.get(Calendar.WEEK_OF_YEAR); 173 | } 174 | 175 | /** 176 | * Gets week of month. 177 | * 获取当前时间为本月的第几周 178 | * 179 | * @return the week of month 180 | */ 181 | public static int getWeekOfMonth() { 182 | Calendar calendar = Calendar.getInstance(); 183 | int week = calendar.get(Calendar.WEEK_OF_MONTH); 184 | return week - 1; 185 | } 186 | 187 | /** 188 | * Gets day of week. 189 | * 获取当前时间为本周的第几天 190 | * 191 | * @return the day of week 192 | */ 193 | public static int getDayOfWeek() { 194 | Calendar calendar = Calendar.getInstance(); 195 | int day = calendar.get(Calendar.DAY_OF_WEEK); 196 | if (day == 1) { 197 | day = 7; 198 | } else { 199 | day = day - 1; 200 | } 201 | return day; 202 | } 203 | 204 | /** 205 | * Gets start time of week. 206 | * 获取一周开始时间 207 | * 208 | * @return the start time of week 209 | * @throws ParseException the parse exception 210 | */ 211 | public static Date getStartTimeOfWeek() throws ParseException { 212 | Calendar c = Calendar.getInstance(); 213 | int day = c.get(Calendar.DAY_OF_WEEK); 214 | long time = System.currentTimeMillis(); 215 | if (day > 1) { 216 | time = time - (day - 2) * 24 * 60 * 60 * 1000L; 217 | } else { 218 | time = time - 6 * 24 * 60 * 60 * 1000L; 219 | } 220 | Date date = new Date(time); 221 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 222 | date = sdf.parse(sdf.format(date)); 223 | return date; 224 | } 225 | 226 | /** 227 | * Gets end time of week. 228 | * 获取一周结束时间 229 | * 230 | * @return the end time of week 231 | */ 232 | public static Date getEndTimeOfWeek() { 233 | Calendar c = Calendar.getInstance(); 234 | int day = c.get(Calendar.DAY_OF_WEEK); 235 | long time = System.currentTimeMillis(); 236 | if (day > 1) { 237 | time = time + (8 - day) * 24 * 60 * 60 * 1000L; 238 | } 239 | Date date = new Date(time); 240 | SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); 241 | SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 242 | try { 243 | date = sdf2.parse(sdf1.format(date) + " 23:59:59"); 244 | } catch (ParseException e) { 245 | e.printStackTrace(); 246 | } 247 | return date; 248 | } 249 | 250 | 251 | /** 252 | * Gets week of date. 253 | * 根据日期获取星期 254 | * 255 | * @param date the date 256 | * @return the week of date 257 | */ 258 | public static int getWeekOfDate(Date date) { 259 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 260 | Date currentDate = null; 261 | Date targetDate = null; 262 | try { 263 | currentDate = sdf.parse(sdf.format(new Date())); 264 | targetDate = sdf.parse(sdf.format(date)); 265 | } catch (ParseException e) { 266 | e.printStackTrace(); 267 | } 268 | if (currentDate.getTime() == targetDate.getTime()) { 269 | return getDayOfWeek(); 270 | } else if (currentDate.getTime() < targetDate.getTime()) { 271 | return (int) ((targetDate.getTime() - currentDate.getTime()) / (24 * 60 * 60 * 1000) 272 | + getDayOfWeek()) % 7; 273 | } else if (currentDate.getTime() > targetDate.getTime()) { 274 | return (int) (getDayOfWeek() + 7 275 | - (currentDate.getTime() - targetDate.getTime()) / (24 * 60 * 60 * 1000) % 7) % 7; 276 | } 277 | return 0; 278 | } 279 | 280 | /** 281 | * Gets date list of week. 282 | * 根据日期获取一周的日期(从周一到周日) 283 | * 284 | * @param date the date 285 | * @return the date list of week 286 | * @throws ParseException the parse exception 287 | */ 288 | public static List getDateListOfWeek(Date date) { 289 | List list = new ArrayList(); 290 | int weekOfDate = getWeekOfDate(date); 291 | Date firstDay = new Date(date.getTime() - (weekOfDate - 1) * 24 * 60 * 60 * 1000L); 292 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 293 | try { 294 | firstDay = sdf.parse(sdf.format(firstDay)); 295 | } catch (ParseException e) { 296 | e.printStackTrace(); 297 | } 298 | list.add(firstDay); 299 | for (int i = 1; i < 7; i++) { 300 | if (i == 1) { 301 | list.add(new Date(firstDay.getTime() + i * 24 * 60 * 60 * 1000L)); 302 | } else { 303 | list.add(new Date(firstDay.getTime() + (i + 1) * 24 * 60 * 60 * 1000L)); 304 | } 305 | } 306 | return list; 307 | } 308 | 309 | /** 310 | * Gets age. 311 | * 根据日期返回年龄 312 | * 313 | * @param birthDate the birth date 314 | * @return the age 315 | */ 316 | public static int getAge(Date birthDate) { 317 | 318 | if (birthDate == null) 319 | throw new RuntimeException("出生日期不能为null"); 320 | 321 | int age = 0; 322 | 323 | Date now = new Date(); 324 | 325 | SimpleDateFormat format_y = new SimpleDateFormat("yyyy"); 326 | SimpleDateFormat format_M = new SimpleDateFormat("MM"); 327 | 328 | String birth_year = format_y.format(birthDate); 329 | String this_year = format_y.format(now); 330 | 331 | String birth_month = format_M.format(birthDate); 332 | String this_month = format_M.format(now); 333 | // 初步,估算 334 | age = Integer.parseInt(this_year) - Integer.parseInt(birth_year); 335 | // 如果未到出生月份,则age - 1 336 | if (this_month.compareTo(birth_month) < 0) { 337 | age -= 1; 338 | } 339 | if (age < 0) { 340 | age = 0; 341 | } 342 | return age; 343 | } 344 | 345 | /** 346 | * Gets next date. 347 | * 获得第二条日期 348 | * 349 | * @return the next date 350 | * @throws Exception the exception 351 | */ 352 | public static Date getNextDate() throws Exception { 353 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 354 | Date date = new Date(); 355 | date.setDate(date.getDate() + 1); 356 | 357 | String str = format.format(date); 358 | return format.parse(str); 359 | } 360 | 361 | /** 362 | * Date to str string. 363 | * 日期转字符串 364 | * 365 | * @param date the date 366 | * @return the string 367 | */ 368 | public static String date2Str(Date date) { 369 | 370 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 371 | String str = format.format(date); 372 | return str; 373 | } 374 | 375 | /** 376 | * Str to date date. 377 | * 字符串转日期 378 | * 379 | * @param str the str 380 | * @return the date 381 | */ 382 | public static Date str2Date(String str) { 383 | return str2Date(str, "yyyy-MM-dd HH:mm:ss"); 384 | } 385 | 386 | /** 387 | * String 2 date date. 388 | * 字符串转换成Date 389 | * 390 | * @param s the s 391 | * @param style the style 392 | * @return the date 393 | */ 394 | public static Date str2Date(String s, String style) { 395 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); 396 | simpleDateFormat.applyPattern(style); 397 | Date date = null; 398 | if (s == null || s.length() < 6) { 399 | return null; 400 | } 401 | try { 402 | date = simpleDateFormat.parse(s); 403 | } catch (ParseException e) { 404 | e.printStackTrace(); 405 | } 406 | return date; 407 | } 408 | 409 | /** 410 | * Is ampm string. 411 | * 判断是上午还是下午 412 | * 413 | * @param date the date 414 | * @return the string 415 | */ 416 | public static String isAMPM(Date date) { 417 | GregorianCalendar ca = new GregorianCalendar(); 418 | ca.setTime(date); 419 | return GregorianCalendar.AM_PM == 0 ? "am" : "pm"; 420 | } 421 | 422 | 423 | /** 424 | * Time am pm night int. 425 | * 判断指定日期是上午,下午,晚上0-上午;1-下午;2-晚上;3-过期 426 | * 427 | * @param date the date 428 | * @return the int 429 | */ 430 | public static String isAmPmNight(Date date) { 431 | String start = "00:00:00"; 432 | String night = "23:59:59"; 433 | String am = "12:00:00"; 434 | String pm = "18:00:00"; 435 | 436 | SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss"); 437 | Date d_start = null; 438 | Date d_night = null; 439 | Date d_am = null; 440 | Date d_pm = null; 441 | try { 442 | d_start = s.parse(start); 443 | d_night = s.parse(night); 444 | d_am = s.parse(am); 445 | d_pm = s.parse(pm); 446 | } catch (ParseException e) { 447 | e.printStackTrace(); 448 | } 449 | 450 | Date paramsTime = str2Date(formatTime(date.getTime()), "HH:mm:ss"); 451 | 452 | if (paramsTime.after(d_start) && paramsTime.before(d_am)) { 453 | return "am"; 454 | } 455 | if (paramsTime.after(d_am) && paramsTime.before(d_pm)) { 456 | return "pm"; 457 | } 458 | if (paramsTime.after(d_pm) && paramsTime.before(d_night)) { 459 | return "night"; 460 | } 461 | return ""; 462 | } 463 | 464 | /** 465 | * Is leap year boolean. 466 | * 判断是否为闰年 467 | * @param date the date 468 | * @return the boolean 469 | */ 470 | public static boolean isLeapYear(Date date) { 471 | 472 | /** 473 | * 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年 474 | * 3.能被4整除同时能被100整除则不是闰年 475 | */ 476 | GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance(); 477 | gc.setTime(date); 478 | int year = gc.get(Calendar.YEAR); 479 | if ((year % 400) == 0) 480 | return true; 481 | else if ((year % 4) == 0) { 482 | if ((year % 100) == 0) 483 | return false; 484 | else 485 | return true; 486 | } else 487 | return false; 488 | } 489 | 490 | } 491 | --------------------------------------------------------------------------------