把項目中常用的小工具做個總結吧,方便自己以後用到

1、根據手機的分辨率從 dp 的單位 轉成爲 px(像素) 

public static int dip2px(Context context, float dpValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }

2、根據手機的分辨率從 px(像素) 的單位 轉成爲 dp

public static int px2dip(Context context, float pxValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    } 

3、獲取屏幕的寬度

public static int getScreenWidth(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getApplicationContext().getResources().getDisplayMetrics();
		int width = dm.widthPixels;
		return width;
	}

4、獲取屏幕的高度

public static int getScreenHeight(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getApplicationContext().getResources().getDisplayMetrics();
		int height = dm.heightPixels;
		return height;
	}

5、驗證手機號格式

public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^[1][3,4,5,8,7][0-9]{9}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

6、驗證郵箱格式正確性,僅驗證郵箱是否是字母或數字組成、以及@符號後是否爲字母或數字

public static boolean checkEmail(String arg0) {
		return arg0.matches("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
	}

7、用戶名,由字母數字下劃線組成,並以字母下劃線開頭,6到20個字符之間

public boolean checkUserName(String name){
		Pattern pattern = Pattern.compile("^^[a-zA-Z_][a-zA-Z0-9_]{5,19}$");
		Matcher matcher = pattern.matcher(name);  
		return matcher.matches();
	}

8、根據身份證獲取性別

public static String getSex(String arg0) {
		if(checkNullMethod(arg0) && arg0.length() >= 18){
			String sex = arg0.substring(16, 17);
			int sex2 = Integer.valueOf(sex);
			if (sex2 % 2 == 0) {
				return "女";
			}
		}else{
			return "男";
		}
		return "";
	}

9、根據身份證獲取出生日期

public static String getBirth(String arg0) {
		String year = arg0.substring(6, 10);
		String month = arg0.substring(10, 12);
		String day = arg0.substring(12, 14);
		return year + "-" + month + "-" + day;
	}

10、根據身份證獲取年齡

public static String getAge(String arg0) {
		String year = arg0.substring(6, 10);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		String nowYear = sdf.format(System.currentTimeMillis());
		int age = Integer.valueOf(nowYear) - Integer.valueOf(year);
		return age + "";
	}

11、String字符串判空

public static boolean checkNullMethod(String arg0) {
		if(arg0 == null)
			return false;
		
		arg0 = arg0.trim();
		if (arg0 != null  && arg0.length() != 0 && !arg0.equals("null") && !arg0.equals("")) {
			return true;
		}
		return false;
	}



12、圖片uri轉換爲bitmap

public Bitmap decodeUriAsBitmap(Uri uri) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(context.getContentResolver()
					.openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}

13、動態設置item中listview的高度

public static void setListheight(ListView listview) {
		ListAdapter listadapter = listview.getAdapter();
		if (listadapter == null) {
			return;
		}
		int totalheight = 0;
		for (int i = 0; i < listadapter.getCount(); i++) {
			View listItem = listadapter.getView(i, null, listview);
			listItem.measure(0, 0);
			totalheight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listview.getLayoutParams();
		params.height = totalheight+ (listview.getDividerHeight() * (listadapter.getCount() - 1));
		listview.setLayoutParams(params);
	}

14、獲取應用版本名稱,此處是versionName

public String getVersionName() {
		String versionName = "v1.0";
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;
	}

15、獲取應用版本號,此處是versionCode

public int getVersionCode() {
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			return pi.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 0;
	}

16、關閉軟鍵盤

public void closeInput(EditText ed_text) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		// 得到InputMethodManager的實例
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(ed_text.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

17、根據uri獲取路徑,如果是uri路徑則通過uri返回文件絕對路徑

public String getUriPath(Uri fileUri) {
		Uri filePathUri = fileUri;
		if (fileUri != null) {
			/** content://  開頭的uri*/
			if (fileUri.getScheme().toString().compareTo("content") == 0) {
				// 通過uri獲取選中的圖片文件路徑
				String[] proj = { MediaStore.Images.Media.DATA };
				@SuppressWarnings("deprecation")
				Cursor cursor = ((Activity) context).managedQuery(fileUri,proj, null, null, null);
				int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				// 最後根據索引值獲取圖片路徑
				String path = cursor.getString(column_index);
				return path;
			}
			/** file://   開頭的uri*/
			else if (fileUri.getScheme().compareTo("file") == 0) {
				String fileName = filePathUri.toString();
				fileName = filePathUri.toString().replace("file://", "");
				return fileName;
			}
		}
		return null;
	}

18、檢測屏幕是否是鎖屏狀態;爲true,表示有兩種狀態:a、屏幕是黑的 b、目前正處於解鎖狀態 。爲false,表示目前未鎖屏

public boolean getIsLockScreen(){
		KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
		return mKeyguardManager.inKeyguardRestrictedInputMode();
	}

19、日期轉換;long類型轉成String類型

public static String longToString(long currentTime, String formatType) throws ParseException {
		Date date = longToDate(currentTime, formatType); // long類型轉成Date類型
		String strTime = dateToString(date, formatType); // date類型轉成String
		return strTime;
	}

20、日期轉換;string類型轉換爲long類型

public static long stringToLong(String strTime, String formatType) throws ParseException {
		Date date = stringToDate(strTime, formatType); // String類型轉成date類型
		if (date == null) {
			return 0;
		} else {
			long currentTime = dateToLong(date); // date類型轉成long類型
			return currentTime;
		}
	}

21、日期轉換;date類型轉換爲long類型

public static long dateToLong(Date date) {
		return date.getTime();
	}

22、日期轉換;long類型轉成date類型

public static Date longToDate(long currentTime, String formatType) throws ParseException {
		Date dateOld = new Date(currentTime); // 根據long類型的毫秒數生命一個date類型的時間
		String sDateTime = dateToString(dateOld, formatType); // 把date類型的時間轉換爲string
		Date date = stringToDate(sDateTime, formatType); // 把String類型轉換爲Date類型
		return date;
	}

23、日期轉換;String類型轉成date類型

public static Date stringToDate(String strTime, String formatType) throws ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat(formatType);
		Date date = null;
		try {
			date = formatter.parse(strTime);
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

24、date類型轉換爲String類型; formatType格式爲 yyyy-MM-dd HH:mm:ss(yyyy年MM月dd日  HH時mm分ss秒); data爲Date類型的時間

public static String dateToString(Date data, String formatType) {
		return new SimpleDateFormat(formatType).format(data);
	}

25、隱藏系統級別導航

public static void hideVirtualButtons(Activity activity) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE);
		}
	}

26、獲取系統內存剩餘

public static long getAvailableMemory(Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
		am.getMemoryInfo(memoryInfo);
		return memoryInfo.availMem;
	}

27、判斷APP是否在前臺

public static boolean isAppOnForeground(Context context) {
		ActivityManager activityManager = (ActivityManager) context.getApplicationContext()
				.getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = context.getApplicationContext().getPackageName();
		List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
		if (appProcesses == null)
			return false;
		for (RunningAppProcessInfo appProcess : appProcesses) {
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}
		return false;
	}

28、判斷SD卡是否可用

public static boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} 
		return false;
	}

29、複製文件

public static void copyfile(File fromFile, File toFile){
    	if(toFile.exists()){
    		toFile.delete();
    	}
    	FileInputStream fosform;
		try {
			fosform = new FileInputStream(fromFile);
			FileOutputStream fosto = new FileOutputStream(toFile);
			byte b[] = new byte[1024];
			int len;
			while((len = fosform.read(b)) > 0){
				fosto.write(b,0,len);
			}
			fosform.close();
			fosto.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

30、轉換文件大小

public static String getFormetFileSize(){
		long fileS = getCacheSize();
		DecimalFormat df = new DecimalFormat("#0.00");
		String fileSizeString = "";
		if (fileS < 1024){
			fileSizeString = df.format((double) fileS) + "B";
		}else if (fileS < 1048576){
			fileSizeString = df.format((double) fileS / 1024) + "K";
		}else if (fileS < 1073741824){
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		}else{
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
	    return fileSizeString;
	 }

31、保存要緩存的數據到私有文件

public void saveDatasInFile(String xmlString, String fileName) {
		FileOutputStream fos = null;
		try{
			fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
			fos.write(xmlString.getBytes());
			fos.flush();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				fos.close();
			} catch (Exception e) {}
		}
	}

32、讀取私有文件緩存的數據

public void readDatasInFile(final String fileName,final readFileCallback callback){  
		try {  
			FileInputStream fin = context.openFileInput(fileName);  
			//獲取文件長度  
			int lenght = fin.available();  
			byte[] buffer = new byte[lenght];  
			fin.read(buffer);  
			//將byte數組轉換成指定格式的字符串  
			String result = new String(buffer,"utf-8");  
			callback.readFile(result);
		} catch (Exception e) {  
			e.printStackTrace();  
		}  
    }  
    public interface readFileCallback{
    	public void readFile(String string);
    }

33、獲取視頻封面

public static String getVideoThumbPath(Context context, String path) {
        String thumbPath = null;
        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
        File file = SDUtils.getCreatFile(context, SDUtils.imgCachePicUrl, System.currentTimeMillis() + ".jpg");
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            return null;
        }
        thumbPath = file.getAbsolutePath();
        return thumbPath;
    }


34、okhttp3打印請求參數(表單提交方式)

private static String bodyToString(final Request request){
	    try {
	        final Request copy = request.newBuilder().build();
	        final Buffer buffer = new Buffer();
	        copy.body().writeTo(buffer);
	        String s = buffer.readUtf8();
	        return URLDecoder.decode(s, "UTF-8");
	    } catch (final IOException e) {
	        return "did not work";
}


持續更新...












































發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章