Skip to content

Instantly share code, notes, and snippets.

@Folyd
Last active September 15, 2015 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Folyd/72438e5c8ca52ba556d1 to your computer and use it in GitHub Desktop.
Save Folyd/72438e5c8ca52ba556d1 to your computer and use it in GitHub Desktop.
Common Utility class
public class Utils {
/**
* To record the user click time.
*/
private static long sLastClickTime = 0L;
/**
* Get device unique identify.
*
* @param context
* @return
*/
public static String getDeviceId(Context context) {
String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
// If android_id is null , then use serial number.
if (androidId == null) {
androidId = android.os.Build.SERIAL;
}
return androidId;
}
/**
* Get channel from META-INF directory.
*
* @param context
* @return the channel name if success,otherwise return "none"
*/
public static String getChannel(Context context) {
ApplicationInfo appinfo = context.getApplicationInfo();
String sourceDir = appinfo.sourceDir;
String ret = "";
ZipFile zipfile = null;
try {
zipfile = new ZipFile(sourceDir);
Enumeration<?> entries = zipfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String entryName = entry.getName();
if (entryName.startsWith("META-INF/channel")) {
ret = entryName;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zipfile != null) {
try {
zipfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] split = ret.split("_");
if (split != null && split.length >= 2) {
return ret.substring(split[0].length() + 1);
} else {
return "none";
}
}
/**
* Determine if the device is a tablet (i.e. it has a large screen).
*
* @param context
* @return
*/
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
/**
* Hide input method.
*
* @param activity
*/
public static void hideInputMethod(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity
.getSystemService(Context.INPUT_METHOD_SERVICE);
View currentFocus = activity.getCurrentFocus();
if (currentFocus != null) {
imm.hideSoftInputFromWindow(currentFocus.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
public static void showInputMethod(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity
.getSystemService(Context.INPUT_METHOD_SERVICE);
View currentFocus = activity.getCurrentFocus();
if (currentFocus != null) {
imm.hideSoftInputFromWindow(currentFocus.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
imm.showSoftInput(currentFocus, InputMethodManager.SHOW_IMPLICIT);
}
}
/**
* This method converts dp unit to equivalent pixels, depending on device
* density.
*
* @param dp A value in dp (density independent pixels) unit. Which we need
* to convert into pixels
* @param context Context to get resources and device specific display metrics
* @return A float value to represent px equivalent to dp depending on
* device density
*/
public static float convertDpToPixel(float dp, Context context) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return px;
}
/**
* This method converts device specific pixels to density independent
* pixels.
*
* @param px A value in px (pixels) unit. Which we need to convert into db
* @param context Context to get resources and device specific display metrics
* @return A float value to represent dp equivalent to px value
*/
public static float convertPixelsToDp(float px, Context context) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return dp;
}
/**
* @param context
* @return return screen width px unit.
*/
public static int getScreenWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.x;
}
/**
* @param context
* @return return screen height px unit.
*/
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.y;
}
public static int getScreenMinWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return Math.min(size.x, size.y);
}
/**
* @param context
* @param drawableArraysId
* @return
*/
public static int[] getDrawableIdsArray(Context context, @IdRes int drawableArraysId) {
TypedArray ta = context.getResources().obtainTypedArray(drawableArraysId);
int count = ta.length();
int[] ids = new int[count];
for (int i = 0; i < count; i++) {
ids[i] = ta.getResourceId(i, 0);
}
ta.recycle();
return ids;
}
/**
* Checked the network connect status.
*
* @return
*/
public static boolean isNetworkConnected(Context context) {
if (context == null) {
return false;
}
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
/**
* Check WIFI connection.
*
* @param context
* @return
*/
public static boolean isWifiConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null && ConnectivityManager.TYPE_WIFI == info.getType());
}
/**
* @param text
* @param color
* @param start
* @param end
* @return
*/
public static SpannableString highLight(CharSequence text, int color, int start, int end) {
SpannableString span = new SpannableString(text);
span.setSpan(new ForegroundColorSpan(color), start, end,
SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
return span;
}
public static SpannableString stylePartTextBold(CharSequence text, int start, int end) {
SpannableString span = new SpannableString(text);
span.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, end,
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return span;
}
public static int getRemainDays(long timeSecond) {
long remainSecond = timeSecond - System.currentTimeMillis() / 1000;
long daySecond = 60 * 60 * 24;
return (int) (remainSecond / daySecond);
}
/**
* Get application version number.
*
* @param context
* @return
*/
public static int getAppVersion(Context context) {
try {
PackageInfo info = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return info.versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return 1;
}
public static String getAppVersionName(Context context) {
String versionName = "1.0";
try {
PackageInfo info = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
versionName = info.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
public static int getStatusBarHeight(Context context) {
Class<?> c;
Object obj;
Field field;
int x, statusBarHeight = 0;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return statusBarHeight;
}
/**
* Get ActionBar size.
*
* @param context
* @return
*/
public static int getActionBarSize(Context context) {
int actionBarSize = 0;
TypedValue tv = new TypedValue();
if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
actionBarSize = TypedValue.complexToDimensionPixelSize(tv.data,
context.getResources().getDisplayMetrics());
}
return actionBarSize;
}
public static boolean isEmailLegal(String email) {
if (TextUtils.isEmpty(email)) return false;
final String REGEXP = "^([a-z0-9\\-_.+]+)@([a-z0-9\\-]+[.][a-z0-9\\-.]+)$";
Pattern p = Pattern.compile(REGEXP);
Matcher m = p.matcher(email.toLowerCase());
return m.matches();
}
public static boolean isCollectionEmpty(Collection<?> collection) {
return collection == null || collection.size() == 0;
}
public static boolean isArrayEmpty(Object[] array) {
return array == null || array.length == 0;
}
/**
* Judge whether the user is deliberately fast clicking. Because if the user
* fast click a button or list item, application will process too much
* unnecessary transaction in short time and may cause to some unexpected
* exception.
* <p/>
* <br/>
* <br/>
* The definition of fast click is: the user click a view,button or list
* item in 800 millisecond.
*
* @return
*/
public static boolean isFastClick() {
return isFastClick(800);
}
public static boolean isFastClick(long space) {
long time = System.currentTimeMillis();
if (time - sLastClickTime < space) {
return true;
}
sLastClickTime = time;
return false;
}
public static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length);
String temp;
for (int i = 0; i < bytes.length; i++) {
temp = Integer.toHexString(0xFF & bytes[i]);
if (temp.length() < 2)
sb.append(0);
sb.append(temp.toUpperCase()).append(" ");
}
return sb.toString();
}
public static String bytesToString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length);
for (int i = 0; i < bytes.length; i++) {
sb.append(String.valueOf(bytes[i])).append(" ");
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment