您的位置:首页 > 移动开发

Android开发系统工具类SysUtils:获取App版本号、SD卡目录、缓存目录、是否后台运行、前台可见

2016-04-11 20:21 661 查看
public class SysUtils {
private static final String TAG = "SysUtils";
private SysUtils() {
}

/**获取版本号
* @param context
* @return
*/
public static String getVersionName(Context context) {
PackageManager pkgMng = context.getPackageManager();
PackageInfo pkgInfo = null;
try {
pkgInfo = pkgMng.getPackageInfo(context.getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return pkgInfo != null ? pkgInfo.versionName : "";
}
/**
* 获取SD卡目录
* @return 如果没有SD卡就返回null
*/
public static String getSdDir() {
boolean sdCardExist = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
if (sdCardExist) {
return Environment.getExternalStorageDirectory().toString(); // 获取目录
}
return null;
}
/**
* 获取应用缓存目录
* @param context
* @return
*/
public static String getCacheDir(Context context) {
return context.getCacheDir().toString();
}
/**获取应用的语言
* @param context
* @return
*/
public static String getLanguage(Context context) {
Locale locale = context.getResources().getConfiguration().locale;
return locale.getLanguage();
}
/**
* 判断程序是否在后台运行
* @param context
* @return
*/
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
return true;
} else {
return false;
}
}
}
return false;
}

/**判断app是否前台可见
* @param context
* @return
*/
public static boolean isVisible(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_VISIBLE ||
appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
} else {
return false;
}
}
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: