Last active
September 8, 2015 04:13
-
-
Save lidemin/133f51a411891d75f143 to your computer and use it in GitHub Desktop.
Android Utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.damon.android; | |
/** | |
* Created by damon on 7/2/15. | |
*/ | |
import android.content.Context; | |
import java.io.Serializable; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* This DLAppSession class is created for persistence some simple data objects.<br/> | |
* This class will be init inside of Android Application subclass.<br/> | |
* It can persistence some simple data objects during Android Application lifecycle.<br/> | |
* <br/> | |
* It can persistence 2 type of data. <br/> | |
* <tr/>1. Data is valid along with Android Application. --Data will be cleared after app been | |
* killed. | |
* <tr/>2. Data is valid all the time. --Data will be stored in SharedPreference. | |
* <br/> | |
* <br/> | |
* <br/> | |
* - TBD<br/> | |
* - 1. Now just return the data object. If we need we can return the data object with last | |
* update timestamp. | |
* <p/> | |
* | |
* @author Damon | |
*/ | |
@SuppressWarnings("unused") | |
public class DLAppSession { | |
/** | |
* Constant String representing class name for logs. | |
*/ | |
protected String _tag = ((Object) this).getClass().getSimpleName(); | |
private static DLAppSession _self; | |
private Context _context; | |
private Map<String, DLCacheValue> _cacheValueMap; | |
private DLAppSession(Context context) { | |
this._context = context.getApplicationContext(); | |
_cacheValueMap = new HashMap<String, DLCacheValue>(); | |
} | |
/** | |
* Retrieve Singleton object of DLAppSession. | |
* | |
* @param context of the application. | |
* @return DLAppSession object | |
*/ | |
public static DLAppSession getInstance(Context context) { | |
if (_self == null) { | |
_self = new DLAppSession(context); | |
} | |
return _self; | |
} | |
/** | |
* Cache data object with specific key value. | |
* | |
* @param key the key of the cached value | |
* @param obj the real object which we need to cache. | |
* @param timeExpiry set the cached value expiry time | |
* @param flagPersistence if it is true data object will be persisted both map | |
* and shared preference | |
* @param constraint the constraint string | |
* @return result. true is success and false is failed. | |
*/ | |
public boolean cacheValue(String key, Object obj, long timeExpiry, | |
Boolean flagPersistence, String constraint) { | |
if (obj == null) { | |
//clear value | |
return DLSharedPreference.saveObjectToSharedPreference(_context, key, null); | |
} | |
DLCacheValue value = new DLCacheValue(key, obj, timeExpiry, flagPersistence, constraint); | |
if (flagPersistence) { | |
if (obj instanceof Serializable) { | |
return DLSharedPreference.saveObjectToSharedPreference(_context, key, value); | |
} else { | |
DLLogger.e(_tag, "Object[" + obj.getClass().getName() + "] is not serializable. " + | |
"Not support to store it into SharedPreference"); | |
return false; | |
} | |
} else { | |
_cacheValueMap.put(key, value); | |
return true; | |
} | |
} | |
/** | |
* Cache data object with specific key value. | |
* | |
* @param key is the key of that object value | |
* @param obj is the object | |
* @param timeExpiry expiry time of object | |
* @param flagPersistence tells if object should be saved in | |
* SharedPreference (persistent memory) | |
* @return retrieved object from Session or SharedPreference | |
*/ | |
public boolean cacheValue(String key, Object obj, long timeExpiry, Boolean flagPersistence) { | |
return cacheValue(key, obj, timeExpiry, flagPersistence, null); | |
} | |
/** | |
* Cache data object with specific key value. | |
* | |
* @param key is the key of that object value | |
* @param obj is the object | |
* @param timeExpiry expiry time of object | |
* @return retrieved object from Session or SharedPreference | |
*/ | |
public boolean cacheValue(String key, Object obj, long timeExpiry) { | |
return cacheValue(key, obj, timeExpiry, false); | |
} | |
/** | |
* Cache data object with specific key value. | |
* | |
* @param key is the key of that object value | |
* @param obj is the object | |
* @param flagPersistence tells if object should be saved in | |
* SharedPreference (persistent memory) | |
* @return retrieved object from Session or SharedPreference | |
*/ | |
public boolean cacheValue(String key, Object obj, boolean flagPersistence) { | |
return cacheValue(key, obj, 0, flagPersistence); | |
} | |
/** | |
* Cache data object with specific key value. | |
* | |
* @param key is the key of that object value | |
* @param obj is the object | |
* @return retrieved object from Session or SharedPreference | |
*/ | |
public boolean cacheValue(String key, Object obj) { | |
return cacheValue(key, obj, 0, false); | |
} | |
/** | |
* Clear the cached value with provided key, both from Session and SharedPreference. | |
* | |
* @param key is the key of that object value | |
*/ | |
public void clearCacheValue(String key) { | |
cacheValue(key, null, true); | |
_cacheValueMap.remove(key); | |
} | |
/** | |
* Clear all the cached values, both from Session and SharedPreference. | |
*/ | |
public void clearAll() { | |
_cacheValueMap = new HashMap<String, DLCacheValue>(); | |
DLSharedPreference.clearSharedPreference(_context); | |
} | |
/** | |
* Retrieve cached data object from DLAppSession. | |
* | |
* @param key is the key of that object value | |
* @param constraint namespace or pool of DLCacheValue | |
* @param type class of object for type casting | |
* @param <T> the object type | |
* @return retrieved object from Session or SharedPreference | |
*/ | |
public <T extends Object> T getCachedValue(String key, String constraint, Class<T> type) { | |
DLCacheValue value; | |
if (_cacheValueMap.containsKey(key)) { | |
//hit in cache map | |
value = _cacheValueMap.get(key); | |
} else { | |
//try to hit in SharedPreference | |
value = DLSharedPreference.retrieveObjectFromSharedPreference(_context, key, | |
DLCacheValue.class); | |
} | |
if (value == null || value.isExpired() || !value.isValid(constraint)) { | |
return null; | |
} | |
Object obj = value.getObj(); | |
if (obj != null && obj.getClass().getName().equals(type.getName())) { | |
return type.cast(obj); | |
} | |
return null; | |
} | |
/** | |
* Retrieve cached data object from DLAppSession. | |
* | |
* @param key is the key of that object value | |
* @param type class of object for type casting | |
* @param <T> the object type | |
* @return retrieved object from Session or SharedPreference | |
*/ | |
public <T extends Object> T getCachedValue(String key, Class<T> type) { | |
return getCachedValue(key, null, type); | |
} | |
/** | |
* Retrieve cached data ArrayList from DLAppSession. | |
* | |
* @param key is the key of that object value | |
* @param type class of object for type casting | |
* @param <T> the object type | |
* @return retrieved ArrayList from Session or SharedPreference | |
*/ | |
public <T extends Object> ArrayList<T> getCachedList(String key, Class<T> type) { | |
if (_cacheValueMap.containsKey(key)) { | |
//hit in cache map | |
DLCacheValue value = _cacheValueMap.get(key); | |
if (value.isExpired()) { | |
return null; | |
} | |
Object obj = value.getObj(); | |
if (obj != null && obj instanceof ArrayList) { | |
//cast to generic type ArrayList | |
ArrayList<T> castObject = (ArrayList<T>) obj; | |
//check type | |
if (castObject != null && castObject.size() > 0 | |
&& castObject.get(0).getClass() == type) { | |
return castObject; | |
} | |
} | |
} else { | |
//try to hit in SharedPreference | |
return DLSharedPreference.retrieveArrayListFromSharedPreference(_context, key, type); | |
} | |
return null; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.Serializable; | |
/** | |
* DL Cache Value is a data object that holds data to be stored in Session or SharedPreference. | |
* All cache objects in Session or SharedPreference must be of type DLCacheValue. | |
* | |
* @author Damon | |
*/ | |
@SuppressWarnings("unused") | |
public class DLCacheValue implements Serializable { | |
private static final long serialVersionUID = 2164077113668197178L; | |
private String _key; | |
private Object _obj; | |
private long _timeStamp; | |
//if time for expiry is less than 0 | |
//then no need to check expiry | |
private long _timeExpiry; | |
private boolean _flagPersistence; | |
private String _constraint; | |
private DLCacheValue(String key, Object obj, boolean flagPersistence) { | |
this(key, obj, 0, flagPersistence); | |
} | |
/** | |
* Creates new DLCacheValue object with following parameters. | |
* | |
* @param key is the key of that object value | |
* @param obj is the object | |
* @param timeExpiry expiry time of object | |
* @param flagPersistence tells if object should be saved in | |
* SharedPreference (persistent memory) | |
* @param constraint namespace or pool of DLCacheValue | |
*/ | |
public DLCacheValue(String key, Object obj, | |
long timeExpiry, boolean flagPersistence, String constraint) { | |
this._key = key; | |
this._obj = obj; | |
this._flagPersistence = flagPersistence; | |
this._timeExpiry = timeExpiry; | |
this._timeStamp = System.currentTimeMillis(); | |
this._constraint = constraint; | |
} | |
/** | |
* Creates new DLCacheValue object with following parameters. | |
* | |
* @param key is the key of that object value | |
* @param obj is the object | |
* @param timeExpiry expiry time of object | |
* @param flagPersistence tells if object should be saved in | |
* SharedPreference (persistent memory) | |
*/ | |
public DLCacheValue(String key, Object obj, | |
long timeExpiry, boolean flagPersistence) { | |
this(key, obj, timeExpiry, flagPersistence, null); | |
} | |
/** | |
* check the cache value whether it is expired. | |
* | |
* @return true if object is expired | |
*/ | |
public boolean isExpired() { | |
if (_timeExpiry > 0) { | |
long now = System.currentTimeMillis(); | |
return (now - _timeStamp > _timeExpiry); | |
} else { | |
return false; | |
} | |
} | |
/** | |
* Verify if object belongs to the right constraint. | |
* | |
* @param constraint namespace or pool of DLCacheValue | |
* @return true if object is valid | |
*/ | |
public boolean isValid(String constraint) { | |
if(_constraint == null){ | |
return true; | |
} | |
if (this._constraint == null && constraint == null) { | |
return true; | |
} | |
if (constraint == null) { | |
return false; | |
} | |
return (this._constraint.equals(constraint)); | |
} | |
/** | |
* @return DLCacheValue object | |
*/ | |
public Object getObj() { | |
return _obj; | |
} | |
@Override | |
public String toString() { | |
return "\nDLCacheValue{" + | |
"\n\t_key='" + _key + '\'' + | |
", \n\t_obj=" + _obj + | |
", \n\t_timeStamp=" + _timeStamp + | |
", \n\t_timeExpiry=" + _timeExpiry + | |
", \n\t_flagPersistence=" + _flagPersistence + | |
", \n\t_constraint='" + _constraint + '\'' + | |
"\n}"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Date Util class holds static utility methods specific to Date and Time manipulation | |
* that can be used across multiple projects. | |
* | |
* @author Damon | |
*/ | |
@SuppressWarnings("unused") | |
public class DLDateUtil { | |
public static final String SECONDS_AGO = " seconds ago"; | |
public static final String MINUTES_AGO = " minutes ago"; | |
public static final String HOURS_AGO = " hours ago"; | |
public static final String DAYS_AGO = " days ago"; | |
/** | |
* Change the date format. | |
* | |
* @param date Date object | |
* @param format Date format | |
* @return The changed date as string | |
*/ | |
public static String formatDate(Date date, String format) { | |
String dateStr = ""; | |
if (date != null) { | |
try { | |
DateFormat df = new DateFormat(); | |
dateStr = df.format(format, date).toString(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
return dateStr; | |
} | |
/** | |
* Get the current date/time in a specific format. | |
* | |
* @param format Date format | |
* @return Current date and time in specified format as string | |
*/ | |
public static String getCurrentDateAndTime(String format) { | |
String currentDateAndTime = ""; | |
try { | |
SimpleDateFormat sdf = new SimpleDateFormat(format); | |
currentDateAndTime = sdf.format(new Date()); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return currentDateAndTime; | |
} | |
/** | |
* Returns relative time difference in string format. | |
* | |
* @param date Date object | |
* @return String expressing relative time difference. | |
* | |
* @see #getTimeDifferenceAsString(java.util.Date, String, String, String, String) | |
*/ | |
public static String getTimeDifferenceAsString(Date date) { | |
return getTimeDifferenceAsString(date, SECONDS_AGO, MINUTES_AGO, HOURS_AGO, DAYS_AGO); | |
} | |
/** | |
* Returns relative time difference in string format. | |
* | |
* <p>Expected output:</p> | |
* <ol> | |
* <li>x seconds ago</li> | |
* <li>x minutes ago</li> | |
* <li>x hours ago</li> | |
* <li>x days ago</li> | |
* </ol> | |
* | |
* @param date Date object | |
* @param secsAgo Override default {@link #SECONDS_AGO} string. | |
* @param minsAgo Override default {@link #MINUTES_AGO} string. | |
* @param hoursAgo Override default {@link #HOURS_AGO} string. | |
* @param daysAgo Override default {@link #DAYS_AGO} string. | |
* @return String expressing relative time difference. | |
*/ | |
public static String getTimeDifferenceAsString(Date date, String secsAgo, String minsAgo, | |
String hoursAgo, String daysAgo) { | |
Date currentDate = new Date(); | |
//in milliseconds | |
long diff = currentDate.getTime() - date.getTime(); | |
long diffSeconds = diff / 1000; | |
long diffMinutes = diff / (60 * 1000); | |
long diffHours = diff / (60 * 60 * 1000); | |
long diffDays = diff / (24 * 60 * 60 * 1000); | |
if (diffSeconds < 0) | |
return "0" + secsAgo; | |
if (diffSeconds > 60) { | |
if (diffMinutes > 60) { | |
if (diffHours > 24) { | |
return diffDays + daysAgo; | |
} else { | |
return diffHours + hoursAgo; | |
} | |
} else { | |
return diffMinutes + minsAgo; | |
} | |
} else { | |
return diffSeconds + secsAgo; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.annotation.TargetApi; | |
import android.content.Context; | |
import android.content.pm.PackageInfo; | |
import android.content.pm.PackageManager; | |
import android.graphics.Point; | |
import android.location.Location; | |
import android.location.LocationManager; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
import android.os.Build; | |
import android.os.Environment; | |
import android.telephony.TelephonyManager; | |
import android.view.Display; | |
import android.view.WindowManager; | |
import org.apache.http.conn.util.InetAddressUtils; | |
import java.net.InetAddress; | |
import java.net.NetworkInterface; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.UUID; | |
@SuppressWarnings("unused") | |
public class DLDeviceUtil { | |
/** Value - {@value}, Tag for Log output.*/ | |
public static final String TAG = "DLDeviceUtil"; | |
/** Value - {@value}, Constant for first available wireless lan hardware.*/ | |
public static final String WLAN0 = "wlan0"; | |
/** Value - {@value}, Constant for first available wireless lan hardware.*/ | |
public static final String ETH0 = "eth0"; | |
/** | |
* Returns MAC Address of wireless lan of the device. | |
* | |
* @return String format MAC Address or empty string. | |
* @see com.tigerspike.android.commons.DLDeviceUtil#WLAN0 | |
* @see com.tigerspike.android.commons.DLDeviceUtil#getMACAddress(String) | |
*/ | |
public static String getMACAddressWLan() { | |
return getMACAddress(WLAN0); | |
} | |
/** | |
* Returns MAC Address of ethernet of the device. | |
* | |
* @return String format MAC Address or empty string. | |
* @see com.tigerspike.android.commons.DLDeviceUtil#ETH0 | |
* @see com.tigerspike.android.commons.DLDeviceUtil#getMACAddress(String) | |
*/ | |
public static String getMACAddressEthernet() { | |
return getMACAddress(ETH0); | |
} | |
/** | |
* Returns MAC Address device's hardware interface. | |
* | |
* The parameter takes the interface name and MAC Address of particular interface is obtained. | |
* If null or empty value is provided, it will get the first interface that is connected to | |
* the internet. | |
* | |
* @param interfaceName Provide {@link com.tigerspike.android.commons.DLDeviceUtil#ETH0}, | |
* {@link com.tigerspike.android.commons.DLDeviceUtil#WLAN0} or NULL | |
* to use first available interface | |
* @return String format MAC Address or empty string | |
*/ | |
public static String getMACAddress(String interfaceName) { | |
String macAddress = ""; | |
try { | |
List<NetworkInterface> interfaces = Collections.list( | |
NetworkInterface.getNetworkInterfaces()); | |
for (NetworkInterface networkInterface : interfaces) { | |
if (interfaceName != null) { | |
if (!networkInterface.getName().equalsIgnoreCase(interfaceName)) { | |
continue; | |
} | |
} | |
byte[] mac = networkInterface.getHardwareAddress(); | |
if (mac != null) { | |
StringBuilder buf = new StringBuilder(); | |
for (byte aMac : mac) { | |
buf.append(String.format("%02X:", aMac)); | |
} | |
if (buf.length() > 0) { | |
buf.deleteCharAt(buf.length() - 1); | |
} | |
macAddress = buf.toString(); | |
} | |
} | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
return macAddress; | |
} | |
/** | |
* Returns IP(v4) Address of the device. | |
* | |
* @return String format IP v4 Address. | |
*/ | |
public static String getIPAddress() { | |
return getIPAddress(true); | |
} | |
/** | |
* Returns IP Address of the device. | |
* | |
* Provides IP address from first non-localhost interface, IP v4 or v6 can be obtained by | |
* passing the boolean parameter. | |
* | |
* See discussion on <a target="_blank" | |
* href="http://stackoverflow.com/questions/6064510/how-to-get-ip-address-of-the-device"> | |
* Stack Overflow</a> about how to get IP Address correctly across all Android devices. | |
* | |
* | |
* @param useIPv4 Returns IP v4 if passed true else IP v6 | |
* @return IP Address or empty string. | |
*/ | |
public static String getIPAddress(boolean useIPv4) { | |
String stringAddress = ""; | |
try { | |
List<NetworkInterface> interfaces = Collections.list( | |
NetworkInterface.getNetworkInterfaces()); | |
for (NetworkInterface networkInterface : interfaces) { | |
List<InetAddress> iNetAddresses = Collections.list( | |
networkInterface.getInetAddresses()); | |
for (InetAddress iNetAddress : iNetAddresses) { | |
if (!iNetAddress.isLoopbackAddress()) { | |
stringAddress = iNetAddress.getHostAddress().toUpperCase(); | |
boolean isIPv4 = InetAddressUtils.isIPv4Address(stringAddress); | |
if (useIPv4) { | |
if (isIPv4) { | |
return stringAddress; | |
} | |
} else { | |
if (!isIPv4) { | |
int delimiter = stringAddress.indexOf('%'); // drop ip6 port suffix | |
return (delimiter < 0 ? stringAddress : | |
stringAddress.substring(0, delimiter)); | |
} | |
} | |
} | |
} | |
} | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
return stringAddress; | |
} | |
/** | |
* Check network connectivity status of the device using {@link android.net.ConnectivityManager} | |
* and {@link android.net.NetworkInfo}. | |
* | |
* @param context Provide context of the application. | |
* @return true if connected to the internet. | |
*/ | |
public static boolean isNetworkConnected(Context context) { | |
boolean status = false; | |
try { | |
ConnectivityManager cm = (ConnectivityManager) context.getSystemService( | |
Context.CONNECTIVITY_SERVICE); | |
NetworkInfo netInfo = cm.getNetworkInfo(0); | |
if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) { | |
status = true; | |
} else { | |
netInfo = cm.getNetworkInfo(1); | |
if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) { | |
status = true; | |
} | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return false; | |
} | |
return status; | |
} | |
/** | |
* Returns device's unique id using {@link android.telephony.TelephonyManager}. | |
* | |
* See discussion on | |
* <a target="_blank" href="http://stackoverflow.com/a/2853253/2534207">Stack Overflow</a> | |
* about how to get Device Id correctly across all Android devices. | |
* | |
* | |
* @param context Provide context of the application. | |
* @return Device's id in String format. | |
*/ | |
public static String getDeviceId(Context context) { | |
final TelephonyManager tm = (TelephonyManager) context.getSystemService( | |
Context.TELEPHONY_SERVICE); | |
final String tmDevice, tmSerial, androidId; | |
tmDevice = "" + tm.getDeviceId(); | |
tmSerial = "" + tm.getSimSerialNumber(); | |
androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), | |
android.provider.Settings.Secure.ANDROID_ID); | |
UUID deviceUuid = new UUID(androidId.hashCode(), | |
((long) tmDevice.hashCode() << 32) | tmSerial.hashCode()); | |
return deviceUuid.toString(); | |
} | |
/** | |
* Returns width of device in pixels. | |
* | |
* @param context Provide context of the application. | |
* @return Width of the device. | |
*/ | |
@SuppressWarnings("deprecation") | |
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) | |
public static int getDeviceWidth(Context context) { | |
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); | |
Display display = wm.getDefaultDisplay(); | |
int width; | |
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { | |
width = display.getWidth(); // deprecated | |
} else { | |
Point size = new Point(); | |
display.getSize(size); | |
width = size.x; | |
} | |
return width; | |
} | |
/** | |
* Returns height of device in pixels. | |
* | |
* @param context Provide context of the application. | |
* @return Height of the device. | |
*/ | |
@SuppressWarnings("deprecation") | |
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) | |
public static int getDeviceHeight(Context context) { | |
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); | |
Display display = wm.getDefaultDisplay(); | |
int height; | |
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { | |
height = display.getHeight(); // deprecated | |
} else { | |
Point size = new Point(); | |
display.getSize(size); | |
height = size.y; | |
} | |
return height; | |
} | |
/** | |
* Returns version code of the Application using {@link android.content.pm.PackageManager}. | |
* | |
* @param context Context of the application. | |
* @return Version code of the Application. | |
*/ | |
public static int getAppVersion(Context context) { | |
try { | |
PackageInfo packageInfo = context.getPackageManager().getPackageInfo( | |
context.getPackageName(), 0); | |
return packageInfo.versionCode; | |
} catch (PackageManager.NameNotFoundException e) { | |
// should never happen | |
throw new RuntimeException("Could not get package name: " + e); | |
} | |
} | |
/** | |
* Returns last known location of device using {@link android.location.LocationManager}. | |
* | |
* @param context Context of the application | |
* @return {@link android.location.Location} object. | |
*/ | |
public static Location getLastKnownLocation(Context context) { | |
LocationManager locationManager = (LocationManager) context.getApplicationContext() | |
.getSystemService(Context.LOCATION_SERVICE); | |
List<String> providers = locationManager.getProviders(true); | |
Location bestLocation = null; | |
for (String provider : providers) { | |
Location l = locationManager.getLastKnownLocation(provider); | |
if (l == null) { | |
continue; | |
} | |
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) { | |
bestLocation = l; | |
} | |
} | |
if (bestLocation == null) { | |
return null; | |
} | |
return bestLocation; | |
} | |
/** | |
* Returns Manufacturer and Model name as String using {@link android.os.Build}. | |
* Get device's Manufacturer and Model name as String. | |
* | |
* @return {@link android.os.Build#MANUFACTURER} and {@link android.os.Build#MODEL}. | |
*/ | |
public static String getDeviceName() { | |
String manufacturer = Build.MANUFACTURER; | |
String model = Build.MODEL; | |
if (model.startsWith(manufacturer)) { | |
return DLUtil.capitalize(model); | |
} else { | |
return DLUtil.capitalize(manufacturer) + " " + model; | |
} | |
} | |
/** | |
* @return true if external storage state is readable. | |
*/ | |
public boolean isExternalStorageReadable() { | |
String state = Environment.getExternalStorageState(); | |
if (Environment.MEDIA_MOUNTED.equals(state) || | |
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { | |
return true; | |
} | |
return false; | |
} | |
/** | |
* @return true if external storage state is writable. | |
*/ | |
public boolean isExternalStorageWritable() { | |
String state = Environment.getExternalStorageState(); | |
if (Environment.MEDIA_MOUNTED.equals(state)) { | |
return true; | |
} | |
return false; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DLTypefaceHelper { | |
private static final String TAG="DLTypefaceHelper"; | |
//using map to cache the typeface for avoiding memory leak | |
public static final HashMap<String, Typeface> fontMap = new HashMap<String, Typeface>(); | |
public static void applyFont(Context context, String font, TextView... textViews){ | |
if(context == null || textViews == null || font == null) { | |
return; | |
} | |
Typeface typeface = null; | |
if(fontMap.containsKey(font)){ | |
typeface = fontMap.get(font); | |
}else{ | |
try { | |
typeface = Typeface.createFromAsset(context.getAssets(), "fonts/" + font); | |
}catch (Exception e){ | |
e.printStackTrace(); | |
Log.e(TAG, "Could not create font "+font+" from assets/fonts folder"); | |
} | |
if(typeface == null){ | |
Log.e(TAG, "Could not find font "+font+" from assets/fonts folder"); | |
return; | |
} | |
fontMap.put(font, typeface); | |
} | |
for (TextView textView : textViews) { | |
if(textView != null) { | |
textView.setTypeface(typeface); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.ContentValues; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.database.Cursor; | |
import android.graphics.Bitmap; | |
import android.net.Uri; | |
import android.provider.MediaStore; | |
import android.util.Log; | |
import java.io.BufferedInputStream; | |
import java.io.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.FileInputStream; | |
import java.io.FileNotFoundException; | |
import java.io.IOException; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.OptionalDataException; | |
import java.io.OutputStream; | |
import java.io.Serializable; | |
import java.io.UnsupportedEncodingException; | |
import java.net.URLEncoder; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
@SuppressWarnings("unused") | |
public class DLUtil { | |
/** Value - {@value}, Tag for Log output.*/ | |
public static final String TAG = "DLUtil"; | |
/** Value - {@value}, output buffer size.*/ | |
public static final int BUFLEN = 1024; | |
/** Value - {@value}, key for message digest algorithm.*/ | |
public static final String SHA_256 = "SHA-256"; | |
/** Value - {@value}, key for UTF charset name.*/ | |
public static final String UTF_8 = "UTF-8"; | |
/** Value - {@value}, key for ISO charset name.*/ | |
public static final String ISO_8859_1 = "ISO-8859-1"; | |
/** | |
* Returns hex string of provided byte array. | |
* | |
* @param bytes Provided byte array. | |
* @return Resulted hex String after conversion. | |
*/ | |
public static String bytesToHex(byte[] bytes) { | |
StringBuilder stringBuilder = new StringBuilder(); | |
for (byte aByte : bytes) { | |
int intVal = aByte & 0xff; | |
if (intVal < 0x10) { | |
stringBuilder.append("0"); | |
} | |
stringBuilder.append(Integer.toHexString(intVal).toUpperCase()); | |
} | |
return stringBuilder.toString(); | |
} | |
/** | |
* Returns utf8 byte array of provided String. | |
* | |
* @param string Base String to be converted to bytes. | |
* @return Array of NULL if error was found | |
*/ | |
public static byte[] getUTF8Bytes(String string) { | |
try { | |
return string.getBytes(UTF_8); | |
} catch (Exception ex) { | |
return null; | |
} | |
} | |
/** | |
* Returns content of a file in String format. | |
* | |
* Load UTF8withBOM or any ansi text file. | |
* | |
* @param filename Name of the file. | |
* @return Content of file as String. | |
* @throws java.io.IOException IOException that can be caused by either reading File or | |
* or converting File's content to String. | |
*/ | |
public static String loadFileAsString(String filename) throws java.io.IOException { | |
BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN); | |
try { | |
ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN); | |
byte[] bytes = new byte[BUFLEN]; | |
boolean isUTF8 = false; | |
int read; | |
int count = 0; | |
while ((read = is.read(bytes)) != -1) { | |
if (count == 0 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB | |
&& bytes[2] == (byte) 0xBF) { | |
isUTF8 = true; | |
baos.write(bytes, 3, read - 3); // drop UTF8 bom marker | |
} else { | |
baos.write(bytes, 0, read); | |
} | |
count += read; | |
} | |
return isUTF8 ? new String(baos.toByteArray(), UTF_8) : new String(baos.toByteArray()); | |
} finally { | |
try { | |
is.close(); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
} | |
} | |
/** | |
* Returns serialized string of provided object. | |
* | |
* @param obj Serializable object. | |
* @return Serialized string of provided object. | |
* @see com.tigerspike.android.commons.DLUtil#deserializeObjectFromString(String) | |
*/ | |
public static String serializeObjectToString(Serializable obj) { | |
Log.d(TAG, "trying to serialize Object[" + obj.getClass().getName() + "]"); | |
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); | |
ObjectOutputStream objectOutputStream = null; | |
String strSerialized = null; | |
try { | |
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); | |
objectOutputStream.writeObject(obj); | |
strSerialized = byteArrayOutputStream.toString(ISO_8859_1); | |
strSerialized = URLEncoder.encode(strSerialized, UTF_8); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
if (objectOutputStream != null) { | |
try { | |
objectOutputStream.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
try { | |
byteArrayOutputStream.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return strSerialized; | |
} | |
/** | |
* Returns serializable object from provided string. | |
* | |
* @param str Serialized String value of serializable object. | |
* @return Serializable object | |
* | |
* @see com.tigerspike.android.commons.DLUtil#serializeObjectToString(java.io.Serializable) | |
*/ | |
public static Object deserializeObjectFromString(String str) { | |
Object obj = null; | |
ByteArrayInputStream byteArrayInputStream = null; | |
ObjectInputStream objectInputStream = null; | |
try { | |
String redStr = java.net.URLDecoder.decode(str, UTF_8); | |
byteArrayInputStream = new ByteArrayInputStream( | |
redStr.getBytes(ISO_8859_1)); | |
objectInputStream = new ObjectInputStream( | |
byteArrayInputStream); | |
obj = objectInputStream.readObject(); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} catch (OptionalDataException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} catch (ClassNotFoundException e) { | |
e.printStackTrace(); | |
} finally { | |
if (byteArrayInputStream != null) { | |
try { | |
byteArrayInputStream.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
if (objectInputStream != null) { | |
try { | |
objectInputStream.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
return obj; | |
} | |
/** | |
* Returns SHA-256 hash of given string. | |
* | |
* Gets message digest algorithm SHA-256 from MessageDigest class, computes hash of the given | |
* String and return the computed value. | |
* | |
* @param base Input string for which hash is required. | |
* @return SHA256 Returns SHA-256 hash of base String | |
* @throws NoSuchAlgorithmException NoSuchAlgorithmException is thrown in case MessageDigest | |
* class cannot find SHA-256 algorithm. | |
*/ | |
public static String computeSHA256Hash(String base) throws NoSuchAlgorithmException { | |
MessageDigest digest = MessageDigest.getInstance(SHA_256); | |
byte[] byteData = new byte[0]; | |
try { | |
byteData = digest.digest(base.getBytes(UTF_8)); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} | |
StringBuilder stringBuffer = new StringBuilder(); | |
for (byte aByteData : byteData) { | |
stringBuffer.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1)); | |
} | |
return stringBuffer.toString(); | |
} | |
/** | |
* Capitalize first letter of the String. | |
* | |
* @param s input String | |
* @return String with first letter capitalized | |
*/ | |
public static String capitalize(String s) { | |
if (s == null || s.length() == 0) { | |
return ""; | |
} | |
char first = s.charAt(0); | |
if (Character.isUpperCase(first)) { | |
return s; | |
} else { | |
return Character.toUpperCase(first) + s.substring(1); | |
} | |
} | |
/** | |
* Returns rounded to two decimal points double value as string. | |
* | |
* @param value Double value. | |
* @return rounded double value as string. | |
*/ | |
public static String getRoundedDoubleString(double value) { | |
return getRoundedDoubleString(value, 2); | |
} | |
/** | |
* Returns rounded to provided decimal points double value as string. | |
* | |
* @param value Double value. | |
* @param decimals No. of decimals. | |
* @return rounded double value as string. | |
*/ | |
public static String getRoundedDoubleString(double value, int decimals) { | |
String roundVal = "0.0"; | |
try { | |
roundVal = String.format("%." + decimals + "f", value); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return roundVal; | |
} | |
/** | |
* Returns real path from URI. | |
* | |
* @param context Current context. | |
* @param contentUri Content Uri from which real path is required. | |
* @return Real path from provided URI. | |
*/ | |
public static String getRealPathFromURI(Context context, Uri contentUri) { | |
String path = null; | |
String[] proj = {MediaStore.MediaColumns.DATA}; | |
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null); | |
if (cursor.moveToFirst()) { | |
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); | |
path = cursor.getString(columnIndex); | |
} | |
cursor.close(); | |
return path; | |
} | |
/** | |
* Shares a text only intent. This will only prompt the user to share if there is an activity | |
* that can consume the intent | |
* | |
* @param context Current context. | |
* @param title Title of the share intent. | |
* @param text The text that is used as the content of the intent. | |
* @return true if a chooser was successfully created. | |
*/ | |
public static boolean shareIntent(Context context, String title, String text) { | |
if (context == null){ | |
return false; | |
} | |
Intent shareIntent = new Intent(); | |
shareIntent.setAction(Intent.ACTION_SEND); | |
shareIntent.putExtra(Intent.EXTRA_TEXT, text); | |
shareIntent.setType("text/plain"); | |
if (context.getPackageManager() != null | |
&& shareIntent.resolveActivity(context.getPackageManager()) != null) { | |
context.startActivity(Intent.createChooser(shareIntent, title)); | |
return true; | |
} | |
return false; | |
} | |
/** | |
* Triggers share action with text, title and image. | |
* | |
* @param context Current context. | |
* @param title Title of the share intent. | |
* @param text The text that is used as the content of the intent. | |
* @param bitmap Image Bitmap that will be shared. | |
* @return true if a chooser was successfully created. | |
*/ | |
public static boolean shareIntent(Context context, String title, String text, Bitmap bitmap) { | |
// Protect against null pointers | |
if (context == null || bitmap == null) { | |
return false; | |
} | |
ContentValues values = new ContentValues(); | |
values.put(MediaStore.Images.Media.TITLE, "Share Image"); | |
values.put(MediaStore.Images.Media.BUCKET_ID, "share"); | |
values.put(MediaStore.Images.Media.DESCRIPTION, "Share Image"); | |
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png"); | |
Uri uri = context.getContentResolver().insert( | |
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); | |
OutputStream outstream = null; | |
try { | |
outstream = context.getContentResolver().openOutputStream(uri); | |
bitmap.compress(Bitmap.CompressFormat.PNG, 70, outstream); | |
outstream.close(); | |
outstream = null; | |
Intent shareIntent = new Intent(Intent.ACTION_SEND); | |
shareIntent.setType("image/*"); | |
shareIntent.putExtra(Intent.EXTRA_STREAM, uri); | |
if (text != null) { | |
shareIntent.putExtra(Intent.EXTRA_TEXT, text); | |
shareIntent.putExtra("sms_body", text); | |
} | |
if (context.getPackageManager() != null | |
&& shareIntent.resolveActivity(context.getPackageManager()) != null) { | |
context.startActivity(Intent.createChooser(shareIntent, title)); | |
return true; | |
} | |
} catch (FileNotFoundException e) { | |
return false; | |
} catch (IOException e) { | |
return false; | |
} finally { | |
if (outstream != null) { | |
try { | |
outstream.flush(); | |
} catch (IOException ex) { | |
// no need to do anything here | |
} | |
try { | |
outstream.close(); | |
} catch (IOException ex) { | |
// no need to do anything here | |
} | |
} | |
} | |
return false; | |
} | |
/** | |
* get Date string from timestamp . | |
* @param timeStamp the timestamp by millionseconds | |
* @param format the date format like : "yyyy-MM-dd HH:mm:ss" | |
* @return Date string | |
*/ | |
public static String getDateStrFromTimestamp(long timeStamp, String format){ | |
if(timeStamp>0 ){ | |
try { | |
if(format == null){ | |
format = "yyyy-MM-dd HH:mm:ss"; | |
} | |
SimpleDateFormat sdf = new SimpleDateFormat(format); | |
Date date = new Date(); | |
date.setTime(timeStamp); | |
return sdf.format(date); | |
}catch (Exception e){ | |
return null; | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
update hash map cache part.