Skip to content

Instantly share code, notes, and snippets.

@SeniorZhai
Created September 2, 2014 03:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SeniorZhai/a391d965bd276f42f191 to your computer and use it in GitHub Desktop.
Save SeniorZhai/a391d965bd276f42f191 to your computer and use it in GitHub Desktop.
通用工具类
public class CommonUtils {
private static NetworkInfo getNetworkInfo(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetWorkInfo();
}
// 是否存在网络
public static boolean isNetworkAvailable(Context context) {
NetworkInfo info = getNetworkInfo(context);
if (info != null) {
return info.isAvailable();
}
return false;
}
// 是否为WiFi
public static boolean isWifi(Context context) {
NetworkInfo info = getNetworkInfo(context);
if (info != null) {
if (info.getType() == ConnectivityManager.Type_WIFI)
return true;
}
return false;
}
// 是否为手机网络
public static boolean isMobile(Context context) {
NetworkInfo info = getNetworkInfo(context);
if (info != null) {
if (info.getType() == ConnectivityManager.Type_MOBILE) {
return true;
}
return false;
}
}
// 改变wifi状态
public static void changeWIFIStatus(Context context,boolean status) {
((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).setWifiEnabled(status);
}
// 获取屏幕宽高
public static int[] getScreenSize() {
int[] screens;
DisplayMetrics dm = new DisplayMetrics();
dm = MyApplication.getInstance().getResources().getDisplayMetrics();
screens = new int[] { dm.widthPixels, dm.heightPixels };
return screens;
}
// 加载字体
public static Typeface getTypeface(Context context, String assetsPah) {
Typeface typeface = Typeface.createFromAsset(context.getAssets(),
assetsPah);
return typeface;
}
// 获取Bitmap的宽和高
public static float[] getBitmapConfiguration(Bitmap bitmap,
ImageView imageView, float screenRadio) {
int screenWidth = getScreenSize()[0];
float rawWidth = 0;
float rawHeight = 0;
float width = 0;
float height = 0;
if (bitmap == null) {
// rawWidth = sourceWidth;
// rawHeight = sourceHeigth;
width = (float) (screenWidth / screenRadio);
height = (float) width;
imageView.setScaleType(ScaleType.FIT_XY);
} else {
rawWidth = bitmap.getWidth();
rawHeight = bitmap.getHeight();
if (rawHeight > 10 * rawWidth) {
imageView.setScaleType(ScaleType.CENTER);
} else {
imageView.setScaleType(ScaleType.FIT_XY);
}
float radio = rawHeight / rawWidth;
width = (float) (screenWidth / screenRadio);
height = (float) (radio * width);
}
return new float[] { width, height };
}
// 获取App版本号
public static String getVersionName(Context context) {
PackageManager pm = context.getPackageManager();
try {
PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
return info.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
// 通过浏览器打开页面
public static void openBrowser(Context context, String urlText) {
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
Uri url = Uri.parse(urlText);
intent.setData(url);
context.startActivity(intent);
}
// 切换全屏状态 isFull 设置为true则全屏,否则非全屏
public static void toggleFullScreen(Activity activity, boolean isFull) {
hideTitleBar(activity);
Window window = activity.getWindow();
WindowManager.LayoutParams params = window.getAttributes();
if (isFull) {
params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
window.setAttributes(params);
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
} else {
params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.setAttributes(params);
window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
}
// 设置为全屏
public static void setFullScreen(Activity activity) {
toggleFullScreen(activity, true);
}
// 隐藏系统标题栏
public static void hideTitleBar(Activity activity) {
activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
// 获取系统状态栏高度
public static int getStatusBarHeight(Activity activity) {
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
Field field = clazz.getField("status_bar_height");
int dpHeight = Integer.parseInt(field.get(object).toString());
return activity.getResources().getDimensionPixelSize(dpHeight);
} catch (Exception e1) {
e1.printStackTrace();
return 0;
}
}
// 强制设置Actiity的显示方向为垂直方向。
public static void setScreenVertical(Activity activity) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// 强制设置Activity的显示方向为横向。
public static void setScreenHorizontal(Activity activity) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
// 隐藏软件输入法
public static void hideSoftInput(Activity activity) {
activity.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
// 关闭已经显示的输入法窗口。 focusingView 输入法所在焦点的View
public static void closeSoftInput(Context context, View focusingView) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(focusingView.getWindowToken(),
InputMethodManager.RESULT_UNCHANGED_SHOWN);
}
// 使UI适配输入法
public static void adjustSoftInput(Activity activity) {
activity.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
}
// 快捷方式是否存在
public static boolean ifAddShortCut(Context context, String[] appName) {
boolean isInstallShortCut = false;
ContentResolver cr = context.getContentResolver();
String authority = "com.android.launcher2.settings";
Uri uri = Uri
.parse("content://" + authority + "/favorites?notify=true");
Cursor c = cr.query(uri, new String[] { "title", "iconResource" },
"title=?", appName, null);
if (null != c && c.getCount() > 0) {
isInstallShortCut = true;
}
return isInstallShortCut;
}
// Clazz指定启动Activity
public static void addShortCut(Context context, String appName, Class clazz) {
Intent shortcut = new Intent(
"com.android.launcher.action.INSTALL_SHORTCUT");
// 设置属性
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
ShortcutIconResource resource = Intent.ShortcutIconResource
.fromContext(context, R.drawable.ic_launcher);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, resource);
// 是否允许重复创建
shortcut.putExtra("duplicate", false);
Intent intent = new Intent(Intent.ACTION_MAIN);// 标识Activity为一个程序的开始
intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClass(context, clazz);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
context.sendBroadcast(shortcut);
}
// 得到view高度
public static int getViewHeight(int w, int bmw, int bmh) {
return w * bmh / bmw;
}
// MD5変換
public static String Md5(String str) {
if(str != null && !str.equals("")) {
try {
MessageDigest md5=MessageDigest.getInstance("MD5");
char[] HEX={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
byte[] md5Byte=md5.digest(str.getBytes("UTF8"));
StringBuffer sb=new StringBuffer();
for(int i=0; i < md5Byte.length; i++) {
sb.append(HEX[(int)(md5Byte[i] & 0xff) / 16]);
sb.append(HEX[(int)(md5Byte[i] & 0xff) % 16]);
}
str=sb.toString();
} catch(NoSuchAlgorithmException e) {
} catch(Exception e) {
}
}
return str;
}
// 得到手机IMEI
public static String getImei(Context context) {
TelephonyManager tm=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
Log.i("IMEI", tm.getDeviceId());
return tm.getDeviceId();
}
// 安装一个APK文件
public static void installApk(Context context, File file) {
Intent intent=new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
context.startActivity(intent);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment