先推荐一款工具类框架
http:
compile 'com.blankj:utilcode:1.9.6'
屏幕尺寸相关
public class DensityUtils {
public static int dip2px(Context context, float dipValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dipValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(pxValue / scale + 0.5f);
}
public static Point getScreenMetrics(Context context){
DisplayMetrics dm =context.getResources().getDisplayMetrics();
int w_screen = dm.widthPixels;
int h_screen = dm.heightPixels;
return new Point(w_screen, h_screen);
}
public static int getScreenWidth(Context context){
DisplayMetrics dm =context.getResources().getDisplayMetrics();
int w_screen = dm.widthPixels;
return w_screen;
}
public static int getScreenHeight(Context context){
DisplayMetrics dm =context.getResources().getDisplayMetrics();
int h_screen = dm.heightPixels;
return h_screen;
}
public static float getScreenRate(Context context){
Point P = getScreenMetrics(context);
float H = P.y;
float W = P.x;
return (H/W);
}
}
图片相关
public class ImageUtils {
public static byte[] bitmapToByte(Bitmap bitmap) {
if (bitmap == null) {
return null;
}
ByteArrayOutputStream o = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, o);
return o.toByteArray();
}
public static Bitmap byteToBitmap(byte[] b) {
return (b == null || b.length == 0) ? null : BitmapFactory.decodeByteArray(b, 0, b.length);
}
public static Bitmap drawableToBitmap(Drawable drawable) {
return drawable == null ? null : ((BitmapDrawable)drawable).getBitmap();
}
@Deprecated
public static Drawable bitmapToDrawable(Bitmap bitmap) {
return bitmap == null ? null : new BitmapDrawable(bitmap);
}
public static Drawable bitmapToDrawable(Resources res,Bitmap bitmap) {
return bitmap == null ? null : new BitmapDrawable(res,bitmap);
}
public static byte[] drawableToByte(Drawable d) {
return bitmapToByte(drawableToBitmap(d));
}
public static Drawable byteToDrawable(byte[] b) {
return bitmapToDrawable(byteToBitmap(b));
}
public static Bitmap scaleImageTo(Bitmap bitmap, int newWidth, int newHeight) {
return scaleImage(bitmap, (float) newWidth / bitmap.getWidth(), (float) newHeight / bitmap.getHeight());
}
public static Bitmap scaleImage(Bitmap bitmap, float scaleWidth, float scaleHeight) {
if (bitmap == null) {
return null;
}
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
}
Log相关
public class LogUtils {
private static boolean isShowLog = true;
private static int priority = 1;
public static final String COLON = ":";
public static final String TAG = "meee";
public static final String VERTICAL = "|";
public static final int PRINTLN = 1;
public static final int VERBOSE = 2;
public static final int DEBUG = 3;
public static final int INFO = 4;
public static final int WARN = 5;
public static final int ERROR = 6;
public static final int ASSERT = 7;
public static final String TAG_FORMAT = "%s.%s(L:%d)";
public static void setShowLog(boolean isShowLog) {
LogUtils.isShowLog = isShowLog;
}
public static boolean isShowLog() {
return isShowLog;
}
public static int getPriority() {
return priority;
}
public static void setPriority(int priority) {
LogUtils.priority = priority;
}
private static String generateTag(StackTraceElement caller) {
String tag = TAG_FORMAT;
String callerClazzName = caller.getClassName();
callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);
tag = String.format(tag,new Object[] { callerClazzName, caller.getMethodName(),Integer.valueOf(caller.getLineNumber()) });
return new StringBuilder().append(TAG).append(VERTICAL).append(tag).toString();
}
public static StackTraceElement getStackTraceElement(int n) {
return Thread.currentThread().getStackTrace()[n];
}
private static String getCallerStackLogTag(){
return generateTag(getStackTraceElement(5));
}
private static String getStackTraceString(Throwable t){
return Log.getStackTraceString(t);
}
public static void v(String msg) {
if (isShowLog && priority <= VERBOSE)
Log.v(getCallerStackLogTag(), String.valueOf(msg));
}
public static void v(Throwable t) {
if (isShowLog && priority <= VERBOSE)
Log.v(getCallerStackLogTag(), getStackTraceString(t));
}
public static void v(String msg,Throwable t) {
if (isShowLog && priority <= VERBOSE)
Log.v(getCallerStackLogTag(), String.valueOf(msg), t);
}
public static void d(String msg) {
if (isShowLog && priority <= DEBUG)
Log.d(getCallerStackLogTag(), String.valueOf(msg));
}
public static void d(Throwable t) {
if (isShowLog && priority <= DEBUG)
Log.d(getCallerStackLogTag(), getStackTraceString(t));
}
public static void d(String msg,Throwable t) {
if (isShowLog && priority <= DEBUG)
Log.d(getCallerStackLogTag(), String.valueOf(msg), t);
}
public static void i(String msg) {
if (isShowLog && priority <= INFO)
Log.i(getCallerStackLogTag(), String.valueOf(msg));
}
public static void i(Throwable t) {
if (isShowLog && priority <= INFO)
Log.i(getCallerStackLogTag(), getStackTraceString(t));
}
public static void i(String msg,Throwable t) {
if (isShowLog && priority <= INFO)
Log.i(getCallerStackLogTag(), String.valueOf(msg), t);
}
public static void w(String msg) {
if (isShowLog && priority <= WARN)
Log.w(getCallerStackLogTag(), String.valueOf(msg));
}
public static void w(Throwable t) {
if (isShowLog && priority <= WARN)
Log.w(getCallerStackLogTag(), getStackTraceString(t));
}
public static void w(String msg,Throwable t) {
if (isShowLog && priority <= WARN)
Log.w(getCallerStackLogTag(), String.valueOf(msg), t);
}
public static void e(String msg) {
if (isShowLog && priority <= ERROR)
Log.e(getCallerStackLogTag(), String.valueOf(msg));
}
public static void e(Throwable t) {
if (isShowLog && priority <= ERROR)
Log.e(getCallerStackLogTag(), getStackTraceString(t));
}
public static void e(String msg,Throwable t) {
if (isShowLog && priority <= ERROR)
Log.e(getCallerStackLogTag(), String.valueOf(msg), t);
}
public static void wtf(String msg) {
if (isShowLog && priority <= ASSERT)
Log.wtf(getCallerStackLogTag(), String.valueOf(msg));
}
public static void wtf(Throwable t) {
if (isShowLog && priority <= ASSERT)
Log.wtf(getCallerStackLogTag(), getStackTraceString(t));
}
public static void wtf(String msg,Throwable t) {
if (isShowLog && priority <= ASSERT)
Log.wtf(getCallerStackLogTag(), String.valueOf(msg), t);
}
public static void print(String msg) {
if (isShowLog && priority <= PRINTLN)
System.out.print(msg);
}
public static void print(Object obj) {
if (isShowLog && priority <= PRINTLN)
System.out.print(obj);
}
public static void printf(String msg) {
if (isShowLog && priority <= PRINTLN)
System.out.printf(msg);
}
public static void println(String msg) {
if (isShowLog && priority <= PRINTLN)
System.out.println(msg);
}
public static void println(Object obj) {
if (isShowLog && priority <= PRINTLN)
System.out.println(obj);
}
}
ListView GridView根据item总高度设置高度
public class AdapterViewUtil {
public static void setListViewHeightBasedOnChildren(GridView listView,int col) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i += col) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
totalHeight += listView.getVerticalSpacing();
if (i==listAdapter.getCount()-1) {
totalHeight += listView.getVerticalSpacing();
}
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight;
((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
listView.setLayoutParams(params);
}
public static void setListViewHeightBasedOnChildren(ListView lv){
ListAdapter listAdapter = lv.getAdapter();
int listViewHeight = 0;
int adaptCount = listAdapter.getCount();
for(int i=0;i<adaptCount;i++){
View temp = listAdapter.getView(i,null,lv);
temp.measure(0,0);
listViewHeight += temp.getMeasuredHeight();
}
LayoutParams layoutParams = lv.getLayoutParams();
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = listViewHeight;
lv.setLayoutParams(layoutParams);
}
}
SharePreference相关
public class SharedPreferencesUtils {
public static final String PREF_NAME = "SHAREDPREFERENCE_FILE_NAME";
public static SharedPreferences getSharedPreferences(Context context){
return getSharedPreferences(context, PREF_NAME);
}
public static SharedPreferences getSharedPreferences(Context context, String prefName){
return context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
}
public static void put(Context context,String key,int value){
getSharedPreferences(context).edit().putInt(key, value).commit();
}
public static int getInt(Context context,String key,int defValue){
return getSharedPreferences(context).getInt(key, defValue);
}
public static int getInt(Context context,String key){
return getInt(context,key,0);
}
public static void put(Context context,String key,float value){
getSharedPreferences(context).edit().putFloat(key, value).commit();
}
public static float getFloat(Context context,String key,float defValue){
return getSharedPreferences(context).getFloat(key, defValue);
}
public static float getFloat(Context context,String key){
return getFloat(context, key, 0);
}
public static void put(Context context,String key,long value){
getSharedPreferences(context).edit().putLong(key, value).commit();
}
public static long getLong(Context context,String key,long defValue){
return getSharedPreferences(context).getLong(key, defValue);
}
public static long getLong(Context context,String key){
return getLong(context, key, 0);
}
public static void put(Context context,String key,boolean value){
getSharedPreferences(context).edit().putBoolean(key, value).commit();
}
public static boolean getBoolean(Context context,String key,boolean defValue){
return getSharedPreferences(context).getBoolean(key, defValue);
}
public static boolean getBoolean(Context context,String key){
return getBoolean(context, key, false);
}
public static void put(Context context,String key,String value){
getSharedPreferences(context).edit().putString(key, value).commit();
}
public static String getString(Context context,String key,String defValue){
return getSharedPreferences(context).getString(key, defValue);
}
public static String getString(Context context,String key){
return getString(context, key, null);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void put(Context context, String key, Set<String> value){
getSharedPreferences(context).edit().putStringSet(key, value).commit();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static Set<String> getStringSet(Context context, String key, Set<String> defValue){
return getSharedPreferences(context).getStringSet(key, defValue);
}
public static Set<String> getStringSet(Context context,String key){
return getStringSet(context, key, null);
}
@SuppressLint("CommitPrefEdits")
public static void putMapString(Context context,Map<String,String> map){
if(map!=null){
SharedPreferences.Editor editor = getSharedPreferences(context).edit();
for(Entry<String, String> entry: map.entrySet()){
if(!TextUtils.isEmpty(entry.getKey()))
editor.putString(entry.getKey(), entry.getValue());
}
editor.commit();
}
}
public static void increase(Context context,String key){
increase(context, key,1);
}
public static void increase(Context context,String key,int deltaValue){
put(context,key,getInt(context, key)+deltaValue);
}
}
String相关
public class StringUtils {
public static boolean isEmpty(CharSequence str) {
return TextUtils.isEmpty(str);
}
public static boolean isEmpty(String str) {
return TextUtils.isEmpty(str);
}
public static int length(CharSequence str) {
return str == null ? 0 : str.length();
}
public static int length(String str) {
return str == null ? 0 : str.length();
}
public static boolean isNotEmpty(Object str){
if(str == null){
return false;
}else{
if(String.valueOf(str).trim().length() == 0){
return false;
}
}
return true;
}
public static boolean equals(String str1,String str2){
return str1 != null ? str1.equals(str2) : str2 == null;
}
}
吐司相关
public class ToastUtils {
private static Toast toast;
public static void toast(Context context,@StringRes int resId){
toast(context,context.getResources().getString(resId));
}
public static void toast(Context context,@StringRes int resId,int duration){
showToast(context,context.getResources().getString(resId),duration);
}
public static void toast(Context context,CharSequence text){
showToast(context,text,Toast.LENGTH_SHORT);
}
public static void toast(Context context,String text,int duration,Object...args){
showToast(context,String.format(text,args),duration);
}
public static void showToast(Context context,CharSequence text,int duration){
if(toast == null){
toast = Toast.makeText(context,text,duration);
}else{
toast.setText(text);
toast.setDuration(duration);
}
toast.show();
}
}
时间格式化相关
public class TimeUtils {
public static final String FORMAT_Y_TO_S = "yyyyMMddHHmmss";
public static final String FORMAT_Y_TO_S_EN = "yyyy-MM-dd HH:mm:ss";
public static final String FORMAT_Y_TO_D = "yyyy-MM-dd";
public static final String FORMAT_YMD = "yyyyMMdd";
public static final String FORMAT_HMS = "HHmmss";
public static final String FORMAT_H_TO_MIN = "HH:mm";
public static String FORMAT_Y_M_D = "yyyy/MM/dd/ HH:mm:ss";
public static String FORMAT_H_M_S = "HH:mm:ss";
public static String formatDate(String time, String fromFormat,
String toFormat) {
if (TextUtils.isEmpty(time)) {
return null;
} else if (TextUtils.isEmpty(fromFormat)
|| TextUtils.isEmpty(toFormat)) {
return time;
}
String dateTime = time;
String dataStr = null;
try {
SimpleDateFormat oldFormat = new SimpleDateFormat(fromFormat);
SimpleDateFormat newFormat = new SimpleDateFormat(toFormat);
dataStr = newFormat.format(oldFormat.parse(dateTime));
} catch (ParseException e) {
return time;
}
return dataStr;
}
public static String formatDate(String time, String toFormat) {
if (time == null || "".equals(time.trim()))
return "";
String fromFormat = null;
if (time.length() == 6) {
fromFormat = "HHmmss";
} else if (time.length() == 8) {
fromFormat = "yyyyMMdd";
} else if (time.length() == 14) {
fromFormat = "yyyyMMddHHmmss";
} else {
return time;
}
try {
SimpleDateFormat oldFormat = new SimpleDateFormat(fromFormat);
SimpleDateFormat newFormat = new SimpleDateFormat(toFormat);
return newFormat.format(oldFormat.parse(time));
} catch (ParseException e) {
return time;
}
}
public static String formatDate(long time, String toFormat) throws ParseException{
Date date = new Date(time);
SimpleDateFormat newFormat = new SimpleDateFormat(toFormat);
return newFormat.format(date);
}
public static String getCurrentDate() throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(FORMAT_Y_TO_S_EN);
return format.format(new Date());
}
public static String getCurrentDate(String formatStr) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
return format.format(new Date());
}
public static String formatDate(Date date, String formatStr) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
return format.format(date);
}
}
Android系统应用相关
public class SystemUtils {
public static void newThread(Runnable runnable){
new Thread(runnable).start();
}
public static boolean isNetWorkActive(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
return activeNetInfo != null && activeNetInfo.isConnected();
}
public static void deleteClick(EditText et) {
final KeyEvent keyEventDown = new KeyEvent(KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_DEL);
et.onKeyDown(KeyEvent.KEYCODE_DEL, keyEventDown);
}
public static void call(Context context, String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(String.format("tel:%s", phoneNumber)));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public static void sendSMS(Context context, String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(String.format("smsto:%s", phoneNumber)));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public static void sendSMS(String phoneNumber, String msg) {
SmsManager sm = SmsManager.getDefault();
List<String> msgs = sm.divideMessage(msg);
for (String text : msgs) {
sm.sendTextMessage(phoneNumber, null, text, null, null);
}
}
public static void imageCapture(Activity activity, int requestCode) {
imageCapture(activity, null, requestCode);
}
public static void imageCapture(Activity activity, String path,
int requestCode) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (!TextUtils.isEmpty(path)) {
Uri uri = Uri.fromFile(new File(path));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
activity.startActivityForResult(intent, requestCode);
}
public static void imageCapture(Fragment fragment, String path,
int requestCode) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (!TextUtils.isEmpty(path)) {
Uri uri = Uri.fromFile(new File(path));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
fragment.startActivityForResult(intent, requestCode);
}
public static PackageInfo getPackageInfo(Context context) {
PackageInfo packageInfo = null;
try {
packageInfo = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
LogUtils.e(e);
} catch (Exception e) {
LogUtils.e(e);
}
return packageInfo;
}
public static String getVersionName(Context context) {
PackageInfo packageInfo = getPackageInfo(context);
return packageInfo != null ? packageInfo.versionName : null;
}
public static int getVersionCode(Context context) {
PackageInfo packageInfo = getPackageInfo(context);
return packageInfo != null ? packageInfo.versionCode : 0;
}
public static void startAppDetailSetings(Context context){
Uri uri = Uri.fromParts("package", context.getPackageName(), null);
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,uri);
context.startActivity(intent);
}
public static void installApk(Context context,String path){
installApk(context,new File(path));
}
public static void installApk(Context context,File file){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uriData = Uri.fromFile(file);
String type = "application/vnd.android.package-archive";
intent.setDataAndType(uriData, type);
context.startActivity(intent);
}
public static void uninstallApk(Context context,String packageName){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uriData = Uri.parse("package:" + packageName);
intent.setData(uriData);
context.startActivity(intent);
}
public static void uninstallApk(Context context){
uninstallApk(context,context.getPackageName());
}
public static boolean checkSelfPermission(Context context, @NonNull String permission){
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
public static void requestPermission(Activity activity, @NonNull String permission, int requestCode){
ActivityCompat.requestPermissions(activity,new String[]{permission}, requestCode);
}
public static void shouldShowRequestPermissionRationale(Activity activity, @NonNull String permission){
ActivityCompat.shouldShowRequestPermissionRationale(activity,permission);
}
public static void hideInputMethod(Context context,EditText v) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(),0);
}
public static void showInputMethod(Context context,EditText v) {
v.requestFocus();
InputMethodManager imm = (InputMethodManager)context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(v,InputMethodManager.SHOW_IMPLICIT);
}
}
Base64相关
public class Base64Utils {
public static String string2Base64(String string){
byte[] bytes = string.getBytes();
return Base64.encodeToString(bytes, Base64.DEFAULT);
}
public static String Base642String(String base64string){
byte[] bytes = Base64.decode(base64string, Base64.DEFAULT);
return bytes.toString();
}
public static String bitmapToBase64(Bitmap bitmap) {
String result = null;
ByteArrayOutputStream baos = null;
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baos.flush();
baos.close();
byte[] bitmapBytes = baos.toByteArray();
result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static Bitmap base64ToBitmap(String base64Data) {
byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length );
}
}
SD卡相关
public class SDCardUtils {
public static boolean isSDCardEnable() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
public static String getSDCardPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator;
}
public static long getSDCardAvailableCapacity() {
if (isSDCardEnable())
{
StatFs stat = new StatFs(getSDCardPath());
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
long freeBlocks = stat.getAvailableBlocks();
return freeBlocks * availableBlocks;
}
return 0;
}
public static long getFreeBytes(String filePath) {
if (filePath.startsWith(getSDCardPath()))
{
filePath = getSDCardPath();
} else
{
filePath = Environment.getDataDirectory().getAbsolutePath();
}
StatFs stat = new StatFs(filePath);
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
return stat.getBlockSize() * availableBlocks;
}
public static String getRootDirectoryPath() {
return Environment.getRootDirectory().getAbsolutePath();
}
}
屏幕相关
public class ScreenUtils {
public static int getScreenWidth(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try
{
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e)
{
e.printStackTrace();
}
return statusHeight;
}
public static Bitmap snapShotWithStatusBar(Activity activity)
{
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
view.destroyDrawingCache();
return bp;
}
public static Bitmap snapShotWithoutStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return bp;
}
}
随机数工具类
public class RandomUtils {
public static final String NUMBERS_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String NUMBERS = "0123456789";
public static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String CAPITAL_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
public static String getRandomNumbersAndLetters(int length) {
return getRandom(NUMBERS_AND_LETTERS, length);
}
public static String getRandomNumbers(int length) {
return getRandom(NUMBERS, length);
}
public static String getRandomLetters(int length) {
return getRandom(LETTERS, length);
}
public static String getRandomCapitalLetters(int length) {
return getRandom(CAPITAL_LETTERS, length);
}
public static String getRandomLowerCaseLetters(int length) {
return getRandom(LOWER_CASE_LETTERS, length);
}
public static String getRandom(String source, int length) {
return StringUtils.isEmpty(source) ? null : getRandom(source.toCharArray(), length);
}
public static String getRandom(char[] sourceChar, int length) {
if (sourceChar == null || sourceChar.length == 0 || length < 0) {
return null;
}
StringBuilder str = new StringBuilder(length);
Random random = new Random();
for (int i = 0; i < length; i++) {
str.append(sourceChar[random.nextInt(sourceChar.length)]);
}
return str.toString();
}
public static int getRandom(int max) {
return getRandom(0, max);
}
public static int getRandom(int min, int max) {
if (min > max) {
return 0;
}
if (min == max) {
return min;
}
return min + new Random().nextInt(max - min);
}
public static boolean shuffle(Object[] objArray) {
if (objArray == null) {
return false;
}
return shuffle(objArray, getRandom(objArray.length));
}
public static boolean shuffle(Object[] objArray, int shuffleCount) {
int length;
if (objArray == null || shuffleCount < 0 || (length = objArray.length) < shuffleCount) {
return false;
}
for (int i = 1; i <= shuffleCount; i++) {
int random = getRandom(length - i);
Object temp = objArray[length - i];
objArray[length - i] = objArray[random];
objArray[random] = temp;
}
return true;
}
public static int[] shuffle(int[] intArray) {
if (intArray == null) {
return null;
}
return shuffle(intArray, getRandom(intArray.length));
}
public static int[] shuffle(int[] intArray, int shuffleCount) {
int length;
if (intArray == null || shuffleCount < 0 || (length = intArray.length) < shuffleCount) {
return null;
}
int[] out = new int[shuffleCount];
for (int i = 1; i <= shuffleCount; i++) {
int random = getRandom(length - i);
out[i - 1] = intArray[random];
int temp = intArray[length - i];
intArray[length - i] = intArray[random];
intArray[random] = temp;
}
return out;
}
}
网络状态相关工具类
public class NetWorkUtils {
public static boolean isConnected(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != connectivity) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (null != info && info.isConnected()) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
public static boolean isWifiConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return false;
return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
}
public static void openNetworkSetting(Activity activity) {
Intent intent = new Intent("/");
ComponentName cm = new ComponentName("com.android.settings",
"com.android.settings.WirelessSettings");
intent.setComponent(cm);
intent.setAction("android.intent.action.VIEW");
activity.startActivityForResult(intent, 0);
}
}
软键盘开关工具类
public class KeyBoardUtils
{
public static void openKeybord(EditText mEditText, Context mContext)
{
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}
public static void closeKeybord(EditText mEditText, Context mContext)
{
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}
}
原生网络请求封装工具类
public class HttpUtils {
private static final int TIMEOUT_IN_MILLIONS = 5000;
public interface CallBack {
void onRequestComplete(String result);
}
/**
* 异步的Get请求
*
* @param urlStr
* @param callBack
*/
public static void doGetAsyn(final String urlStr, final CallBack callBack) {
new Thread() {
public void run() {
try {
String result = doGet(urlStr);
if (callBack != null) {
callBack.onRequestComplete(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
;
}.start();
}
/**
* 异步的Post请求
*
* @param urlStr
* @param params
* @param callBack
* @throws Exception
*/
public static void doPostAsyn(final String urlStr, final String params,
final CallBack callBack) throws Exception {
new Thread() {
public void run() {
try {
String result = doPost(urlStr, params);
if (callBack != null) {
callBack.onRequestComplete(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
;
}.start();
}
/**
* Get请求,获得返回数据
*
* @param urlStr
* @return
* @throws Exception
*/
public static String doGet(String urlStr) {
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
conn.setRequestMethod("GET");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[128];
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
baos.flush();
return baos.toString();
} else {
throw new RuntimeException(" responseCode is not 200 ... ");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (baos != null)
baos.close();
} catch (IOException e) {
}
conn.disconnect();
}
return null;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
* @throws Exception
*/
public static String doPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl
.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
if (param != null && !param.trim().equals("")) {
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
}
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
文件相关
public class FileUtils {
private static FileUtils util;
public static FileUtils getInstance() {
if (util == null)
util = new FileUtils();
return util;
}
private Context context = null;
public void setContext(Context c) {
this.context = c;
}
public Context getContext() {
return context;
}
public File creatFileIfNotExist(String path) {
System.out.println("cr");
File file = new File(path);
if (!file.exists()) {
try {
new File(path.substring(0, path.lastIndexOf(File.separator)))
.mkdirs();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
public File creatDirIfNotExist(String path) {
File file = new File(path);
if (!file.exists()) {
try {
file.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
public boolean IsExist(String path) {
File file = new File(path);
if (!file.exists())
return false;
else
return true;
}
public File creatNewFile(String path) {
File file = new File(path);
if (IsExist(path))
file.delete();
creatFileIfNotExist(path);
return file;
}
public boolean deleteFile(String path) {
File file = new File(path);
if (IsExist(path))
file.delete();
return true;
}
public boolean deleteFileDir(String path) {
boolean flag = false;
File file = new File(path);
if (!IsExist(path)) {
return flag;
}
if (!file.isDirectory()) {
file.delete();
return true;
}
String[] filelist = file.list();
File temp = null;
for (int i = 0; i < filelist.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + filelist[i]);
} else {
temp = new File(path + File.separator + filelist[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
deleteFileDir(path + "/" + filelist[i]);
}
}
file.delete();
flag = true;
return flag;
}
public void delFolder(String folderPath) {
try {
delAllFile(folderPath);
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);
delFolder(path + "/" + tempList[i]);
flag = true;
}
}
return flag;
}
public String[] getFlieName(String rootpath) {
File root = new File(rootpath);
File[] filesOrDirs = root.listFiles();
if (filesOrDirs != null) {
String[] dir = new String[filesOrDirs.length];
int num = 0;
for (int i = 0; i < filesOrDirs.length; i++) {
if (filesOrDirs[i].isDirectory()) {
dir[i] = filesOrDirs[i].getName();
num++;
}
}
String[] dir_r = new String[num];
num = 0;
for (int i = 0; i < dir.length; i++) {
if (dir[i] != null && !dir[i].equals("")) {
dir_r[num] = dir[i];
num++;
}
}
return dir_r;
} else
return null;
}
public BufferedWriter getWriter(String path) throws FileNotFoundException,
UnsupportedEncodingException {
FileOutputStream fileout = null;
fileout = new FileOutputStream(new File(path));
OutputStreamWriter writer = null;
writer = new OutputStreamWriter(fileout, "UTF-8");
BufferedWriter w = new BufferedWriter(writer);
return w;
}
public InputStream getInputStream(String path) throws FileNotFoundException {
FileInputStream filein = null;
File file = new File(path);
filein = new FileInputStream(file);
BufferedInputStream in = null;
if (filein != null)
in = new BufferedInputStream(filein);
return in;
}
public boolean ifFileExit(String path) {
File f = new File(path);
if (!f.exists())
return false;
if (f.length() == 0)
return false;
return true;
}
public static byte[] InputStream2Bytes(InputStream in) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[6 * 1024];
int count = -1;
while ((count = in.read(data, 0, 4 * 1024)) != -1)
outStream.write(data, 0, count);
data = null;
return outStream.toByteArray();
}
public static byte[] OutputStream2Bytes(OutputStream out)
throws IOException {
byte[] data = new byte[6 * 1024];
out.write(data);
return data;
}
public static InputStream byte2InputStream(byte[] in) {
ByteArrayInputStream is = new ByteArrayInputStream(in);
return is;
}
public static OutputStream bytes2OutputStream(byte[] in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(in);
return out;
}
public File writeFromInputToSD(String path, InputStream inputStream) {
File file = null;
OutputStream output = null;
try {
file = creatFileIfNotExist(path);
output = new FileOutputStream(file);
byte[] buffer = new byte[4 * 1024];
int temp;
while ((temp = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, temp);
}
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
public File writeFromInputToSD(String path, byte[] b) {
File file = null;
OutputStream output = null;
try {
file = creatFileIfNotExist(path);
output = new FileOutputStream(file);
output.write(b);
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
public void saveTxtFile(String filePath, String text) {
try {
creatFileIfNotExist(filePath);
String txt = readTextLine(filePath);
text = text + txt;
FileOutputStream out = new FileOutputStream(filePath);
OutputStreamWriter writer = new OutputStreamWriter(out, "gb2312");
writer.write(text);
writer.close();
out.close();
} catch (Exception e) {
String ext = e.getLocalizedMessage();
}
}
public void clearTxtFile(String filePath) {
try {
String text = "";
FileOutputStream out = new FileOutputStream(filePath);
OutputStreamWriter writer = new OutputStreamWriter(out, "gb2312");
writer.write(text);
writer.close();
out.close();
} catch (Exception e) {
String ext = e.getLocalizedMessage();
}
}
public String readTextLine(String textFilePath) {
try {
FileInputStream input = new FileInputStream(textFilePath);
InputStreamReader streamReader = new InputStreamReader(input,
"gb2312");
LineNumberReader reader = new LineNumberReader(streamReader);
String line = null;
StringBuilder allLine = new StringBuilder();
while ((line = reader.readLine()) != null) {
allLine.append(line);
allLine.append("\n");
}
streamReader.close();
reader.close();
input.close();
return allLine.toString();
} catch (Exception e) {
return "";
}
}
public String getNameByFlag(String source, String flag) {
String[] source_spli = source.split(flag);
String s = source_spli[0].replace(flag, "");
return s.trim();
}
public InputStream getAssetsInputStream(Context paramContext,
String paramString) throws IOException {
return paramContext.getResources().getAssets().open(paramString);
}
public Bitmap getBitmap(InputStream is) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
opt.inSampleSize = 4;
return BitmapFactory.decodeStream(is, null, opt);
}
}