├── .idea ├── .name ├── copyright │ └── profiles_settings.xml ├── encodings.xml ├── dictionaries │ └── shaharbarsheshet.xml ├── libraries │ ├── junit_4_12.xml │ ├── hamcrest_core_1_3.xml │ ├── support_annotations_24_1_1.xml │ ├── support_vector_drawable_24_1_1.xml │ ├── animated_vector_drawable_24_1_1.xml │ ├── appcompat_v7_24_1_1.xml │ └── support_v4_24_1_1.xml ├── modules.xml ├── runConfigurations.xml ├── compiler.xml ├── gradle.xml └── misc.xml ├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── styles.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 │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── bytesizebit │ │ │ └── androidutils │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── bytesizebit │ │ └── androidutils │ │ └── ApplicationTest.java ├── proguard-rules.pro └── build.gradle ├── androidutils ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ └── values │ │ │ │ └── strings.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── bytesizebit │ │ │ └── androidutils │ │ │ ├── ResourcesUtils.java │ │ │ ├── VersionUtils.java │ │ │ ├── ThreadUtils.java │ │ │ ├── ValidationUtils.java │ │ │ ├── SizeUtils.java │ │ │ ├── JavaUtils.java │ │ │ ├── IOUtils.java │ │ │ ├── KeyboardUtils.java │ │ │ ├── PermissionUtils.java │ │ │ ├── ViewUtils.java │ │ │ ├── StringUtils.java │ │ │ ├── DialogUtils.java │ │ │ ├── EncryptionUtils.java │ │ │ ├── NetworkUtils.java │ │ │ ├── IntentUtils.java │ │ │ ├── ScreenUtils.java │ │ │ ├── ImageUtils.java │ │ │ └── DateUtils.java │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── bytesizebit │ │ │ └── androidutils │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── bytesizebit │ │ └── androidutils │ │ └── ApplicationTest.java ├── proguard-rules.pro ├── gradle.properties ├── maven-push.gradle └── build.gradle ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradle.properties ├── gradlew.bat ├── gradlew ├── README.md └── LICENSE /.idea/.name: -------------------------------------------------------------------------------- 1 | Android Utils -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /androidutils/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':androidutils' 2 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Android Utils 3 | 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shahar2k5/AndroidUtils/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /androidutils/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AndroidUtils 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shahar2k5/AndroidUtils/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shahar2k5/AndroidUtils/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shahar2k5/AndroidUtils/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shahar2k5/AndroidUtils/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shahar2k5/AndroidUtils/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /.idea/dictionaries/shaharbarsheshet.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | barsheshet 5 | bytesizebit 6 | shahar 7 | 8 | 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip 7 | -------------------------------------------------------------------------------- /androidutils/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/bytesizebit/androidutils/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 7 | */ 8 | public class ExampleUnitTest { 9 | @Test 10 | public void addition_isCorrect() throws Exception { 11 | 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /androidutils/src/test/java/com/bytesizebit/androidutils/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test 12 | public void addition_isCorrect() throws Exception { 13 | assertEquals(4, 2 + 2); 14 | } 15 | } -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/bytesizebit/androidutils/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /androidutils/src/androidTest/java/com/bytesizebit/androidutils/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /.idea/libraries/junit_4_12.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/libraries/hamcrest_core_1_3.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/libraries/support_annotations_24_1_1.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/shaharbarsheshet/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /androidutils/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/shaharbarsheshet/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 24 5 | buildToolsVersion "24.0.1" 6 | 7 | defaultConfig { 8 | applicationId "com.bytesizebit.androidutils" 9 | minSdkVersion 16 10 | targetSdkVersion 24 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | testCompile 'junit:junit:4.12' 25 | compile 'com.android.support:appcompat-v7:24.1.1' 26 | testCompile project(path: ':androidutils') 27 | } 28 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/ResourcesUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import java.lang.reflect.Field; 4 | 5 | /*********** 6 | * Android Utils 7 | * Created by Shahar Barsheshet on 11/03/2016. 8 | * bytesizebit@gmail.com 9 | * www.bytesizebit.com 10 | ***********/ 11 | public class ResourcesUtils { 12 | 13 | /** 14 | * Load resource id by name 15 | * 16 | * @param resName the name of the resource 17 | * @param c some clazz 18 | * @return the id of the resource 19 | */ 20 | public static int getResIdFromString(CharSequence resName, Class c) { 21 | try { 22 | Field idField = c.getDeclaredField(resName.toString()); 23 | return idField.getInt(idField); 24 | } catch (Exception e) { 25 | return -1; 26 | } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /.idea/libraries/support_vector_drawable_24_1_1.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/libraries/animated_vector_drawable_24_1_1.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 24 | 25 | -------------------------------------------------------------------------------- /androidutils/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | POM_NAME=AndroidUtils 21 | POM_ARTIFACT_ID=androidutils 22 | POM_PACKAGING=aar 23 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/VersionUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.os.Build; 4 | 5 | /*********** 6 | * Android Utils 7 | * Created by Shahar Barsheshet on 17/08/2015. 8 | * bytesizebit@gmail.com 9 | * www.bytesizebit.com 10 | ***********/ 11 | public class VersionUtils { 12 | public static boolean isNougatOrHigher() { 13 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N; 14 | } 15 | 16 | public static boolean isMarshmallowOrHigher() { 17 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; 18 | } 19 | 20 | public static boolean isLollipopOrHigher() { 21 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; 22 | } 23 | 24 | public static boolean isKitKatOrHigher() { 25 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; 26 | } 27 | 28 | public static boolean isJellyBeanOrHigher() { 29 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /.idea/libraries/appcompat_v7_24_1_1.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/ThreadUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.os.Looper; 4 | import android.util.Log; 5 | 6 | /*********** 7 | * Android Utils 8 | * Created by Shahar Barsheshet on 11/06/2015. 9 | * bytesizebit@gmail.com 10 | * www.bytesizebit.com 11 | ***********/ 12 | public class ThreadUtils { 13 | 14 | private ThreadUtils() { 15 | } 16 | 17 | /** 18 | * Makes the thread sleep for some time 19 | * 20 | * @param millis time to sleep in millis 21 | */ 22 | public static void threadSleep(long millis) { 23 | try { 24 | Thread.sleep(millis); 25 | } catch (InterruptedException ex) { 26 | Log.e("Exception", StringUtils.exceptionStackTraceToString(ex)); 27 | } 28 | } 29 | 30 | /** 31 | * Check if running on main thread 32 | */ 33 | public static void checkUiThread() { 34 | if (Looper.getMainLooper() != Looper.myLooper()) { 35 | throw new IllegalStateException( 36 | "Must be called from the main thread. Was: " + Thread.currentThread()); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /.idea/libraries/support_v4_24_1_1.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/ValidationUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.util.Patterns; 4 | 5 | /****** 6 | * Android Utils 7 | * Created by Shahar Barsheshet on 08/08/2016. 8 | * bytesizebit@gmail.com 9 | * www.bytesizebit.com 10 | ******/ 11 | public class ValidationUtils { 12 | private ValidationUtils() { 13 | } 14 | 15 | /** 16 | * Check if an email is valid 17 | * 18 | * @param email the email to check 19 | * @return {@code true} if the email is valid 20 | */ 21 | public static boolean isValidEmail(String email) { 22 | return Patterns.EMAIL_ADDRESS.matcher(email).matches(); 23 | } 24 | 25 | /** 26 | * Check if an IP Address is valid 27 | * 28 | * @param IPAddress the IP Address to check 29 | * @return {@code true} if the email is valid 30 | */ 31 | public static boolean isValidIPAddress(String IPAddress) { 32 | return Patterns.IP_ADDRESS.matcher(IPAddress).matches(); 33 | } 34 | 35 | /** 36 | * Check if a url is valid 37 | * 38 | * @param url the url to check 39 | * @return {@code true} if the url is valid 40 | */ 41 | public static boolean isValidUrl(String url) { 42 | return Patterns.WEB_URL.matcher(url).matches(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # [Android] ======================== 2 | # Built application files 3 | *.apk 4 | *.ap_ 5 | 6 | # Files for the Dalvik VM 7 | *.dex 8 | 9 | # Java class files 10 | *.class 11 | 12 | # Generated files 13 | bin/ 14 | gen/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | 30 | ## Directory-based project format: 31 | .idea/ 32 | 33 | ## File-based project format: 34 | *.ipr 35 | *.iws 36 | 37 | ## Plugin-specific files: 38 | 39 | # IntelliJ 40 | out/ 41 | 42 | # mpeltonen/sbt-idea plugin 43 | .idea_modules/ 44 | 45 | # JIRA plugin 46 | atlassian-ide-plugin.xml 47 | 48 | # Crashlytics plugin (for Android Studio and IntelliJ) 49 | com_crashlytics_export_strings.xml 50 | 51 | 52 | # [Maven] ======================== 53 | target/ 54 | pom.xml.tag 55 | pom.xml.releaseBackup 56 | pom.xml.versionsBackup 57 | pom.xml.next 58 | release.properties 59 | 60 | 61 | # [Gradle-Android] ======================== 62 | 63 | # Ignore Gradle GUI config 64 | gradle-app.setting 65 | 66 | # Gradle Signing 67 | signing.properties 68 | trestle.keystore 69 | 70 | # Mobile Tools for Java (J2ME) 71 | .mtj.tmp/ 72 | 73 | # Package Files # 74 | *.jar 75 | *.war 76 | *.ear 77 | 78 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 79 | hs_err_pid* 80 | 81 | # Misc 82 | /.idea/workspace.xml 83 | .DS_Store 84 | /captures 85 | **/*.iml 86 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | VERSION_NAME=1.0.0 21 | VERSION_CODE=1 22 | GROUP=com.github.shahar2k5 23 | 24 | POM_DESCRIPTION=A library full of greate Android must have Utils 25 | POM_URL=https://github.com/shahar2k5/AndroidUtils 26 | POM_SCM_URL=https://github.com/Shahar2k5/AndroidUtils 27 | POM_SCM_CONNECTION=scm:git@github.com:Shahar2k5/AndroidUtils.git 28 | POM_SCM_DEV_CONNECTION=scm:git@github.com:Shahar2k5/AndroidUtils.git 29 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 30 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 31 | POM_LICENCE_DIST=repo 32 | POM_DEVELOPER_ID=Shahar2k5 33 | POM_DEVELOPER_NAME=Shahar Barsheshet 34 | 35 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/SizeUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.content.Context; 4 | 5 | /*********** 6 | * Android Utils 7 | * Created by Shahar Barsheshet on 17/10/2015. 8 | * bytesizebit@gmail.com 9 | * www.bytesizebit.com 10 | ***********/ 11 | public class SizeUtils { 12 | 13 | private SizeUtils() { 14 | } 15 | 16 | /** 17 | * Convert DP to PX 18 | * 19 | * @param context the context 20 | * @param dpValue size in dp 21 | * @return size in pixels 22 | */ 23 | public static int dpToPx(Context context, float dpValue) { 24 | final float scale = context.getResources().getDisplayMetrics().density; 25 | return (int) (dpValue * scale + 0.5f); 26 | } 27 | 28 | /** 29 | * Convert PX to DP 30 | * 31 | * @param context the context 32 | * @param pxValue size in pixels 33 | * @return size in dp 34 | */ 35 | public static int pxToDp(Context context, float pxValue) { 36 | final float scale = context.getResources().getDisplayMetrics().density; 37 | return (int) (pxValue / scale + 0.5f); 38 | } 39 | 40 | /** 41 | * Convert SP to PX 42 | * 43 | * @param context the context 44 | * @param spValue size in sp 45 | * @return 46 | */ 47 | public static int spToPx(Context context, float spValue) { 48 | final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 49 | return (int) (spValue * fontScale + 0.5f); 50 | } 51 | 52 | /** 53 | * Convert PX to SP 54 | * 55 | * @param context the context 56 | * @param pxValue size in px 57 | * @return size in sp 58 | */ 59 | public static int pxToSp(Context context, float pxValue) { 60 | final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 61 | return (int) (pxValue / fontScale + 0.5f); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/JavaUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /*********** 7 | * Android Utils 8 | * Created by Shahar Barsheshet on 17/10/2015. 9 | * bytesizebit@gmail.com 10 | * www.bytesizebit.com 11 | ***********/ 12 | public class JavaUtils { 13 | private JavaUtils() { 14 | } 15 | 16 | /** 17 | * Get the index of an object 18 | * 19 | * @param array the items 20 | * @param objectToFind the object 21 | * @return the index of the object or -1 if not found 22 | */ 23 | public static int indexOf(Object[] array, Object objectToFind) { 24 | if (array == null || array.length == 0 || objectToFind == null) { 25 | return -1; 26 | } 27 | for (int i = 0; i < array.length; i++) { 28 | Object obj = array[i]; 29 | if (obj.equals(objectToFind)) { 30 | return i; 31 | } 32 | } 33 | return -1; 34 | } 35 | 36 | /** 37 | * Create a Integer arrayList from String arrayList 38 | * 39 | * @param arrayList source array 40 | * @return Integer arrayList 41 | */ 42 | public static ArrayList convertStringArrayToIntegerArray(List arrayList) { 43 | ArrayList integers = new ArrayList<>(); 44 | for (String str : arrayList) { 45 | integers.add(Integer.valueOf(str)); 46 | } 47 | return integers; 48 | } 49 | 50 | /** 51 | * Check if object is null and throw 52 | * 53 | * @param object the object to check 54 | * @param message the message to throw 55 | * @param the object type 56 | * @return the object if not null 57 | */ 58 | public static T checkNotNull(T object, String message) { 59 | if (object == null) { 60 | throw new NullPointerException(message); 61 | } 62 | return object; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/IOUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.graphics.Bitmap; 4 | 5 | import java.io.File; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | 9 | /*********** 10 | * Android Utils 11 | * Created by Shahar Barsheshet on 17/10/2015. 12 | * bytesizebit@gmail.com 13 | * www.bytesizebit.com 14 | ***********/ 15 | public class IOUtils { 16 | 17 | private IOUtils() { 18 | } 19 | 20 | /** 21 | * Save a Bitmap to a local file 22 | * 23 | * @param bmp the Bitmap to save 24 | * @param fullPathWithFileName path and file name 25 | * @throws IOException 26 | */ 27 | public static void saveBitmapToFile(Bitmap bmp, String fullPathWithFileName) throws IOException { 28 | FileOutputStream out = null; 29 | try { 30 | out = new FileOutputStream(createParentDirIfNotExists(fullPathWithFileName)); 31 | bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance 32 | // PNG is a lossless format, the compression factor (100) is ignored 33 | } finally { 34 | try { 35 | if (out != null) { 36 | out.close(); 37 | } 38 | } catch (IOException e) { 39 | e.printStackTrace(); 40 | } 41 | } 42 | } 43 | 44 | /** 45 | * Delete a selected directory recursively 46 | * 47 | * @param dir the directory to delete 48 | * @return {@code true} is deleted successfully 49 | */ 50 | public static boolean deleteDir(File dir) { 51 | if (dir == null) { 52 | return false; 53 | } 54 | if (dir.isDirectory()) { 55 | String[] children = dir.list(); 56 | for (String child : children) { 57 | boolean success = deleteDir(new File(dir, child)); 58 | if (!success) { 59 | return false; 60 | } 61 | } 62 | } 63 | return dir.delete(); 64 | } 65 | 66 | /** 67 | * Create a directory if needed 68 | * 69 | * @param filePath the path to the directory 70 | * @return File of the create directory 71 | */ 72 | public static File createParentDirIfNotExists(String filePath) { 73 | File file = new File(filePath); 74 | file.getParentFile().mkdirs(); 75 | return file; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/KeyboardUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.view.View; 6 | import android.view.inputmethod.InputMethodManager; 7 | import android.widget.EditText; 8 | 9 | /*********** 10 | * Android Utils 11 | * Created by Shahar Barsheshet on 17/10/2015. 12 | * bytesizebit@gmail.com 13 | * www.bytesizebit.com 14 | ***********/ 15 | public class KeyboardUtils { 16 | 17 | private KeyboardUtils() { 18 | } 19 | 20 | /** 21 | * Hide soft keyboard 22 | */ 23 | public static void hideSoftKeyboard(Activity activity) { 24 | View view = activity.getWindow().peekDecorView(); 25 | if (view != null) { 26 | InputMethodManager inputmanger = (InputMethodManager) activity 27 | .getSystemService(Context.INPUT_METHOD_SERVICE); 28 | inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0); 29 | } 30 | } 31 | 32 | /** 33 | * Hide soft keyboard 34 | */ 35 | public static void hideSoftKeyboard(Context context, View view) { 36 | view.clearFocus(); 37 | InputMethodManager inputmanger = (InputMethodManager) context 38 | .getSystemService(Context.INPUT_METHOD_SERVICE); 39 | inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0); 40 | } 41 | 42 | /** 43 | * Show soft keyboard 44 | */ 45 | public static void showSoftKeyboard(Activity activity) { 46 | showSoftKeyboard(activity, null); 47 | } 48 | 49 | /** 50 | * Show soft keyboard 51 | */ 52 | public static void showSoftKeyboard(Context context, View view) { 53 | view.setFocusable(true); 54 | view.setFocusableInTouchMode(true); 55 | view.requestFocus(); 56 | InputMethodManager inputManager = (InputMethodManager) context 57 | .getSystemService(Context.INPUT_METHOD_SERVICE); 58 | inputManager.showSoftInput(view, 0); 59 | } 60 | 61 | /** 62 | * Toggle soft keyboard state 63 | */ 64 | public static void toggleKeyboradState(Context context, EditText edit) { 65 | edit.setFocusable(true); 66 | edit.setFocusableInTouchMode(true); 67 | edit.requestFocus(); 68 | InputMethodManager inputManager = (InputMethodManager) context 69 | .getSystemService(Context.INPUT_METHOD_SERVICE); 70 | inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); 71 | } 72 | 73 | 74 | } 75 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/PermissionUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.Activity; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.net.Uri; 8 | import android.os.Build; 9 | import android.provider.Settings; 10 | import android.support.v4.app.ActivityCompat; 11 | import android.support.v4.app.Fragment; 12 | 13 | /****** 14 | * Android Utils 15 | * Created by Shahar Barsheshet on 20/06/16. 16 | * bytesizebit@gmail.com 17 | * www.bytesizebit.com 18 | ******/ 19 | public class PermissionUtils { 20 | public static final int RC_CAMERA_PERM = 10; 21 | public static final int RC_LOCATION_PERM = 11; 22 | public static final int RC_MIC_PERM = 12; 23 | public static final int RC_CALL_PERM = 13; 24 | public static final int RC_CONTACT_PERM = 14; 25 | 26 | /** 27 | * Open the app settings to enable permissions 28 | * 29 | * @param context the calling Activity or Fragment. 30 | */ 31 | public static void openPermissionsSettings(Context context) { 32 | if (context == null) { 33 | return; 34 | } 35 | final Intent i = new Intent(); 36 | i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); 37 | i.addCategory(Intent.CATEGORY_DEFAULT); 38 | i.setData(Uri.parse("package:" + context.getPackageName())); 39 | i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 40 | i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 41 | i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 42 | context.startActivity(i); 43 | } 44 | 45 | /** 46 | * Check if user denied permissions with the flag NEVER ASK AGAIN. 47 | * 48 | * @param object the calling Activity or Fragment. 49 | * @param deniedPerms the set of denied permissions. 50 | * @return {@code true} if user denied at least one permission with the flag NEVER ASK AGAIN. 51 | */ 52 | public static boolean checkDeniedPermissionsNeverAskAgain(Object object, String deniedPerms) { 53 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 54 | boolean shouldShowRationale; 55 | shouldShowRationale = shouldShowRequestPermissionRationale(object, deniedPerms); 56 | return !shouldShowRationale; 57 | } 58 | return false; 59 | } 60 | 61 | @TargetApi(23) 62 | private static boolean shouldShowRequestPermissionRationale(Object object, String perm) { 63 | if (object instanceof Activity) { 64 | return ActivityCompat.shouldShowRequestPermissionRationale((Activity) object, perm); 65 | } else if (object instanceof Fragment) { 66 | return ((Fragment) object).shouldShowRequestPermissionRationale(perm); 67 | } else 68 | return object instanceof android.app.Fragment && ((android.app.Fragment) object).shouldShowRequestPermissionRationale(perm); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 24 | 25 | 37 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 64 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/ViewUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.text.SpannableString; 4 | import android.text.Spanned; 5 | import android.text.SpannedString; 6 | import android.text.method.LinkMovementMethod; 7 | import android.text.style.ClickableSpan; 8 | import android.text.style.UnderlineSpan; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | import android.widget.ListView; 12 | import android.widget.TextView; 13 | 14 | /*********** 15 | * Android Utils 16 | * Created by Shahar Barsheshet on 07/02/2015. 17 | * bytesizebit@gmail.com 18 | * www.bytesizebit.com 19 | ***********/ 20 | public class ViewUtils { 21 | 22 | /** 23 | * Set visibility to sibling views 24 | * 25 | * @param view current view 26 | * @param visibility visibility state 27 | */ 28 | public static void setSiblingsVisibility(View view, int visibility) { 29 | ViewGroup parent = (ViewGroup) view.getParent(); 30 | for (int i = 0; i < parent.getChildCount(); i++) { 31 | View child = parent.getChildAt(i); 32 | if (child != view) { 33 | child.setVisibility(visibility); 34 | } 35 | } 36 | } 37 | 38 | /** 39 | * Scroll listview to bottom 40 | * 41 | * @param listView the listview to scroll 42 | * @param smoothScroll should scroll smooth or snap 43 | */ 44 | public static void listViewScrollToBottom(final ListView listView, boolean smoothScroll) { 45 | // due to issue with scrolling in listview doesnt reach the end of the list, this small hack is needed - calling the method twice with small delay in between 46 | if (smoothScroll) { 47 | listView.post(new Runnable() { 48 | @Override 49 | public void run() { 50 | listView.smoothScrollToPosition(listView.getCount() - 1); 51 | } 52 | }); 53 | listView.postDelayed(new Runnable() { 54 | @Override 55 | public void run() { 56 | listView.smoothScrollToPosition(listView.getCount() - 1); 57 | } 58 | }, 100); 59 | } else { 60 | listView.post(new Runnable() { 61 | @Override 62 | public void run() { 63 | listView.setSelection(listView.getCount() - 1); 64 | } 65 | }); 66 | listView.postDelayed(new Runnable() { 67 | @Override 68 | public void run() { 69 | listView.setSelection(listView.getCount() - 1); 70 | } 71 | }, 100); 72 | } 73 | } 74 | 75 | /** 76 | * Create an underline text clickable 77 | * 78 | * @param textView the view to handle 79 | * @param onclick the click callback 80 | */ 81 | public static void makeUnderlinedTextClickable(TextView textView, ClickableSpan onclick) { 82 | SpannedString string = (SpannedString) textView.getText(); 83 | int underlineStart = string.nextSpanTransition(0, string.length(), UnderlineSpan.class); 84 | int underlineEnd = string.nextSpanTransition(underlineStart, string.length(), UnderlineSpan.class); 85 | 86 | SpannableString ss = new SpannableString(string); 87 | ss.setSpan(onclick, underlineStart, underlineEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 88 | textView.setText(ss); 89 | textView.setMovementMethod(LinkMovementMethod.getInstance()); 90 | } 91 | 92 | 93 | } 94 | -------------------------------------------------------------------------------- /androidutils/maven-push.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Chris Banes 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 | apply plugin: 'maven' 18 | apply plugin: 'signing' 19 | 20 | def isReleaseBuild() { 21 | return VERSION_NAME.contains("SNAPSHOT") == false 22 | } 23 | 24 | def getReleaseRepositoryUrl() { 25 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL 26 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 27 | } 28 | 29 | def getSnapshotRepositoryUrl() { 30 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL 31 | : "https://oss.sonatype.org/content/repositories/snapshots/" 32 | } 33 | 34 | def getRepositoryUsername() { 35 | return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : "" 36 | } 37 | 38 | def getRepositoryPassword() { 39 | return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : "" 40 | } 41 | 42 | afterEvaluate { project -> 43 | uploadArchives { 44 | repositories { 45 | mavenDeployer { 46 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 47 | 48 | pom.groupId = GROUP 49 | pom.artifactId = POM_ARTIFACT_ID 50 | pom.version = VERSION_NAME 51 | 52 | repository(url: getReleaseRepositoryUrl()) { 53 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 54 | } 55 | snapshotRepository(url: getSnapshotRepositoryUrl()) { 56 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 57 | } 58 | 59 | pom.project { 60 | name POM_NAME 61 | packaging POM_PACKAGING 62 | description POM_DESCRIPTION 63 | url POM_URL 64 | 65 | scm { 66 | url POM_SCM_URL 67 | connection POM_SCM_CONNECTION 68 | developerConnection POM_SCM_DEV_CONNECTION 69 | } 70 | 71 | licenses { 72 | license { 73 | name POM_LICENCE_NAME 74 | url POM_LICENCE_URL 75 | distribution POM_LICENCE_DIST 76 | } 77 | } 78 | 79 | developers { 80 | developer { 81 | id POM_DEVELOPER_ID 82 | name POM_DEVELOPER_NAME 83 | } 84 | } 85 | } 86 | } 87 | } 88 | } 89 | 90 | signing { 91 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } 92 | sign configurations.archives 93 | } 94 | 95 | //task androidJavadocs(type: Javadoc) { 96 | //source = android.sourceSets.main.allJava 97 | //} 98 | 99 | //task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { 100 | //classifier = 'javadoc' 101 | //from androidJavadocs.destinationDir 102 | //} 103 | 104 | task androidSourcesJar(type: Jar) { 105 | classifier = 'sources' 106 | from android.sourceSets.main.java.sourceFiles 107 | } 108 | 109 | artifacts { 110 | archives androidSourcesJar 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /androidutils/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | apply plugin: "com.jfrog.bintray" 4 | 5 | // This is the library version used when deploying the artifact 6 | version = "1.0.1" 7 | 8 | 9 | android { 10 | compileSdkVersion 24 11 | buildToolsVersion "24.0.1" 12 | 13 | defaultConfig { 14 | minSdkVersion 16 15 | targetSdkVersion 24 16 | versionCode 1 17 | versionName version 18 | } 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | } 26 | 27 | dependencies { 28 | compile fileTree(dir: 'libs', include: ['*.jar']) 29 | testCompile 'junit:junit:4.12' 30 | compile 'com.android.support:appcompat-v7:24.1.1' 31 | } 32 | 33 | def siteUrl = 'https://github.com/shahar2k5/AndroidUtils' // Homepage URL of the library 34 | def gitUrl = 'https://github.com/shahar2k5/AndroidUtils.git' // Git repository URL 35 | group = "com.github.shahar2k5" // Maven Group ID for the artifact 36 | 37 | install { 38 | repositories.mavenInstaller { 39 | // This generates POM.xml with proper parameters 40 | pom { 41 | project { 42 | packaging 'aar' 43 | 44 | // Add your description here 45 | name 'com.github.shahar2k5:androidutils' 46 | description = 'A library full of greate Android must have Utils' 47 | url siteUrl 48 | 49 | // Set your license 50 | licenses { 51 | license { 52 | name 'The Apache Software License, Version 2.0' 53 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 54 | } 55 | } 56 | developers { 57 | developer { 58 | id 'shahar2k5' 59 | name 'Shahar Barsheshet' 60 | email 'shahar2k5@gmail.com' 61 | } 62 | } 63 | scm { 64 | connection gitUrl 65 | developerConnection gitUrl 66 | url siteUrl 67 | } 68 | } 69 | } 70 | } 71 | } 72 | 73 | task sourcesJar(type: Jar) { 74 | from android.sourceSets.main.java.srcDirs 75 | classifier = 'sources' 76 | } 77 | 78 | task javadoc(type: Javadoc) { 79 | source = android.sourceSets.main.java.srcDirs 80 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 81 | } 82 | 83 | task javadocJar(type: Jar, dependsOn: javadoc) { 84 | classifier = 'javadoc' 85 | from javadoc.destinationDir 86 | } 87 | artifacts { 88 | archives javadocJar 89 | archives sourcesJar 90 | } 91 | 92 | Properties properties = new Properties() 93 | properties.load(project.rootProject.file('local.properties').newDataInputStream()) 94 | 95 | // https://github.com/bintray/gradle-bintray-plugin 96 | bintray { 97 | user = properties.getProperty("bintray.user") 98 | key = properties.getProperty("bintray.apikey") 99 | 100 | configurations = ['archives'] 101 | pkg { 102 | repo = "maven" 103 | // it is the name that appears in bintray when logged 104 | name = "androidutils" 105 | websiteUrl = siteUrl 106 | vcsUrl = gitUrl 107 | licenses = ["Apache-2.0"] 108 | publish = true 109 | version { 110 | gpg { 111 | sign = true //Determines whether to GPG sign the files. The default is false 112 | passphrase = properties.getProperty("bintray.gpg.password") 113 | //Optional. The passphrase for GPG signing' 114 | } 115 | } 116 | } 117 | } 118 | 119 | if (JavaVersion.current().isJava8Compatible()) { 120 | allprojects { 121 | tasks.withType(Javadoc) { 122 | options.addStringOption('Xdoclint:none', '-quiet') 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.support.annotation.NonNull; 4 | import android.text.TextUtils; 5 | 6 | import java.io.PrintWriter; 7 | import java.io.StringWriter; 8 | 9 | /*********** 10 | * Android Utils 11 | * Created by Shahar Barsheshet on 12/11/2015. 12 | * bytesizebit@gmail.com 13 | * www.bytesizebit.com 14 | ***********/ 15 | public class StringUtils { 16 | 17 | private StringUtils() { 18 | } 19 | 20 | /** 21 | *

Checks if a String is whitespace, empty ("") or null.

22 | *

23 | *

 24 |      * StringUtils.isBlank(null)      = true
 25 |      * StringUtils.isBlank("")        = true
 26 |      * StringUtils.isBlank(" ")       = true
 27 |      * StringUtils.isBlank("bob")     = false
 28 |      * StringUtils.isBlank("  bob  ") = false
 29 |      * 
30 | * 31 | * @param str the String to check, may be null 32 | * @return true if the String is null, empty or whitespace 33 | */ 34 | public static boolean isBlank(CharSequence str) { 35 | int strLen; 36 | if (str == null || (strLen = str.length()) == 0) { 37 | return true; 38 | } 39 | for (int i = 0; i < strLen; i++) { 40 | if ((!Character.isWhitespace(str.charAt(i)))) { 41 | return false; 42 | } 43 | } 44 | return true; 45 | } 46 | 47 | /** 48 | *

Checks if a String is not empty (""), not null and not whitespace only.

49 | *

50 | *

 51 |      * StringUtils.isNotBlank(null)      = false
 52 |      * StringUtils.isNotBlank("")        = false
 53 |      * StringUtils.isNotBlank(" ")       = false
 54 |      * StringUtils.isNotBlank("bob")     = true
 55 |      * StringUtils.isNotBlank("  bob  ") = true
 56 |      * 
57 | * 58 | * @param str the String to check, may be null 59 | * @return true if the String is 60 | * not empty and not null and not whitespace 61 | */ 62 | public static boolean isNotBlank(CharSequence str) { 63 | return !isBlank(str); 64 | } 65 | 66 | /** 67 | * Check if a string is empty 68 | * 69 | * @param str string to check 70 | * @return {@code true} if empty 71 | */ 72 | public static boolean isEmpty(CharSequence str) { 73 | return TextUtils.isEmpty(str); 74 | } 75 | 76 | /** 77 | * Check if a string is NOT empty 78 | * 79 | * @param str string to check 80 | * @return {@code true} if NOT empty 81 | */ 82 | public static boolean isNotEmpty(CharSequence str) { 83 | return !isEmpty(str); 84 | } 85 | 86 | /** 87 | * Capital only first letter 88 | * 89 | * @param original the string to change 90 | * @return a String with first capital letter 91 | */ 92 | public static String capitalizeFirstLetter(String original) { 93 | if (original == null || original.length() == 0) { 94 | return original; 95 | } 96 | return original.substring(0, 1).toUpperCase() + original.substring(1).toLowerCase(); 97 | } 98 | 99 | /** 100 | * Create a String from stacktrace 101 | * 102 | * @param ex the exception 103 | * @return a String generated from exception's stacktrace 104 | */ 105 | public static String exceptionStackTraceToString(Exception ex) { 106 | StringWriter errors = new StringWriter(); 107 | ex.printStackTrace(new PrintWriter(errors)); 108 | return errors.toString(); 109 | } 110 | 111 | /** 112 | * Get initials from a string 113 | * 114 | * @param string string to get initials from 115 | * @param maxLength max number of initials 116 | * @return a String with words initials 117 | */ 118 | @NonNull 119 | public static String getInitialsFromString(String string, int maxLength) { 120 | String[] splitted = string.split(" "); 121 | String initials = ""; 122 | for (String word : splitted) { 123 | if (StringUtils.isNotBlank(word)) { 124 | initials += word.charAt(0); 125 | } 126 | if (initials.length() >= maxLength) { 127 | break; 128 | } 129 | } 130 | return initials.toUpperCase(); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/DialogUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.app.Activity; 4 | import android.app.AlertDialog; 5 | import android.app.Dialog; 6 | import android.content.DialogInterface; 7 | 8 | /*********** 9 | * Android Utils 10 | * Created by Shahar Barsheshet on 17/10/2015. 11 | * bytesizebit@gmail.com 12 | * www.bytesizebit.com 13 | ***********/ 14 | public class DialogUtils { 15 | 16 | private DialogUtils() { 17 | } 18 | 19 | /** 20 | * Show an Alert Dialog with one button 21 | * 22 | * @param activity the context 23 | * @param title dialog title 24 | * @param text dialog message 25 | * @param buttonText text to appear in the dialog button 26 | * @param buttonListener button onClick callback 27 | * @return the AlertDialog 28 | */ 29 | public static AlertDialog showOneButtonsDialog( 30 | final Activity activity, final String title, final String text, final String buttonText, final DialogInterface.OnClickListener buttonListener) { 31 | if (activity == null || activity.isFinishing()) { 32 | return null; 33 | } 34 | return new AlertDialog.Builder(activity).setTitle(title) 35 | .setMessage(text) 36 | .setPositiveButton(buttonText, buttonListener) 37 | .show(); 38 | } 39 | 40 | /** 41 | * Show an Alert Dialog with two buttons 42 | * 43 | * @param activity the context 44 | * @param title dialog title 45 | * @param text dialog message 46 | * @param negativeButtonText negative text 47 | * @param leftButtonListener negative button callback 48 | * @param positiveButtonText positive button text 49 | * @param positiveButtonListener positive button text 50 | * @return the AlertDialog 51 | */ 52 | public static AlertDialog showTwoButtonsDialog( 53 | final Activity activity, final String title, final String text, final String negativeButtonText, final DialogInterface.OnClickListener leftButtonListener, final String 54 | positiveButtonText, final DialogInterface.OnClickListener positiveButtonListener) { 55 | if (activity == null || activity.isFinishing()) { 56 | return null; 57 | } 58 | return new AlertDialog.Builder(activity).setTitle(title) 59 | .setMessage(text) 60 | .setPositiveButton(negativeButtonText, leftButtonListener) 61 | .setNegativeButton(positiveButtonText, positiveButtonListener) 62 | .show(); 63 | } 64 | 65 | 66 | /** 67 | * Displays a dialog box with an OK button 68 | * 69 | * @param activity the context 70 | * @param title dialog title 71 | * @param text dialog message 72 | * @param okListener button callback 73 | */ 74 | public static void showOkDialog(final Activity activity, final String title, final String text, final DialogInterface.OnClickListener okListener) { 75 | if (activity == null || activity.isFinishing()) { 76 | return; 77 | } 78 | tryOnUiThread(activity, new Runnable() { 79 | @Override 80 | public void run() { 81 | new AlertDialog.Builder(activity).setTitle(title).setMessage(text).setPositiveButton(android.R.string.ok, okListener).show().setOwnerActivity(activity); 82 | } 83 | }); 84 | } 85 | 86 | /** 87 | * Displays a dialog box with an OK button 88 | * 89 | * @param activity the context 90 | * @param title dialog title 91 | * @param text dialog message 92 | */ 93 | public static void showOkDialog(final Activity activity, final String title, final String text) { 94 | showOkDialog(activity, title, text, null); 95 | } 96 | 97 | /** 98 | * Displays a dialog box with an OK button 99 | * 100 | * @param activity the context 101 | * @param title dialog title 102 | * @param text dialog message 103 | * @param okListener button callback 104 | * @return the SlertDialog 105 | */ 106 | public static AlertDialog createOkDialog(final Activity activity, final String title, final String text, final DialogInterface.OnClickListener okListener) { 107 | AlertDialog dialog = new AlertDialog.Builder(activity).setTitle(title).setMessage(text).setPositiveButton(android.R.string.ok, okListener).create(); 108 | dialog.setOwnerActivity(activity); 109 | return dialog; 110 | } 111 | 112 | /** 113 | * Dismiss dialog safely 114 | * 115 | * @param dialog dialog to dismiss 116 | */ 117 | public static void dismissDialogSafely(Dialog dialog) { 118 | if (dialog != null && dialog.isShowing()) { 119 | dialog.dismiss(); 120 | } 121 | } 122 | 123 | // helper to run on the UI thread 124 | private static void tryOnUiThread(Activity activity, final Runnable runnable) { 125 | activity.runOnUiThread(new Runnable() { 126 | @Override 127 | public void run() { 128 | try { 129 | runnable.run(); 130 | } catch (Exception e) { 131 | // probably window was closed 132 | } 133 | } 134 | }); 135 | } 136 | 137 | } 138 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/EncryptionUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.IOException; 6 | import java.nio.MappedByteBuffer; 7 | import java.nio.channels.FileChannel; 8 | import java.security.MessageDigest; 9 | import java.security.NoSuchAlgorithmException; 10 | 11 | /*********** 12 | * Android Utils 13 | * Created by Shahar Barsheshet on 20/01/2016. 14 | * bytesizebit@gmail.com 15 | * www.bytesizebit.com 16 | ***********/ 17 | public class EncryptionUtils { 18 | 19 | private EncryptionUtils() { 20 | } 21 | 22 | /** 23 | * Create MD5 String from string 24 | * 25 | * @param str the string 26 | * @return MD5 String 27 | */ 28 | public static String getMD5String(String str) { 29 | return getMD5String(str.getBytes()); 30 | } 31 | 32 | /** 33 | * Create MD5 String with salt 34 | * 35 | * @param str the string 36 | * @param salt salt 37 | * @return MD5 String 38 | */ 39 | public static String getMD5String(String str, String salt) { 40 | return bytesToHex(encryptMD5((str + salt).getBytes())); 41 | } 42 | 43 | /** 44 | * Create MD5 String from byte array 45 | * 46 | * @param bytes byte array 47 | * @return MD5 String 48 | */ 49 | public static String getMD5String(byte[] bytes) { 50 | return bytesToHex(encryptMD5(bytes)); 51 | } 52 | 53 | /** 54 | * Create MD5 String from byte array with salt 55 | * 56 | * @param bytes byte array 57 | * @param salt salt 58 | * @return MD5 String 59 | */ 60 | public static String getMD5String(byte[] bytes, byte[] salt) { 61 | byte[] dataSalt = new byte[bytes.length + salt.length]; 62 | System.arraycopy(bytes, 0, dataSalt, 0, bytes.length); 63 | System.arraycopy(salt, 0, dataSalt, bytes.length, salt.length); 64 | return bytesToHex(encryptMD5(dataSalt)); 65 | } 66 | 67 | /** 68 | * Encrypt byte array 69 | * 70 | * @param bytes bytes to encrypt 71 | * @return encrypted byte array if available 72 | */ 73 | public static byte[] encryptMD5(byte[] bytes) { 74 | try { 75 | MessageDigest md = MessageDigest.getInstance("MD5"); 76 | md.update(bytes); 77 | return md.digest(); 78 | } catch (NoSuchAlgorithmException e) { 79 | e.printStackTrace(); 80 | } 81 | return new byte[0]; 82 | } 83 | 84 | /** 85 | * Create a MD5 String from file path 86 | * 87 | * @param filePath path to a file 88 | * @return {@code String} MD5 string 89 | */ 90 | public static String getMD5File(String filePath) { 91 | return getMD5File(new File(filePath)); 92 | } 93 | 94 | /** 95 | * Create a MD5 String from file 96 | * 97 | * @param file file to get MD5 from 98 | * @return MD5 String 99 | */ 100 | public static String getMD5File(File file) { 101 | FileInputStream in = null; 102 | try { 103 | in = new FileInputStream(file); 104 | FileChannel channel = in.getChannel(); 105 | MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); 106 | MessageDigest md = MessageDigest.getInstance("MD5"); 107 | md.update(buffer); 108 | return bytesToHex(md.digest()); 109 | } catch (NoSuchAlgorithmException | IOException e) { 110 | e.printStackTrace(); 111 | } finally { 112 | if (in != null) { 113 | try { 114 | in.close(); 115 | } catch (IOException ignored) { 116 | } 117 | } 118 | } 119 | return ""; 120 | } 121 | 122 | /** 123 | * Get SHA1 from String 124 | * 125 | * @param str String to get SHA1 from 126 | * @return SHA1 string 127 | */ 128 | public static String getSHA(String str) { 129 | return getSHA(str.getBytes()); 130 | } 131 | 132 | /** 133 | * Get SHA1 from byte array 134 | * 135 | * @param bytes bytes to get SHA1 from 136 | * @return SHA1 String 137 | */ 138 | public static String getSHA(byte[] bytes) { 139 | return bytesToHex(encryptSHA(bytes)); 140 | } 141 | 142 | /** 143 | * Encrypt SHA1 144 | * 145 | * @param bytes bytes to encrypt 146 | * @return an SHA1 encrypted byte array 147 | */ 148 | public static byte[] encryptSHA(byte[] bytes) { 149 | try { 150 | MessageDigest md = MessageDigest.getInstance("SHA"); 151 | md.update(bytes); 152 | return md.digest(); 153 | } catch (NoSuchAlgorithmException e) { 154 | e.printStackTrace(); 155 | } 156 | return new byte[0]; 157 | } 158 | 159 | /** 160 | * Convert bytes to Hex 161 | * 162 | * @param src byte array to convert 163 | * @return String from converted byte array 164 | */ 165 | public static String bytesToHex(byte[] src) { 166 | char[] res = new char[src.length * 2]; 167 | final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; 168 | for (int i = 0, j = 0; i < src.length; i++) { 169 | res[j++] = hexDigits[src[i] >>> 4 & 0x0f]; 170 | res[j++] = hexDigits[src[i] & 0x0f]; 171 | } 172 | return new String(res); 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/NetworkUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.net.ConnectivityManager; 6 | import android.net.NetworkInfo; 7 | import android.telephony.TelephonyManager; 8 | 9 | /*********** 10 | * Android Utils 11 | * Created by Shahar Barsheshet on 18/05/2015. 12 | * bytesizebit@gmail.com 13 | * www.bytesizebit.com 14 | ***********/ 15 | public class NetworkUtils { 16 | 17 | private NetworkUtils() { 18 | } 19 | 20 | /** 21 | * Check if there is an active network 22 | * 23 | * @param context the context 24 | * @return {@code true} for active network 25 | */ 26 | public static boolean isNetworkAvailable(Context context) { 27 | ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 28 | NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 29 | return activeNetworkInfo != null && activeNetworkInfo.isConnected(); 30 | } 31 | 32 | /** 33 | * Get the network type 34 | * 35 | * @param context the context 36 | * @return String value network type 37 | */ 38 | public static String getNetworkType(Context context) { 39 | ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 40 | NetworkInfo eventInfo = connectivityManager.getActiveNetworkInfo(); 41 | if (eventInfo == null) { 42 | return "NONE"; 43 | } 44 | return eventInfo.getTypeName(); 45 | } 46 | 47 | /** 48 | * Get the network sub type 49 | * 50 | * @param context the context 51 | * @return String value network sub type 52 | */ 53 | public static String getNetworkSubType(Context context) { 54 | ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 55 | NetworkInfo eventInfo = connectivityManager.getActiveNetworkInfo(); 56 | if (eventInfo == null) { 57 | return "NONE"; 58 | } 59 | 60 | String typeName = eventInfo.getTypeName(); 61 | if (typeName.equals("WIFI")) { 62 | return eventInfo.getExtraInfo(); 63 | } 64 | 65 | return eventInfo.getSubtypeName(); 66 | } 67 | 68 | /** 69 | * Check if connected to cellular provider 70 | * 71 | * @param networkType the network type 72 | * @return {@code true} if connected to cellular provider 73 | */ 74 | public static boolean isNetworkTypeCellular(String networkType) { 75 | return networkType.equals("MOBILE"); 76 | } 77 | 78 | /** 79 | * Check if network connection has changed 80 | * 81 | * @param context the context 82 | * @param prevConnectivityType previous network type 83 | * @param mPrevConnectionSubType previous network sub type 84 | * @return {@code true} if network changed 85 | */ 86 | public static boolean isNetworkChanged(Context context, String prevConnectivityType, String mPrevConnectionSubType) { 87 | String connectivityType = getNetworkType(context); 88 | String connectivitySubType = getNetworkSubType(context); 89 | if (null == prevConnectivityType) { 90 | return false; 91 | } else if (!prevConnectivityType.equals(connectivityType)) { 92 | return true; 93 | } else if (!mPrevConnectionSubType.equals(connectivitySubType)) 94 | { 95 | return true; 96 | } 97 | 98 | return false; 99 | } 100 | 101 | /** 102 | * open the wireless network settings 103 | * 104 | * @param context the context 105 | */ 106 | public static void openWirelessNetworkSettings(Context context) { 107 | if (android.os.Build.VERSION.SDK_INT > 10) { 108 | context.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)); 109 | } else { 110 | context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS)); 111 | } 112 | } 113 | 114 | /** 115 | * Check if we have a WiFi connection 116 | * 117 | * @param context the context 118 | * @return {@code true} if connected to WiFi 119 | */ 120 | public static boolean isWifiConnected(Context context) { 121 | ConnectivityManager cm = (ConnectivityManager) context 122 | .getSystemService(Context.CONNECTIVITY_SERVICE); 123 | return cm != null && cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; 124 | } 125 | 126 | /** 127 | * Get the operator name 128 | * 129 | * @param context the context 130 | * @return String with operator name 131 | */ 132 | public static String getNetworkOperatorName(Context context) { 133 | TelephonyManager tm = (TelephonyManager) context 134 | .getSystemService(Context.TELEPHONY_SERVICE); 135 | return tm != null ? tm.getNetworkOperatorName() : null; 136 | } 137 | 138 | /** 139 | * Get the phone type 140 | *
141 |      * PHONE_TYPE_NONE  : 0
142 |      * PHONE_TYPE_GSM   : 1
143 |      * PHONE_TYPE_CDMA  : 2
144 |      * PHONE_TYPE_SIP   : 3
145 |      * 
146 |      *
147 |      * @param context  the context
148 |      * @return int phone type
149 |      */
150 |     public static int getPhoneType(Context context) {
151 |         TelephonyManager tm = (TelephonyManager) context
152 |                 .getSystemService(Context.TELEPHONY_SERVICE);
153 |         return tm != null ? tm.getPhoneType() : -1;
154 |     }
155 | }
156 | 


--------------------------------------------------------------------------------
/androidutils/src/main/java/com/bytesizebit/androidutils/IntentUtils.java:
--------------------------------------------------------------------------------
  1 | package com.bytesizebit.androidutils;
  2 | 
  3 | import android.app.ActivityManager;
  4 | import android.content.ComponentName;
  5 | import android.content.Context;
  6 | import android.content.Intent;
  7 | import android.content.pm.ResolveInfo;
  8 | import android.net.Uri;
  9 | 
 10 | import java.util.List;
 11 | 
 12 | /***********
 13 |  * Android Utils
 14 |  * Created by Shahar Barsheshet on 13/11/2015.
 15 |  * bytesizebit@gmail.com
 16 |  * www.bytesizebit.com
 17 |  ***********/
 18 | public class IntentUtils {
 19 | 
 20 |     private IntentUtils() {
 21 |     }
 22 | 
 23 |     /**
 24 |      * Makes a call
 25 |      *
 26 |      * @param context     some context
 27 |      * @param phoneNumber number to call
 28 |      */
 29 |     public static void callNumber(Context context, String phoneNumber) {
 30 |         openDialerActivityWithAction(context, phoneNumber, Intent.ACTION_CALL);
 31 |     }
 32 | 
 33 |     /**
 34 |      * Dial a number in the phone's keypad
 35 |      *
 36 |      * @param context     some context
 37 |      * @param phoneNumber number to dial
 38 |      */
 39 |     public static void dialNumber(Context context, String phoneNumber) {
 40 |         openDialerActivityWithAction(context, phoneNumber, Intent.ACTION_DIAL);
 41 |     }
 42 | 
 43 |     /**
 44 |      * Open dialer and perform action
 45 |      * 

46 | * Intent.ACTION_DIAL 47 | * Intent.ACTION_CALL 48 | *

49 | * 50 | * @param context some context 51 | * @param phoneNumber number to dial 52 | * @param action action to perform 53 | */ 54 | public static void openDialerActivityWithAction(Context context, String phoneNumber, String action) { 55 | Intent callIntent = new Intent(action); 56 | callIntent.setData(Uri.parse("tel:" + phoneNumber)); 57 | callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 58 | List resolveInfos = context.getPackageManager().queryIntentActivities(callIntent, 0); 59 | ResolveInfo chosenRi = null; 60 | for (ResolveInfo ri : resolveInfos) { 61 | if (ri.activityInfo != null && ri.activityInfo.name.startsWith("com.android")) { 62 | chosenRi = ri; 63 | } 64 | } 65 | if (chosenRi != null) { 66 | callIntent.setPackage(chosenRi.activityInfo.packageName); 67 | context.startActivity(callIntent); 68 | } 69 | } 70 | 71 | /** 72 | * Open compose email activity 73 | * 74 | * @param context some context 75 | * @param addresses email adress to send to 76 | * @param subject email subject 77 | */ 78 | public static void openComposeEmailActivity(Context context, String[] addresses, String subject) { 79 | Intent intent = new Intent(Intent.ACTION_SENDTO); 80 | intent.setData(Uri.parse("mailto:")); // only email apps should handle this 81 | intent.putExtra(Intent.EXTRA_EMAIL, addresses); 82 | intent.putExtra(Intent.EXTRA_SUBJECT, subject); 83 | startIntentIfPossible(context, intent); 84 | } 85 | 86 | /** 87 | * Open SMS activity to send SMS 88 | * 89 | * @param context some context 90 | * @param phoneNumber number to send to 91 | * @param body the message 92 | */ 93 | public static void openSendSmsActivity(Context context, String phoneNumber, String body) { 94 | Intent intent = new Intent(Intent.ACTION_VIEW); 95 | String phone = phoneNumber != null ? phoneNumber : ""; 96 | intent.setData(Uri.parse("sms:" + phone)); 97 | if (StringUtils.isNotBlank(body)) { 98 | intent.putExtra("sms_body", body); 99 | } 100 | startIntentIfPossible(context, intent); 101 | } 102 | 103 | /** 104 | * Create a WhatsApp share intent 105 | * 106 | * @param body the text to send 107 | * @return an Intent to share via whatsapp 108 | */ 109 | public static Intent createWhatsAppShareIntent(String body) { 110 | Intent intent = new Intent(); 111 | intent.setAction(Intent.ACTION_SEND); 112 | intent.putExtra(Intent.EXTRA_TEXT, body); 113 | intent.setType("text/plain"); 114 | intent.setPackage("com.whatsapp"); 115 | return intent; 116 | } 117 | 118 | /** 119 | * Starts an Activity if it is exists 120 | * 121 | * @param context the context 122 | * @param intent the intent to start 123 | */ 124 | private static void startIntentIfPossible(Context context, Intent intent) { 125 | if (isActivityAvailableForIntent(context, intent)) { 126 | context.startActivity(intent); 127 | } 128 | } 129 | 130 | /** 131 | * Check if there is a valid Activity for the intent 132 | * 133 | * @param context the context 134 | * @param intent the intent to test 135 | * @return {@code true} if Activity exists for that Intent 136 | */ 137 | public static boolean isActivityAvailableForIntent(Context context, Intent intent) { 138 | return intent.resolveActivity(context.getPackageManager()) != null; 139 | } 140 | 141 | /** 142 | * Open the playstore page for the current app 143 | * 144 | * @param context the context 145 | */ 146 | public static void openPlayStoreAppPage(Context context) { 147 | final String appPackageName = context.getPackageName(); // getPackageName() from Context or Activity object 148 | try { 149 | context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName))); 150 | } catch (android.content.ActivityNotFoundException anfe) { 151 | context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName))); 152 | } 153 | } 154 | 155 | /** 156 | * Check if a service is running 157 | * 158 | * @param className service class name 159 | * @param context some context 160 | * @return {@code true} if service is running 161 | */ 162 | public static boolean isRunningService(String className, Context context) { 163 | ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 164 | List runningServices = activityManager.getRunningServices(1000); 165 | for (ActivityManager.RunningServiceInfo runningServiceInfo : runningServices) { 166 | ComponentName service = runningServiceInfo.service; 167 | if (className.equals(service.getClassName())) { 168 | return true; 169 | } 170 | } 171 | return false; 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/ScreenUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.app.Activity; 4 | import android.app.KeyguardManager; 5 | import android.content.Context; 6 | import android.graphics.Bitmap; 7 | import android.os.Build; 8 | import android.util.DisplayMetrics; 9 | import android.util.TypedValue; 10 | import android.view.View; 11 | import android.view.WindowManager; 12 | import android.view.WindowManager.LayoutParams; 13 | 14 | /*********** 15 | * Android Utils 16 | * Created by Shahar Barsheshet on 17/10/2015. 17 | * bytesizebit@gmail.com 18 | * www.bytesizebit.com 19 | ***********/ 20 | public class ScreenUtils { 21 | 22 | private ScreenUtils() { 23 | } 24 | 25 | /** 26 | * Get screen width 27 | * 28 | * @param context the context 29 | * @return screen width in pixels 30 | */ 31 | public static int getScreenWidthInPx(Context context) { 32 | WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 33 | DisplayMetrics metrics = new DisplayMetrics(); 34 | windowManager.getDefaultDisplay().getMetrics(metrics); 35 | return metrics.widthPixels; 36 | } 37 | 38 | /** 39 | * Get screen height 40 | * 41 | * @param context the context 42 | * @return screen height in pixels 43 | */ 44 | public static int getScreenHeightInPx(Context context) { 45 | WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 46 | DisplayMetrics metrics = new DisplayMetrics(); 47 | windowManager.getDefaultDisplay().getMetrics(metrics); 48 | return metrics.heightPixels; 49 | } 50 | 51 | /** 52 | * Get the screen size 53 | * 54 | * @param context some context 55 | * @return ScreenSize object 56 | */ 57 | public static ScreenSize getScreenSize(Context context) { 58 | WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 59 | DisplayMetrics metrics = new DisplayMetrics(); 60 | windowManager.getDefaultDisplay().getMetrics(metrics); 61 | return new ScreenSize(metrics.widthPixels, metrics.heightPixels); 62 | } 63 | 64 | /** 65 | * Set transparent status bar 66 | * MIN API 19 67 | * should be called when onCreate() starts 68 | * 69 | * @param activity some activity 70 | */ 71 | public static void setTransparentStatusBar(Activity activity) { 72 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 73 | activity.getWindow().addFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS); 74 | activity.getWindow().addFlags(LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); 75 | } 76 | } 77 | 78 | /** 79 | * Get status bar height 80 | * 81 | * @param context the context 82 | * @return status bar height in pixels 83 | */ 84 | public static int getStatusBarHeight(Context context) { 85 | int result = 0; 86 | int resourceId = context.getResources() 87 | .getIdentifier("status_bar_height", "dimen", "android"); 88 | if (resourceId > 0) { 89 | result = context.getResources().getDimensionPixelSize(resourceId); 90 | } 91 | return result; 92 | } 93 | 94 | /** 95 | * Check if we have status bar 96 | * 97 | * @param activity some activity 98 | * @return {@code true} if we have status bar 99 | */ 100 | public static boolean hasStatusBar(Activity activity) { 101 | LayoutParams params = activity.getWindow().getAttributes(); 102 | return (params.flags & LayoutParams.FLAG_FULLSCREEN) != LayoutParams.FLAG_FULLSCREEN; 103 | } 104 | 105 | /** 106 | * Get the action bar height 107 | * 108 | * @param activity some activity 109 | * @return action bar height in pixels 110 | */ 111 | public static int getActionBarHeight(Activity activity) { 112 | TypedValue tv = new TypedValue(); 113 | if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { 114 | return TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics()); 115 | } 116 | return 0; 117 | } 118 | 119 | /** 120 | * Take a screenshot with the status bar 121 | * 122 | * @param activity the activity to capture 123 | * @return a Bitmap 124 | */ 125 | public static Bitmap takeScreenShotWithStatusBar(Activity activity) { 126 | View view = activity.getWindow().getDecorView(); 127 | view.setDrawingCacheEnabled(true); 128 | view.buildDrawingCache(); 129 | Bitmap bmp = view.getDrawingCache(); 130 | int width = getScreenWidthInPx(activity); 131 | int height = getScreenHeightInPx(activity); 132 | Bitmap bp = Bitmap.createBitmap(bmp, 0, 0, width, height); 133 | view.destroyDrawingCache(); 134 | return bp; 135 | } 136 | 137 | /** 138 | * Take a screenshot without the status bar 139 | * 140 | * @param activity the activity to capture 141 | * @return a Bitmap 142 | */ 143 | public static Bitmap takeScreenShoteWithoutStatusBar(Activity activity) { 144 | View view = activity.getWindow().getDecorView(); 145 | view.setDrawingCacheEnabled(true); 146 | view.buildDrawingCache(); 147 | Bitmap bmp = view.getDrawingCache(); 148 | int statusBarHeight = getStatusBarHeight(activity); 149 | int width = getScreenWidthInPx(activity); 150 | int height = getScreenHeightInPx(activity); 151 | Bitmap bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight); 152 | view.destroyDrawingCache(); 153 | return bp; 154 | } 155 | 156 | /** 157 | * Check if the screen is locked 158 | * 159 | * @param context some context 160 | * @return {@code true} if the screen is lock 161 | */ 162 | public static boolean isScreenLocked(Context context) { 163 | KeyguardManager km = (KeyguardManager) context 164 | .getSystemService(Context.KEYGUARD_SERVICE); 165 | return km.inKeyguardRestrictedInputMode(); 166 | } 167 | 168 | private static class ScreenSize { 169 | private int screenWidth; 170 | private int screenHeight; 171 | 172 | public ScreenSize(int screenWidth, int screenHeight) { 173 | this.screenWidth = screenWidth; 174 | this.screenHeight = screenHeight; 175 | } 176 | 177 | public int getScreenWidth() { 178 | return screenWidth; 179 | } 180 | 181 | public void setScreenWidth(int screenWidth) { 182 | this.screenWidth = screenWidth; 183 | } 184 | 185 | public int getScreenHeight() { 186 | return screenHeight; 187 | } 188 | 189 | public void setScreenHeight(int screenHeight) { 190 | this.screenHeight = screenHeight; 191 | } 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AndroidUtils 2 | Lots of Android utils every project should have 3 | 4 | ## Quick start 5 | 6 | Add jcenter to your project's gradle file 7 | 8 | ``` 9 | allprojects { 10 | repositories { 11 | jcenter() 12 | } 13 | } 14 | ``` 15 | 16 | #### Gradle 17 | 18 | 19 | ``` 20 | compile 'com.github.shahar2k5:androidutils:1.0.1' 21 | ``` 22 | 23 | 24 | #### Maven 25 | ``` 26 | 27 | com.github.shahar2k5 28 | androidutils 29 | 1.0.1 30 | pom 31 | 32 | ``` 33 | 34 | ## Usage 35 | 36 | A few examples on how to use the library 37 | 38 | ``` 39 | int sizeInPixels = SizeUtils.dpToPx(this, 20); 40 | 41 | boolean hasNetwork = NetworkUtils.isNetworkAvailable(this); 42 | 43 | ViewUtils.listViewScrollToBottom(listView, true); 44 | 45 | IntentUtils.openPlayStoreAppPage(this); 46 | 47 | DialogUtils.showOkDialog(this, dialogTitle, dialogMessage, new DialogInterface.OnClickListener() { 48 | @Override 49 | public void onClick(DialogInterface dialogInterface, int i) { 50 | // do something when the OK button was clicked 51 | } 52 | }); 53 | ``` 54 | 55 | ## API 56 | 57 | #### » [DateUtils](androidutils/src/main/java/com/bytesizebit/androidutils/DateUtils.java) 58 | 59 | + Convert Date to string with long format -> `formatDateLong` 60 | + Check if the date is less than 7 days from now -> `isLessThanOneWeek` 61 | + Check if the specific date is today -> `isToday` 62 | + Is the specific date yesterday -> `isYesterday` 63 | + Check for a leap year -> `isLeapYear` 64 | + return date string from milliseconds -> `millisecondsToString` 65 | + create time in milliseconds from a formatted string -> `stringToMilliseconds` 66 | + create a date from formatted string -> `stringToDate` 67 | + Create a formatted date -> `dateToString` 68 | + Convert date object to milliseconds -> `dateToMilliseconds` 69 | + Convert milliseconds to date object -> `millisecondsToDate` 70 | + Convert milliseconds to specific time unit -> `millisecondsToTimeUnit` 71 | + Get current time in milliseconds -> `getCurrentTimeMillis` 72 | + Get current time in formatted string -> `getCurrentTimeString` 73 | + Get current time in date object -> `getCurrentTimeDate` 74 | + Calculate time interval from now -> `getTimeIntervalFromNow` 75 | + Calculate time interval between 2 dates -> `getTimeIntervalBetweenDates` 76 | 77 | #### » [DialogUtils](androidutils/src/main/java/com/bytesizebit/androidutils/DialogUtils.java) 78 | 79 | + Show an Alert Dialog with one button -> `showOneButtonsDialog` 80 | + Show an Alert Dialog with two buttons -> `showTwoButtonsDialog` 81 | + Displays a dialog box with an OK button -> `showOkDialog` 82 | + Creates a dialog box with an OK button -> `createOkDialog` 83 | + Dismiss dialog safely -> `dismissDialogSafely` 84 | 85 | #### » [EncryptionUtils](androidutils/src/main/java/com/bytesizebit/androidutils/EncryptionUtils.java) 86 | 87 | + Create MD5 String from string -> `getMD5String` 88 | + Create MD5 String with salt -> `getMD5String` 89 | + Create MD5 String from byte array -> `getMD5String` 90 | + Create MD5 String from byte array with salt -> `getMD5String` 91 | + Encrypt byte array -> `encryptMD5` 92 | + Create a MD5 String from file path -> `getMD5File` 93 | + Create a MD5 String from file -> `getMD5File` 94 | + Get SHA1 from String -> `getSHA` 95 | + Get SHA1 from byte array -> `getSHA` 96 | + Encrypt SHA1 -> `encryptSHA` 97 | + Convert bytes to Hex -> `bytesToHex` 98 | 99 | #### » [ImageUtils](androidutils/src/main/java/com/bytesizebit/androidutils/ImageUtils.java) 100 | 101 | + Create a Bitmap from URI -> `getBitmapFromUri` 102 | + Get file system path from a URI -> `getRealPathFromURI` 103 | + Normalize a bitmap to 640px -> `normalize` 104 | + Normalize a bitmap to specific size -> `normalize` 105 | + Get image rotated by degree from metedata -> `getImageRotatedByMetadata` 106 | + Create a fullscreen image and punch a hole inside -> `punchARoundedHoleInABitmap` 107 | 108 | #### » [IntentUtils](androidutils/src/main/java/com/bytesizebit/androidutils/IntentUtils.java) 109 | 110 | + Makes a call -> `callNumber` 111 | + Dial a number in the phone's keypad -> `dialNumber` 112 | + Open compose email activity -> `openComposeEmailActivity` 113 | + Open SMS activity to send SMS -> `openSendSmsActivity` 114 | + Create a WhatsApp share intent -> `createWhatsAppShareIntent` 115 | + Starts an Activity if it is exists -> `startIntentIfPossible` 116 | + Check if there is a valid Activity for the intent -> `isActivityAvailableForIntent` 117 | + Open the playstore page for the current app -> `openPlayStoreAppPage` 118 | + Check if a service is running -> `isRunningService` 119 | 120 | #### » [IOUtils](androidutils/src/main/java/com/bytesizebit/androidutils/IOUtils.java) 121 | 122 | + Save a Bitmap to a local file -> `saveBitmapToFile` 123 | + Delete a selected directory recursively -> `deleteDir` 124 | + Create a directory if needed -> `createParentDirIfNotExists` 125 | 126 | #### » [JavaUtils](androidutils/src/main/java/com/bytesizebit/androidutils/JavaUtils.java) 127 | 128 | + Get the index of an object -> `indexOf` 129 | + Create a Integer arrayList from String arrayList -> `convertStringArrayToIntegerArray` 130 | + Check if object is null and throw -> `checkNotNull` 131 | 132 | #### » [KeyboardUtils](androidutils/src/main/java/com/bytesizebit/androidutils/KeyboardUtils.java) 133 | 134 | + Hide soft keyboard -> `hideSoftKeyboard` 135 | + Show soft keyboard -> `showSoftKeyboard` 136 | + Toggle soft keyboard state -> `toggleKeyboradState` 137 | 138 | #### » [NetworkUtils](androidutils/src/main/java/com/bytesizebit/androidutils/DateUtils.java) 139 | 140 | + Check if there is an active network -> `isNetworkAvailable` 141 | + Get the network type -> `getNetworkType` 142 | + Toggle soft keyboard state -> `toggleKeyboradState` 143 | 144 | #### » [PermissionUtils](androidutils/src/main/java/com/bytesizebit/androidutils/PermissionUtils.java) 145 | 146 | + Open the app settings to enable permissions -> `openPermissionsSettings` 147 | + Check if user denied permissions with the flag NEVER ASK AGAIN -> `checkDeniedPermissionsNeverAskAgain` 148 | 149 | #### » [ResourcesUtils](androidutils/src/main/java/com/bytesizebit/androidutils/ResourcesUtils.java) 150 | 151 | + Load resource id by name -> `getResIdFromString` 152 | 153 | #### » [ScreenUtils](androidutils/src/main/java/com/bytesizebit/androidutils/ScreenUtils.java) 154 | 155 | + Get screen width -> `getScreenWidthInPx` 156 | + Get screen height -> `getScreenHeightInPx` 157 | + ScreenSize -> `getScreenSize` 158 | + Set transparent status bar -> `setTransparentStatusBar` 159 | + Get status bar height -> `getStatusBarHeight` 160 | + Check if we have status bar -> `hasStatusBar` 161 | + Get the action bar height -> `getActionBarHeight` 162 | + Take a screenshot with the status bar -> `takeScreenShotWithStatusBar` 163 | + Take a screenshot without the status bar -> `takeScreenShoteWithoutStatusBar` 164 | + Check if the screen is locked -> `isScreenLocked` 165 | 166 | #### » [SizeUtils](androidutils/src/main/java/com/bytesizebit/androidutils/SizeUtils.java) 167 | 168 | + Convert DP to PX -> `dpToPx` 169 | + Convert PX to DP -> `pxToDp` 170 | + Convert SP to PX -> `spToPx` 171 | + Convert PX to SP -> `pxToSp` 172 | 173 | #### » [StringUtils](androidutils/src/main/java/com/bytesizebit/androidutils/StringUtils.java) 174 | 175 | + Checks if a String is whitespace, empty ("") or null. -> `isBlank` 176 | + Checks if a String is not empty (""), not null and not whitespace only. -> `isNotBlank` 177 | + Check if a string is empty -> `isEmpty` 178 | + Check if a string is NOT empty -> `isNotEmpty` 179 | + Capital only first letter -> `capitalizeFirstLetter` 180 | + Create a String from stacktrace -> `exceptionStackTraceToString` 181 | + Get initials from a string -> `getInitialsFromString` 182 | 183 | #### » [ThreadUtils](androidutils/src/main/java/com/bytesizebit/androidutils/ThreadUtils.java) 184 | 185 | + Makes the thread sleep for some time -> `threadSleep` 186 | + Check if running on main thread -> `checkUiThread` 187 | 188 | #### » [ValidationUtils](androidutils/src/main/java/com/bytesizebit/androidutils/ValidationUtils.java) 189 | 190 | + Check if an email is valid -> `isValidEmail` 191 | + Check if an IP Address is valid -> `isValidIPAddress` 192 | + Check if a url is valid -> `isValidUrl` 193 | 194 | #### » [VersionUtils](androidutils/src/main/java/com/bytesizebit/androidutils/VersionUtils.java) 195 | 196 | + `isNougatOrHigher` 197 | + `isMarshmallowOrHigher` 198 | + `isLollipopOrHigher` 199 | + `isKitKatOrHigher` 200 | + `isJellyBeanOrHigher` 201 | 202 | #### » [ViewUtils](androidutils/src/main/java/com/bytesizebit/androidutils/ViewUtils.java) 203 | 204 | + Set visibility to sibling views -> `setSiblingsVisibility` 205 | + Scroll listview to bottom -> `listViewScrollToBottom` 206 | + Create an underline text clickable -> `makeUnderlinedTextClickable` 207 | 208 | --- 209 | 210 | ## [License](LICENSE) 211 | 212 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/ImageUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.content.Context; 4 | import android.content.res.AssetFileDescriptor; 5 | import android.database.Cursor; 6 | import android.graphics.Bitmap; 7 | import android.graphics.BitmapFactory; 8 | import android.graphics.Canvas; 9 | import android.graphics.Matrix; 10 | import android.graphics.Paint; 11 | import android.graphics.PorterDuff; 12 | import android.graphics.PorterDuffXfermode; 13 | import android.media.ExifInterface; 14 | import android.net.Uri; 15 | import android.provider.MediaStore; 16 | import android.support.annotation.Nullable; 17 | 18 | import java.io.FileNotFoundException; 19 | import java.io.IOException; 20 | 21 | /*********** 22 | * Android Utils 23 | * Created by Shahar Barsheshet on 22/11/2015. 24 | * bytesizebit@gmail.com 25 | * www.bytesizebit.com 26 | ***********/ 27 | public class ImageUtils { 28 | 29 | private ImageUtils() { 30 | } 31 | 32 | private static final int MAX_BITMAP_WIDTH = 640; 33 | private static final int MAX_BITMAP_HEIGHT = 640; 34 | 35 | /** 36 | * Create a Bitmap from URI 37 | * 38 | * @param context the context 39 | * @param uri the uri to load from 40 | * @return a Bitmap 41 | */ 42 | @Nullable 43 | public static Bitmap getBitmapFromUri(Context context, Uri uri) { 44 | Bitmap bitmap = null; 45 | try { 46 | bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri); 47 | } catch (IOException e) { 48 | e.printStackTrace(); 49 | } 50 | return bitmap; 51 | } 52 | 53 | /** 54 | * Get file system path from a URI 55 | * 56 | * @param context the context 57 | * @param contentURI uri to load from 58 | * @return String path to the actual file 59 | */ 60 | public static String getRealPathFromURI(Context context, Uri contentURI) { 61 | String result; 62 | Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null); 63 | if (cursor == null) { // Source is Dropbox or other similar local file path 64 | result = contentURI.getPath(); 65 | } else { 66 | cursor.moveToFirst(); 67 | int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 68 | result = cursor.getString(idx); 69 | cursor.close(); 70 | } 71 | return result; 72 | } 73 | 74 | /** 75 | * Normalize a bitmap to 640px 76 | * 77 | * @param context the context 78 | * @param selectedImage uri for the selected image 79 | * @return {@code Bitmap} from the selected uri image 80 | */ 81 | public static Bitmap normalize(Context context, Uri selectedImage) { 82 | return normalize(context, selectedImage, MAX_BITMAP_WIDTH, MAX_BITMAP_HEIGHT); 83 | } 84 | 85 | /** 86 | * Normalize a bitmap to specific size 87 | * 88 | * @param context the context 89 | * @param selectedImage uri for the selected image 90 | * @return 91 | */ 92 | public static Bitmap normalize(Context context, Uri selectedImage, int maxWidth, int maxHeight) { 93 | Bitmap bm; 94 | bm = getImageResized(context, selectedImage, maxWidth, maxHeight); 95 | bm = getImageRotatedByMetadata(context, bm, selectedImage); 96 | return bm; 97 | } 98 | 99 | /** 100 | * Get image rotated by degree from metedata 101 | * 102 | * @param context the context 103 | * @param bitmap the bitmap to check 104 | * @param src the uri of the image 105 | * @return a rotated Bitmap 106 | */ 107 | public static Bitmap getImageRotatedByMetadata(Context context, Bitmap bitmap, Uri src) { 108 | try { 109 | ExifInterface exif = new ExifInterface(ImageUtils.getRealPathFromURI(context, src)); 110 | int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 111 | 112 | Matrix matrix = new Matrix(); 113 | switch (orientation) { 114 | case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: 115 | matrix.setScale(-1, 1); 116 | break; 117 | case ExifInterface.ORIENTATION_ROTATE_180: 118 | matrix.setRotate(180); 119 | break; 120 | case ExifInterface.ORIENTATION_FLIP_VERTICAL: 121 | matrix.setRotate(180); 122 | matrix.postScale(-1, 1); 123 | break; 124 | case ExifInterface.ORIENTATION_TRANSPOSE: 125 | matrix.setRotate(90); 126 | matrix.postScale(-1, 1); 127 | break; 128 | case ExifInterface.ORIENTATION_ROTATE_90: 129 | matrix.setRotate(90); 130 | break; 131 | case ExifInterface.ORIENTATION_TRANSVERSE: 132 | matrix.setRotate(-90); 133 | matrix.postScale(-1, 1); 134 | break; 135 | case ExifInterface.ORIENTATION_ROTATE_270: 136 | matrix.setRotate(-90); 137 | break; 138 | case ExifInterface.ORIENTATION_NORMAL: 139 | case ExifInterface.ORIENTATION_UNDEFINED: 140 | default: 141 | return bitmap; 142 | } 143 | 144 | try { 145 | Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); 146 | bitmap.recycle(); 147 | return oriented; 148 | } catch (OutOfMemoryError e) { 149 | e.printStackTrace(); 150 | return bitmap; 151 | } 152 | } catch (IOException e) { 153 | e.printStackTrace(); 154 | } 155 | return bitmap; 156 | } 157 | 158 | 159 | /** 160 | * Create a fullscreen image and punch a hole inside 161 | * 162 | * @param context some context 163 | * @param screenWidth the screen width 164 | * @param screenHeight the screen height 165 | * @param x x coordinate of the hole 166 | * @param y y coordinate of the hole 167 | * @param holeDiameter hole width 168 | * @param backgroundColor the background color to use 169 | * @return 170 | */ 171 | public static Bitmap punchARoundedHoleInABitmap(Context context, int screenWidth, int screenHeight, int x, int y, int holeDiameter, int backgroundColor) { 172 | Bitmap bitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888); 173 | Canvas canvas = new Canvas(bitmap); 174 | Paint paint = new Paint(); 175 | paint.setAntiAlias(true); 176 | canvas.drawColor(context.getResources().getColor(backgroundColor)); 177 | paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); 178 | canvas.drawCircle(x + holeDiameter / 2, y + holeDiameter / 2, holeDiameter / 2, paint); 179 | return bitmap; 180 | } 181 | 182 | 183 | // helper for normalizing image size 184 | private static Bitmap decodeBitmapWithClosestSampleSize(Context context, Uri theUri, int maxWidth, int maxHeight) { 185 | BitmapFactory.Options options = new BitmapFactory.Options(); 186 | 187 | AssetFileDescriptor fileDescriptor; 188 | try { 189 | fileDescriptor = context.getContentResolver().openAssetFileDescriptor(theUri, "r"); 190 | } catch (FileNotFoundException e) { 191 | e.printStackTrace(); 192 | return null; 193 | } 194 | 195 | options.inJustDecodeBounds = true; 196 | BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options); 197 | 198 | options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight); 199 | 200 | options.inJustDecodeBounds = false; 201 | 202 | return BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options); 203 | } 204 | 205 | // helper for normalizing image size 206 | private static Bitmap getImageResized(Context context, Uri selectedImage, int maxWidth, int maxHeight) { 207 | Bitmap bm = decodeBitmapWithClosestSampleSize(context, selectedImage, maxWidth, maxHeight); 208 | Bitmap resizedBmp = Bitmap.createScaledBitmap(bm, maxWidth, maxHeight, true); 209 | if (resizedBmp != bm) { 210 | bm.recycle(); 211 | } 212 | return resizedBmp; 213 | } 214 | 215 | // helper for normalizing image size 216 | private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 217 | // Raw height and width of image 218 | final int height = options.outHeight; 219 | final int width = options.outWidth; 220 | int inSampleSize = 1; 221 | 222 | if (height > reqHeight || width > reqWidth) { 223 | final int halfHeight = height / 2; 224 | final int halfWidth = width / 2; 225 | // Calculate the largest inSampleSize value that is a power of 2 and keeps both 226 | // height and width larger than the requested height and width. 227 | while ((halfHeight / inSampleSize) > reqHeight 228 | && (halfWidth / inSampleSize) > reqWidth) { 229 | inSampleSize *= 2; 230 | } 231 | } 232 | 233 | return inSampleSize; 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /androidutils/src/main/java/com/bytesizebit/androidutils/DateUtils.java: -------------------------------------------------------------------------------- 1 | package com.bytesizebit.androidutils; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | 6 | import java.text.DateFormat; 7 | import java.text.ParseException; 8 | import java.text.SimpleDateFormat; 9 | import java.util.Calendar; 10 | import java.util.Date; 11 | 12 | /*********** 13 | * Android Utils 14 | * Created by Shahar Barsheshet on 18/03/2015. 15 | * bytesizebit@gmail.com 16 | * www.bytesizebit.com 17 | ***********/ 18 | public class DateUtils { 19 | 20 | private DateUtils() { 21 | } 22 | 23 | @SuppressLint("SimpleDateFormat") 24 | public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 25 | 26 | public static final int TU_MILLISECONDS = 1; 27 | public static final int TU_SECONDS = 1000; 28 | public static final int TU_MINUTES = 60000; 29 | public static final int TU_HOURS = 3600000; 30 | public static final int TU_DAYS = 86400000; 31 | 32 | /** 33 | * Convert Date to string with long format 34 | * 35 | * @param context some context 36 | * @param date date to format 37 | * @return {@code String} formatted date 38 | */ 39 | public static String formatDateLong(Context context, Date date) { 40 | DateFormat dateFormat = android.text.format.DateFormat.getLongDateFormat(context); 41 | return dateFormat.format(date); 42 | } 43 | 44 | /** 45 | * Check if the date is less than 7 days from now 46 | * 47 | * @param date date to check 48 | * @return {@code true} if the date is less than 7 days 49 | */ 50 | private static boolean isLessThanOneWeek(Date date) { 51 | Calendar calendar = Calendar.getInstance(); 52 | calendar.add(Calendar.DAY_OF_MONTH, -6); 53 | return date.after(calendar.getTime()); 54 | } 55 | 56 | /** 57 | * Check if the specific date is today 58 | * 59 | * @param date date to check 60 | * @return {@code true} if the date is today 61 | */ 62 | public static boolean isToday(Date date) { 63 | return android.text.format.DateUtils.isToday(date.getTime()); 64 | } 65 | 66 | /** 67 | * Is the specific date yesterday 68 | * 69 | * @param date date to check 70 | * @return {@code true} if the date is yesterday 71 | */ 72 | public static boolean isYesterday(Date date) { 73 | Calendar calendar = Calendar.getInstance(); 74 | calendar.add(Calendar.DAY_OF_MONTH, -1); 75 | int nowYear = calendar.get(Calendar.YEAR); 76 | int nowMonth = calendar.get(Calendar.MONTH); 77 | int nowMonthDay = calendar.get(Calendar.DAY_OF_MONTH); 78 | 79 | calendar.setTimeInMillis(date.getTime()); 80 | int thenYear = calendar.get(Calendar.YEAR); 81 | int thenMonth = calendar.get(Calendar.MONTH); 82 | int thenMonthDay = calendar.get(Calendar.DAY_OF_MONTH); 83 | 84 | return (thenYear == nowYear) 85 | && (thenMonth == nowMonth) 86 | && (thenMonthDay == nowMonthDay); 87 | } 88 | 89 | /** 90 | * Check for a leap year 91 | * 92 | * @param year the year to check 93 | * @return {@code true} for a leap year 94 | */ 95 | public static boolean isLeapYear(int year) { 96 | return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 97 | } 98 | 99 | /** 100 | * return date string from milliseconds 101 | * 102 | * @param milliseconds time in millis 103 | * @return yyyy-MM-dd HH:mm:ss formatted string 104 | */ 105 | public static String millisecondsToString(long milliseconds) { 106 | return millisecondsToString(milliseconds, SIMPLE_DATE_FORMAT); 107 | } 108 | 109 | /** 110 | * return a date string from milliseconds with a specific date format 111 | * 112 | * @param milliseconds time in millis 113 | * @param dateFormat the format to use 114 | * @return date formatted string 115 | */ 116 | public static String millisecondsToString(long milliseconds, SimpleDateFormat dateFormat) { 117 | return dateFormat.format(new Date(milliseconds)); 118 | } 119 | 120 | /** 121 | * Create time in milliseconds from a formatted string 122 | * 123 | * @param formattedDate date string in format yyyy-MM-dd HH:mm:ss 124 | * @return time in milliseconds 125 | */ 126 | public static long stringToMilliseconds(String formattedDate) { 127 | return stringToMilliseconds(formattedDate, SIMPLE_DATE_FORMAT); 128 | } 129 | 130 | /** 131 | * Create time in milliseconds from a formatted string with specific date format 132 | * 133 | * @param formattedDate date string in format yyyy-MM-dd HH:mm:ss 134 | * @param dateFormat how to format the string 135 | * @return time in milliseconds 136 | */ 137 | public static long stringToMilliseconds(String formattedDate, SimpleDateFormat dateFormat) { 138 | try { 139 | return dateFormat.parse(formattedDate).getTime(); 140 | } catch (ParseException e) { 141 | e.printStackTrace(); 142 | } 143 | return -1; 144 | } 145 | 146 | /** 147 | * Create a date from formatted string 148 | * 149 | * @param formattedDate the formatted string 150 | * @return Date 151 | */ 152 | public static Date stringToDate(String formattedDate) { 153 | return stringToDate(formattedDate, SIMPLE_DATE_FORMAT); 154 | } 155 | 156 | /** 157 | * Create a date from formatted string with specific date format 158 | * 159 | * @param formattedDate string to convert 160 | * @param dateFormat 161 | * @return {@code Date} Date object from the string value 162 | */ 163 | public static Date stringToDate(String formattedDate, SimpleDateFormat dateFormat) { 164 | return new Date(stringToMilliseconds(formattedDate, dateFormat)); 165 | } 166 | 167 | /** 168 | * Create a formatted date 169 | * 170 | * @param date date to format 171 | * @return a yyyy-MM-dd HH:mm:ss formatted string 172 | */ 173 | public static String dateToString(Date date) { 174 | return dateToString(date, SIMPLE_DATE_FORMAT); 175 | } 176 | 177 | /** 178 | * Create a formatted date with specific date format 179 | * 180 | * @param date date to format 181 | * @param dateFormat the Date format to use 182 | * @return a date formatted string 183 | */ 184 | public static String dateToString(Date date, SimpleDateFormat dateFormat) { 185 | return dateFormat.format(date); 186 | } 187 | 188 | /** 189 | * Convert date object to milliseconds 190 | * 191 | * @param date object to convert 192 | * @return long 193 | */ 194 | public static long dateToMilliseconds(Date date) { 195 | return date.getTime(); 196 | } 197 | 198 | /** 199 | * Convert milliseconds to date object 200 | * 201 | * @param milliseconds time to use 202 | * @return Date 203 | */ 204 | public static Date millisecondsToDate(long milliseconds) { 205 | return new Date(milliseconds); 206 | } 207 | 208 | /** 209 | * Convert milliseconds to specific time unit 210 | * 211 | * @param milliseconds time in milliseconds 212 | * @param timeUnit time unit to use 213 | * @return long in Time Unit 214 | */ 215 | private static long millisecondsToTimeUnit(long milliseconds, int timeUnit) { 216 | switch (timeUnit) { 217 | case TU_MILLISECONDS: 218 | case TU_SECONDS: 219 | case TU_MINUTES: 220 | case TU_HOURS: 221 | case TU_DAYS: 222 | return Math.abs(milliseconds) / timeUnit; 223 | } 224 | return -1; 225 | } 226 | 227 | 228 | /** 229 | * Get current time in milliseconds 230 | * 231 | * @return long time in milliseconds 232 | */ 233 | public static long getCurrentTimeMillis() { 234 | return System.currentTimeMillis(); 235 | } 236 | 237 | /** 238 | * Get current time in formatted string 239 | * 240 | * @return a yyyy-MM-dd HH:mm:ss formatted string 241 | */ 242 | public static String getCurrentTimeString() { 243 | return millisecondsToString(getCurrentTimeMillis()); 244 | } 245 | 246 | /** 247 | * Get current time in formatted string with specific date format 248 | * 249 | * @param dateFormat the date format to use 250 | * @return String time in milliseconds 251 | */ 252 | public static String getCurrentTimeString(SimpleDateFormat dateFormat) { 253 | return millisecondsToString(getCurrentTimeMillis(), dateFormat); 254 | } 255 | 256 | /** 257 | * Get current time in date object 258 | * 259 | * @return a Date object with the current time 260 | */ 261 | public static Date getCurrentTimeDate() { 262 | return new Date(); 263 | } 264 | 265 | /** 266 | * Calculate time interval from now 267 | * 268 | * @param date date to compare 269 | * @param timeUnit time unit to get the result 270 | * @return long time in time unit 271 | */ 272 | public static long getTimeIntervalFromNow(Date date, int timeUnit) { 273 | return getTimeIntervalBetweenDates(getCurrentTimeDate(), date, timeUnit); 274 | } 275 | 276 | /** 277 | * Calculate time interval from now 278 | * 279 | * @param dateString date to compare 280 | * @param timeUnit time unit to get the result 281 | * @return long time in time unit 282 | */ 283 | public static long getTimeIntervalFromNow(String dateString, int timeUnit) { 284 | return getTimeIntervalFromNow(dateString, timeUnit, SIMPLE_DATE_FORMAT); 285 | } 286 | 287 | 288 | /** 289 | * Calculate time interval from now with specific format 290 | * 291 | * @param dateString date to compare 292 | * @param timeUnit time unit to get the result 293 | * @param dateFormat the format to use 294 | * @return long time in time unit 295 | */ 296 | public static long getTimeIntervalFromNow(String dateString, int timeUnit, SimpleDateFormat dateFormat) { 297 | return getTimeIntervalBetweenDates(getCurrentTimeString(), dateString, timeUnit, dateFormat); 298 | } 299 | 300 | /** 301 | * Calculate time interval between 2 dates 302 | * 303 | * @param dateString1 first date 304 | * @param dateString2 second date 305 | * @param timeUnit time unit to get the result 306 | * @return time in time unit 307 | */ 308 | public static long getTimeIntervalBetweenDates(String dateString1, String dateString2, int timeUnit) { 309 | return getTimeIntervalBetweenDates(dateString1, dateString2, timeUnit, SIMPLE_DATE_FORMAT); 310 | } 311 | 312 | /** 313 | * Calculate time interval between 2 dates with a specific date format 314 | * 315 | * @param dateString1 first date 316 | * @param dateString2 second date 317 | * @param timeUnit time unit to get the result 318 | * @param dateFormat the format used in the dates 319 | * @return {@code long} the time interval between two dates 320 | */ 321 | public static long getTimeIntervalBetweenDates(String dateString1, String dateString2, int timeUnit, SimpleDateFormat dateFormat) { 322 | return millisecondsToTimeUnit(stringToMilliseconds(dateString1, dateFormat) 323 | - stringToMilliseconds(dateString2, dateFormat), timeUnit); 324 | } 325 | 326 | /** 327 | * Calculate time interval between 2 dates 328 | * 329 | * @param date1 first date 330 | * @param date2 second date 331 | * @param timeUnit time unit to get the result 332 | * @return {@code long} the time interval between two dates 333 | */ 334 | public static long getTimeIntervalBetweenDates(Date date1, Date date2, int timeUnit) { 335 | return millisecondsToTimeUnit(dateToMilliseconds(date2) - dateToMilliseconds(date1), timeUnit); 336 | } 337 | } 338 | --------------------------------------------------------------------------------