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 |
--------------------------------------------------------------------------------