Skip to content

Instantly share code, notes, and snippets.

@tbruyelle
Created December 30, 2013 15:07
Show Gist options
  • Save tbruyelle/8183155 to your computer and use it in GitHub Desktop.
Save tbruyelle/8183155 to your computer and use it in GitHub Desktop.
package com.comalia.gesicamobile.util;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.comalia.gesicamobile.BuildConfig;
import com.comalia.gesicamobile.Constants;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;
import timber.log.Timber;
public class AndroidUtils {
private static final String TEL_PREFIX = "tel:";
public static final char DOT = '.';
public static final char COMMA = ',';
public static NumberFormat NUMERFORMAT = NumberFormat.getInstance(Locale.getDefault());
static {
NUMERFORMAT.setMaximumFractionDigits(2);
NUMERFORMAT.setMinimumFractionDigits(2);
}
static Timber logger = BuildConfig.LOGGER;
public static double parsePrice(String price) {
try {
return Double.parseDouble(price.replace(COMMA, DOT).replaceAll("\\s", Constants.NO_VALUE));
} catch (RuntimeException e) {
logger.e(e, "Error while parsing price " + price, e);
return 0l;
}
}
public static String formatPrice(double price) {
return NUMERFORMAT.format(price);
}
public static int dpToPx(Context context, int dp) {
return (int) ((dp * context.getResources().getDisplayMetrics().density) + 0.5);
}
public static int pxToDp(Context context, int px) {
return (int) ((px / context.getResources().getDisplayMetrics().density) + 0.5);
}
public static void showKeyboard(InputMethodManager inputMethodManager) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
public static void hideKeyboard(InputMethodManager inputMethodManager) {
inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
// inputMethodManager.hideSoftInputFromWindow( editText.getWindowToken(), 0 );
}
public static boolean hasPhoneCapabilities(Context context) {
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
}
public static void callPhoneNumber(Context context, String phoneNumber) {
Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse(TEL_PREFIX + phoneNumber));
context.startActivity(dialIntent);
}
/**
* @return the views tagged by the tag in parameter
*/
public static ArrayList<View> findViewsByTag(ViewGroup root, String tag) {
ArrayList<View> views = new ArrayList<View>();
final int childCount = root.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = root.getChildAt(i);
if (child instanceof ViewGroup) {
views.addAll(findViewsByTag((ViewGroup) child, tag));
}
final Object tagObj = child.getTag();
if (tagObj != null && tagObj.equals(tag)) {
views.add(child);
}
}
return views;
}
public static String urlEncode(String data) {
try {
return URLEncoder.encode(data, Constants.UTF_8);
} catch (UnsupportedEncodingException e) {
logger.e("Error while encoding " + data);
return data;
}
}
public static void launchBrowser(final Context context, String url) {
if (context == null) {
return;
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
}
/**
* Handy method for converting ISO-8859-1 to unicode
* while apache server's still in ISO
*/
public static String fixEncoding(String str) {
try {
str = new String(str.getBytes(Constants.ISO_8859_1));
} catch (UnsupportedEncodingException e) {
logger.e(e, "UnsupportedEncodingException for " + str);
}
return str;
}
/**
* @return true if current thread is the main thread
*/
public static boolean inMainThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
public static String getRawResourceContent(Resources resources, int rawId)
throws IOException {
InputStream is = resources.openRawResource(rawId);
InputStreamReader isr = new InputStreamReader(is, Charset.forName(Constants.UTF_8));
// We guarantee that the available method returns the total
// size of the asset... of course, this does mean that a single
// asset can't be more than 2 gigs.
int size = is.available();
// Read the entire asset into a local byte buffer.
char[] buffer = new char[size];
isr.read(buffer);
isr.close();
is.close();
// Convert the buffer into a string.
return new String(buffer);
}
/**
* @return return the dimension value of an attribute
*/
public static float getAttrDimention(Context context, int attr) {
TypedValue tv = new TypedValue();
if (!context.getTheme().resolveAttribute(attr, tv, true)) {
throw new RuntimeException("Attribute " + attr + " not found");
}
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
return tv.getDimension(metrics);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment