1. 程式人生 > >Android工具類一些方法函式

Android工具類一些方法函式

1.檢查手機網路是否可用:

public static boolean isNetworkAvailable(Activity activity) {
		Context context = activity.getApplicationContext();
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectivityManager == null) {
			return false;
		} else {
			NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

			if (networkInfo != null && networkInfo.length > 0) {
				for (int i = 0; i < networkInfo.length; i++) {
					if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
2.long型別時間格式變換:
public static String longToDate(String timestampString) {
		Long timestamp = Long.parseLong(timestampString) * 1000;
		String date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new java.util.Date(timestamp));
		return date;
	}

3.toast輸出:

public static void showToast(Context ctx, String msg) {
		Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
	}
4.跳轉Activity
public static void startAct(Context ctx, Class<?> cls) {
		Intent intent = new Intent(ctx, cls);
		ctx.startActivity(intent);
		((Activity) ctx).overridePendingTransition(R.anim.slide_in_from_right,
				R.anim.slide_out_to_left);
	}
5.獲得螢幕寬度畫素:
static public int getScreenWidthPixels(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getMetrics(dm);
		return dm.widthPixels;
	}
5.dip和畫素的單位轉換:
static public int dipToPx(Context context, int dip) {
		return (int) (dip * getScreenDensity(context) + 0.5f);
	}
6.獲取螢幕密度:
static public float getScreenDensity(Context context) {
		try {
			DisplayMetrics dm = new DisplayMetrics();
			((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
					.getDefaultDisplay().getMetrics(dm);
			return dm.density;
		} catch (Exception e) {
			return DisplayMetrics.DENSITY_DEFAULT;
		}
	}
7.判斷手機安裝的微信是否為官方的:
/**
	 * 判斷是否為官方微信
	 * 
	 * @return
	 */
	public static boolean isOfficialWx(Context context) {
		PackageInfo pi;
		try {
			pi = context.getPackageManager().getPackageInfo(
					"com.tencent.mm", PackageManager.GET_SIGNATURES);

			Signature signatures = pi.signatures[0];

			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(signatures.toByteArray());
			byte[] digest = md.digest();
			String res = toHexString(digest);
			if (WXConstants.WxMD5.equals(res)) {
				return true;
			}

		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
public static final String WxMD5 = "18:C8:67:F0:71:7A:A6:7B:2A:B7:34:75:05:BA:07:ED";
private static String toHexString(byte[] block) {
		StringBuffer buf = new StringBuffer();


		int len = block.length;


		for (int i = 0; i < len; i++) {
			byte2hex(block[i], buf);
			if (i < len - 1) {
				buf.append(":");
			}
		}
		return buf.toString();
	}
8.獲取手機剩餘記憶體是否滿足條件:
/**
	 * 獲取手機剩餘記憶體是否滿足條件
	 */
	public static boolean getAvailMemory() {
		if (externalMemoryAvailable()) {
			File path = Environment.getExternalStorageDirectory();
			StatFs sf = new StatFs(path.getPath());
			// 獲取單個數據塊的大小(Byte)
			long blockSize = sf.getBlockSize();
			// 空閒的資料塊的數量
			long freeBlocks = sf.getAvailableBlocks();
			// 返回SD卡空閒大小
			long availSize2 = (freeBlocks * blockSize) / 1024; // 單位KB
			if (availSize2 > WXConstants.REMAININGMEMORY) {
				return true;
			}
		}
		return false;
	}
public static final long REMAININGMEMORY = 307200;
public static boolean externalMemoryAvailable() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}
9.是否安裝某個應用程式:
/**
	 * 是否安裝應用程式
	 * 
	 * @param context
	 * @param packagename
	 * @return
	 */
	public static boolean isAppInstalled(Context context, String packagename) {
		PackageInfo packageInfo;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(
					packagename, 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		if (packageInfo == null) {
			// System.out.println("沒有安裝");
			return false;
		} else {
			// System.out.println("已經安裝");
			return true;
		}
	}
10.開啟某個應用程式:
/**
	 * 開啟應用
	 * @param _ctx
	 * @param packagename
	 */
	public static void openApp(Context _ctx, String packagename) {
		final PackageManager pm = _ctx.getPackageManager();
		try {
			Intent i = pm.getLaunchIntentForPackage(packagename);
			if (i != null)
				_ctx.startActivity(i);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}