AppUtils.java
应用工具类相关方法:
getAppName : 获取应用名称
getAppIcon : 获取应用图标
getAppFirstInstallTime : 获取应用第一次安装日期
getAppLastUpdateTime : 获取应用更新日期
getAppSize : 获取应用大小
getAppApk : 获取应用 apk 文件
getAppVersionName : 获取应用版本名称
getAppInstaller : 获取应用的安装市场
getAppSign : 获取应用签名
getAppTargetSdkVersion : 获取应用兼容sdk
getAppUid : 获取应用uid
getNumCores : 获取Cpu内核数
getRootPermission : 获得root权限
getAppPermissions : 获取应用的所有权限
hasPermission : 是否有权限
isInstalled : 应用是否安装
isSystemApp : 是否是系统应用
isServiceRunning : 服务是否在运行
stopRunningService : 停止服务
killProcesses : 结束进程
runScript : 运行脚本
runApp : 启动应用
cleanCache : 清除应用内部缓存
cleanDatabases : 清除应用内部数据库
cleanSharedPreference : 清除应用内部SP
public class AppUtils {
public static String getAppName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
String appName = null;
try {
ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
appName = String.valueOf(pm.getApplicationLabel(applicationInfo));
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appName;
}
public static Drawable getAppIcon(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
Drawable appIcon = null;
try {
ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
appIcon = applicationInfo.loadIcon(pm);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appIcon;
}
public static long getAppFirstInstallTime(Context context, String packageName) {
long lastUpdateTime = 0;
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
lastUpdateTime = packageInfo.firstInstallTime;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return lastUpdateTime;
}
public static long getAppLastUpdateTime(Context context, String packageName) {
long lastUpdateTime = 0;
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
lastUpdateTime = packageInfo.lastUpdateTime;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return lastUpdateTime;
}
public static long getAppSize(Context context, String packageName) {
long appSize = 0;
try {
ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
appSize = new File(applicationInfo.sourceDir).length();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appSize;
}
public static String getAppApk(Context context, String packageName) {
String sourceDir = null;
try {
ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
sourceDir = applicationInfo.sourceDir;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return sourceDir;
}
public static String getAppVersionName(Context context, String packageName) {
String appVersion = null;
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
appVersion = packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appVersion;
}
public static int getAppVersionCode(Context context, String packageName) {
int appVersionCode = 0;
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
appVersionCode = packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appVersionCode;
}
public static String getAppInstaller(Context context, String packageName) {
return context.getPackageManager().getInstallerPackageName(packageName);
}
public static String getAppSign(Context context, String packageName) {
try {
PackageInfo pis = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
return hexdigest(pis.signatures[0].toByteArray());
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(AppUtils.class.getName() + "the " + packageName + "'s application not found");
}
}
public static int getAppTargetSdkVersion(Context context, String packageName) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
ApplicationInfo applicationInfo = packageInfo.applicationInfo;
return applicationInfo.targetSdkVersion;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return 0;
}
}
public static int getAppUid(Context context, String packageName) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
ApplicationInfo applicationInfo = packageInfo.applicationInfo;
return applicationInfo.uid;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return 0;
}
}
public static int getNumCores() {
try {
File dir = new File("/sys/devices/system/cpu/");
File[] files = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return Pattern.matches("cpu[0-9]", pathname.getName());
}
});
return files.length;
} catch (Exception e) {
e.printStackTrace();
return 1;
}
}
public static boolean getRootPermission(Context context) {
String packageCodePath = context.getPackageCodePath();
Process process = null;
DataOutputStream os = null;
try {
String cmd = "chmod 777 " + packageCodePath;
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
public static String[] getAppPermissions(Context context, String packname) {
String[] requestedPermissions = null;
try {
PackageInfo info = context.getPackageManager().getPackageInfo(packname, PackageManager.GET_PERMISSIONS);
requestedPermissions = info.requestedPermissions;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return requestedPermissions;
}
public static boolean hasPermission(Context context, String permission) {
if (context != null && !TextUtils.isEmpty(permission)) {
try {
PackageManager packageManager = context.getPackageManager();
if (packageManager != null) {
if (PackageManager.PERMISSION_GRANTED == packageManager.checkPermission(permission, context
.getPackageName())) {
return true;
}
Log.d("AppUtils", "Have you declared permission " + permission + " in AndroidManifest.xml ?");
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
return false;
}
public static boolean isInstalled(Context context, String packageName) {
boolean installed = false;
if (TextUtils.isEmpty(packageName)) {
return false;
}
List<ApplicationInfo> installedApplications = context.getPackageManager().getInstalledApplications(0);
for (ApplicationInfo in : installedApplications) {
if (packageName.equals(in.packageName)) {
installed = true;
break;
} else {
installed = false;
}
}
return installed;
}
@Deprecated
public static boolean installApk(Context context, String filePath) {
File file = new File(filePath);
if (!file.exists() || !file.isFile() || file.length() <= 0) {
return false;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
return true;
}
@Deprecated
public static boolean uninstallApk(Context context, String packageName) {
if (TextUtils.isEmpty(packageName)) {
return false;
}
Intent i = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + packageName));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
return true;
}
public static boolean isSystemApp(Context context, String packageName) {
boolean isSys = false;
PackageManager pm = context.getPackageManager();
try {
ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
if (applicationInfo != null && (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
isSys = true;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
isSys = false;
}
return isSys;
}
public static boolean isServiceRunning(Context context, String className) {
boolean isRunning = false;
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> servicesList = activityManager.getRunningServices(Integer.MAX_VALUE);
for (RunningServiceInfo si : servicesList) {
if (className.equals(si.service.getClassName())) {
isRunning = true;
}
}
return isRunning;
}
public static boolean stopRunningService(Context context, String className) {
Intent intent_service = null;
boolean ret = false;
try {
intent_service = new Intent(context, Class.forName(className));
} catch (Exception e) {
e.printStackTrace();
}
if (intent_service != null) {
ret = context.stopService(intent_service);
}
return ret;
}
public static void killProcesses(Context context, int pid, String processName) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
String packageName;
try {
if (!processName.contains(":")) {
packageName = processName;
} else {
packageName = processName.split(":")[0];
}
activityManager.killBackgroundProcesses(packageName);
Method forceStopPackage = activityManager.getClass().getDeclaredMethod("forceStopPackage", String.class);
forceStopPackage.setAccessible(true);
forceStopPackage.invoke(activityManager, packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String runScript(String script) {
String sRet;
try {
final Process m_process = Runtime.getRuntime().exec(script);
final StringBuilder sbread = new StringBuilder();
Thread tout = new Thread(new Runnable() {
public void run() {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(m_process.getInputStream()),
8192);
String ls_1;
try {
while ((ls_1 = bufferedReader.readLine()) != null) {
sbread.append(ls_1).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
tout.start();
final StringBuilder sberr = new StringBuilder();
Thread terr = new Thread(new Runnable() {
public void run() {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(m_process.getErrorStream()),
8192);
String ls_1;
try {
while ((ls_1 = bufferedReader.readLine()) != null) {
sberr.append(ls_1).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
terr.start();
m_process.waitFor();
while (tout.isAlive()) {
Thread.sleep(50);
}
if (terr.isAlive())
terr.interrupt();
String stdout = sbread.toString();
String stderr = sberr.toString();
sRet = stdout + stderr;
} catch (Exception e) {
e.printStackTrace();
return null;
}
return sRet;
}
public static void runApp(Context context, String packagename) {
context.startActivity(new Intent(context.getPackageManager().getLaunchIntentForPackage(packagename)));
}
@Deprecated
public static void cleanCache(Context context) {
FileUtils.deleteFileByDirectory(context.getCacheDir());
}
@Deprecated
public static void cleanDatabases(Context context) {
String filepath = String.format(String.format(context.getFilesDir().getParent() + File.separator + "%s", "databases"));
FileUtils.deleteFileByDirectory(new File(filepath));
}
@Deprecated
public static void cleanSharedPreference(Context context) {
String filepath = String.format(String.format(context.getFilesDir().getParent() + File.separator + "%s", "shared_prefs"));
FileUtils.deleteFileByDirectory(new File(filepath));
}
}
DeviceUtils.java
设备信息工具相关方法:
getAndroidID : 获取AndroidID
getIMEI : 获取设备IMEI码
getIMSI : 获取设备IMSI码
getWifiMacAddr : 获取MAC地址
getIP : 获取网络IP地址(优先获取wifi地址)
getWifiIP : 获取WIFI连接下的ip地址
getGPRSIP : 获取GPRS连接下的ip地址
getSerial : 获取设备序列号
getSIMSerial : 获取SIM序列号
getMNC : 获取网络运营商 46000,46002,46007 中国移动,46001 中国联通,46003 中国电信
getCarrier : 获取网络运营商:中国电信,中国移动,中国联通
getModel : 获取硬件型号
getBuildBrand : 获取编译厂商
getBuildHost : 获取编译服务器主机
getBuildTags : 获取描述Build的标签
getBuildTime : 获取系统编译时间
getBuildUser : 获取系统编译作者
getBuildVersionRelease : 获取编译系统版本(5.1)
getBuildVersionCodename : 获取开发代号
getBuildVersionIncremental : 获取源码控制版本号
getBuildVersionSDK : 获取编译的SDK
getBuildID : 获取修订版本列表(LMY47D)
getSupportedABIS : CPU指令集
getManufacturer : 获取硬件制造厂商
getBootloader : 获取系统启动程序版本号
getScreenDisplayID
getDisplayVersion : 获取系统版本号
getLanguage : 获取语言
getCountry : 获取国家
getOSVersion : 获取系统版本:5.1.1
getGSFID : 获取GSF序列号
getBluetoothMAC : 获取蓝牙地址
getPsuedoUniqueID : Android设备物理唯一标识符
getFingerprint : 构建标识,包括brand,name,device,version.release,id,version.incremental,type,tags这些信息
getHardware : 获取硬件信息
getProduct : 获取产品信息
getDevice : 获取设备信息
getBoard : 获取主板信息
getRadioVersion : 获取基带版本(无线电固件版本 Api14以上)
getUA : 获取的浏览器指纹(User-Agent)
getDensity : 获取得屏幕密度
getGoogleAccounts : 获取google账号
public class DeviceUtils {
public static String getAndroidID(Context ctx) {
return Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.ANDROID_ID);
}
public static String getIMEI(Context ctx) {
return ((TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
}
public static String getIMSI(Context ctx) {
TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getSubscriberId() != null ? tm.getSubscriberId() : null;
}
@SuppressWarnings("MissingPermission")
public static String getWifiMacAddr(Context ctx) {
String macAddr = "";
try {
WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
macAddr = wifi.getConnectionInfo().getMacAddress();
if (macAddr == null) {
macAddr = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return macAddr;
}
public static String getIP(Context ctx) {
WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
return wifiManager.isWifiEnabled() ? getWifiIP(wifiManager) : getGPRSIP();
}
public static String getWifiIP(WifiManager wifiManager) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ip = intToIp(wifiInfo.getIpAddress());
return ip != null ? ip : "";
}
public static String getGPRSIP() {
String ip = null;
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
for (Enumeration<InetAddress> enumIpAddr = en.nextElement().getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
ip = inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
ip = null;
}
return ip;
}
private static String intToIp(int i) {
return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
}
public static String getSerial() {
return Build.SERIAL;
}
public static String getSIMSerial(Context ctx) {
TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getSimSerialNumber();
}
public static String getMNC(Context ctx) {
String providersName = "";
TelephonyManager telephonyManager = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY) {
providersName = telephonyManager.getSimOperator();
providersName = providersName == null ? "" : providersName;
}
return providersName;
}
public static String getCarrier(Context ctx) {
TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getNetworkOperatorName().toLowerCase(Locale.getDefault());
}
public static String getModel() {
return Build.MODEL;
}
public static String getBuildBrand() {
return Build.BRAND;
}
public static String getBuildHost() {
return Build.HOST;
}
public static String getBuildTags() {
return Build.TAGS;
}
public static long getBuildTime() {
return Build.TIME;
}
public static String getBuildUser() {
return Build.USER;
}
public static String getBuildVersionRelease() {
return Build.VERSION.RELEASE;
}
public static String getBuildVersionCodename() {
return Build.VERSION.CODENAME;
}
public static String getBuildVersionIncremental() {
return Build.VERSION.INCREMENTAL;
}
public static int getBuildVersionSDK() {
return Build.VERSION.SDK_INT;
}
public static String getBuildID() {
return Build.ID;
}
public static String[] getSupportedABIS() {
String[] result = new String[]{"-"};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
result = Build.SUPPORTED_ABIS;
}
if (result == null || result.length == 0) {
result = new String[]{"-"};
}
return result;
}
public static String getManufacturer() {
return Build.MANUFACTURER;
}
public static String getBootloader() {
return Build.BOOTLOADER;
}
public static String getScreenDisplayID(Context ctx) {
WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
return String.valueOf(wm.getDefaultDisplay().getDisplayId());
}
public static String getDisplayVersion() {
return Build.DISPLAY;
}
public static String getLanguage() {
return Locale.getDefault().getLanguage();
}
public static String getCountry(Context ctx) {
TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
Locale locale = Locale.getDefault();
return tm.getSimState() == TelephonyManager.SIM_STATE_READY ? tm.getSimCountryIso().toLowerCase(Locale.getDefault()) : locale.getCountry().toLowerCase(locale);
}
public static String getOSVersion() {
return Build.VERSION.RELEASE;
}
//<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
public static String getGSFID(Context context) {
String result;
final Uri URI = Uri.parse("content://com.google.android.gsf.gservices");
final String ID_KEY = "android_id";
String[] params = {ID_KEY};
Cursor c = context.getContentResolver().query(URI, null, null, params, null);
if (c == null || !c.moveToFirst() || c.getColumnCount() < 2) {
return null;
} else {
result = Long.toHexString(Long.parseLong(c.getString(1)));
}
c.close();
return result;
}
//<uses-permission android:name="android.permission.BLUETOOTH"/>
@SuppressWarnings("MissingPermission")
public static String getBluetoothMAC(Context context) {
String result = null;
try {
if (context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH)
== PackageManager.PERMISSION_GRANTED) {
BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
result = bta.getAddress();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String getPsuedoUniqueID() {
String devIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
devIDShort += (Build.SUPPORTED_ABIS[0].length() % 10);
} else {
devIDShort += (Build.CPU_ABI.length() % 10);
}
devIDShort += (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
String serial;
try {
serial = Build.class.getField("SERIAL").get(null).toString();
return new UUID(devIDShort.hashCode(), serial.hashCode()).toString();
} catch (Exception e) {
serial = "ESYDV000";
}
return new UUID(devIDShort.hashCode(), serial.hashCode()).toString();
}
public static String getFingerprint() {
return Build.FINGERPRINT;
}
public static String getHardware() {
return Build.HARDWARE;
}
public static String getProduct() {
return Build.PRODUCT;
}
public static String getDevice() {
return Build.DEVICE;
}
public static String getBoard() {
return Build.BOARD;
}
public static String getRadioVersion() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ? Build.getRadioVersion() : "";
}
public static String getUA(Context ctx) {
final String system_ua = System.getProperty("http.agent");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return new WebView(ctx).getSettings().getDefaultUserAgent(ctx) + "__" + system_ua;
} else {
return new WebView(ctx).getSettings().getUserAgentString() + "__" + system_ua;
}
}
public static String getDensity(Context ctx) {
String densityStr = null;
final int density = ctx.getResources().getDisplayMetrics().densityDpi;
switch (density) {
case DisplayMetrics.DENSITY_LOW:
densityStr = "LDPI";
break;
case DisplayMetrics.DENSITY_MEDIUM:
densityStr = "MDPI";
break;
case DisplayMetrics.DENSITY_TV:
densityStr = "TVDPI";
break;
case DisplayMetrics.DENSITY_HIGH:
densityStr = "HDPI";
break;
case DisplayMetrics.DENSITY_XHIGH:
densityStr = "XHDPI";
break;
case DisplayMetrics.DENSITY_400:
densityStr = "XMHDPI";
break;
case DisplayMetrics.DENSITY_XXHIGH:
densityStr = "XXHDPI";
break;
case DisplayMetrics.DENSITY_XXXHIGH:
densityStr = "XXXHDPI";
break;
}
return densityStr;
}
//<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
@SuppressWarnings("MissingPermission")
public static String[] getGoogleAccounts(Context ctx) {
if (ctx.checkCallingOrSelfPermission(Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) {
Account[] accounts = AccountManager.get(ctx).getAccountsByType("com.google");
String[] result = new String[accounts.length];
for (int i = 0; i < accounts.length; i++) {
result[i] = accounts[i].name;
}
return result;
}
return null;
}
}
DateUtil.java
日期工具类相关方法:
formatDataTime : 格式化日期时间
formatDate : 格式化日期
formatTime : 格式化时间
formatDateCustom : 自定义格式的格式化日期时间
string2Date : 将时间字符串转换成Date
getDate : 获取系统日期
getTime : 获取系统时间
getDateTime : 获取系统日期时间
subtractDate : 计算两个时间差
getDateAfter : 得到几天后的时间
getWeekOfMonth : 获取当前时间为本月的第几周
getDayOfWeek : 获取当前时间为本周的第几天
public class DateUtils {
private static final SimpleDateFormat DATE_FORMAT_DATETIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final SimpleDateFormat DATE_FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat DATE_FORMAT_TIME = new SimpleDateFormat("HH:mm:ss");
public static String formatDataTime(long date) {
return DATE_FORMAT_DATETIME.format(new Date(date));
}
public static String formatDate(long date) {
return DATE_FORMAT_DATE.format(new Date(date));
}
public static String formatTime(long date) {
return DATE_FORMAT_TIME.format(new Date(date));
}
public static String formatDateCustom(String beginDate, String format) {
return new SimpleDateFormat(format).format(new Date(Long.parseLong(beginDate)));
}
public static String formatDateCustom(Date beginDate, String format) {
return new SimpleDateFormat(format).format(beginDate);
}
public static Date string2Date(String s, String style) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.applyPattern(style);
Date date = null;
if (s == null || s.length() < 6) {
return null;
}
try {
date = simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static String getTime() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
return cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND);
}
public static String getDate() {
return new SimpleDateFormat("yyyyMMdd").format(System.currentTimeMillis());
}
public static String getDateTime(){
return DATE_FORMAT_DATETIME.format(System.currentTimeMillis());
}
public static String getDateTime(String format){
return new SimpleDateFormat(format).format(System.currentTimeMillis());
}
public static long subtractDate(Date dateStart, Date dateEnd) {
return dateEnd.getTime() - dateStart.getTime();
}
public static Date getDateAfter(Date d, int day) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
return now.getTime();
}
public static int getWeekOfMonth() {
Calendar calendar = Calendar.getInstance();
int week = calendar.get(Calendar.WEEK_OF_MONTH);
return week - 1;
}
public static int getDayOfWeek() {
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
if (day == 1) {
day = 7;
} else {
day = day - 1;
}
return day;
}
}
DensityUtil.java
屏幕工具类相关方法:
dip2px : dp转像素
dip2sp : dip转sp
px2dip : 像素转dp
px2sp : 像素转sp
sp2px : sp转像素
sp2dip : sp转dip
getScreenW : 获取屏幕宽度
getScreenH : 获取屏幕高度
getScreenRealSize : 获取屏幕的真实高度
getStatusBarH : 获取状态栏高度
getNavigationBarrH : 获取导航栏高度
public class DensityUtil {
public static int dip2px(Context c, float dpValue) {
final float scale = c.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static int dip2sp(Context c, float dpValue) {
return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, c.getResources().getDisplayMetrics()));
}
public static int px2dip(Context c, float pxValue) {
final float scale = c.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static int px2sp(Context c, float pxValue) {
float fontScale = c.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
public static int sp2px(Context c, float spValue) {
float fontScale = c.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
public static int sp2dip(Context c, float spValue) {
return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, c.getResources().getDisplayMetrics()));
}
public static int getScreenW(Context c) {
return c.getResources().getDisplayMetrics().widthPixels;
}
public static int getScreenH(Context c) {
return c.getResources().getDisplayMetrics().heightPixels;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static int getScreenRealH(Context context) {
int h;
WindowManager winMgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = winMgr.getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= 17) {
display.getRealMetrics(dm);
h = dm.heightPixels;
} else {
try {
Method method = Class.forName("android.view.Display").getMethod("getRealMetrics", DisplayMetrics.class);
method.invoke(display, dm);
h = dm.heightPixels;
} catch (Exception e) {
display.getMetrics(dm);
h = dm.heightPixels;
}
}
return h;
}
public static int getStatusBarH(Context context) {
Class<?> c;
Object obj;
Field field;
int statusBarHeight = 0;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return statusBarHeight;
}
public static int getNavigationBarrH(Context c) {
Resources resources = c.getResources();
int identifier = resources.getIdentifier("navigation_bar_height", "dimen", "android");
return resources.getDimensionPixelOffset(identifier);
}
}
FileUtils.java
文件工具类相关方法:
closeIO : 关闭IO流
isFileExist : 文件是否存在
writeFile : 将字符串写入到文件
readFile : 从文件中读取字符串
readFile : 从文件中读取字符串(可设置编码)
copyFile : 复制文件
copyFileFast : 快速复制
shareFile : 分享文件
zip : zip压缩
unzip : zip解压
formatFileSize : 格式化文件大小
Stream2File : 将输入流写入到文件
createFolder : 创建文件夹
createFolder : 创建文件夹(支持覆盖已存在的同名文件夹)
getFileName : 获取文件名
getFileSize : 获取文件大小
rename : 重名名文件\文件夹
getFolderName : 获取文件夹名称
getFilesArray : 获取文件夹下所有文件
deleteFile : 删除文件
deleteFileByDirectory : 删除目录下的所有文件
openImage : 打开图片
openVideo : 打开视频
openURL : 打开URL
downloadFile : 下载文件
upgradeApp : 通过APKURL升级应用
isSDCardAvailable : 是否挂在SDCard
getAppExternalPath : 获取应用在SDCard上的工作路径
getExtraPath : 获取SDCard上目录的路径
public class FileUtils {
public static void closeIO(Closeable... closeables) {
if (null == closeables || closeables.length <= 0) {
return;
}
for (Closeable cb : closeables) {
try {
if (null == cb) {
continue;
}
cb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static boolean deleteFile(String filename) {
return new File(filename).delete();
}
public static void deleteFileByDirectory(File directory) {
if (directory.exists() && directory.isDirectory()) {
for (File file : directory.listFiles()) {
file.delete();
}
}
}
public static boolean isFileExist(String filePath) {
return new File(filePath).exists();
}
public static boolean writeFile(String filename, String content, boolean append) {
boolean isSuccess = false;
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(filename, append));
bufferedWriter.write(content);
isSuccess = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
closeIO(bufferedWriter);
}
return isSuccess;
}
public static String readFile(String filename) {
File file = new File(filename);
BufferedReader bufferedReader = null;
String str = null;
try {
if (file.exists()) {
bufferedReader = new BufferedReader(new FileReader(filename));
str = bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
closeIO(bufferedReader);
}
return str;
}
public static StringBuilder readFile(File file, String charsetName) {
StringBuilder fileContent = new StringBuilder("");
if (file == null || !file.isFile()) {
return null;
}
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
if (!fileContent.toString().equals("")) {
fileContent.append("\r\n");
}
fileContent.append(line);
}
return fileContent;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
closeIO(reader);
}
}
public static void copyFile(InputStream in, OutputStream out) {
try {
byte[] b = new byte[2 * 1024 * 1024]; //2M memory
int len = -1;
while ((len = in.read(b)) > 0) {
out.write(b, 0, len);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
closeIO(in, out);
}
}
public static void copyFileFast(File in, File out) {
FileChannel filein = null;
FileChannel fileout = null;
try {
filein = new FileInputStream(in).getChannel();
fileout = new FileOutputStream(out).getChannel();
filein.transferTo(0, filein.size(), fileout);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeIO(filein, fileout);
}
}
public static void shareFile(Context context, String title, String filePath) {
Intent intent = new Intent(Intent.ACTION_SEND);
Uri uri = Uri.parse("file://" + filePath);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(intent, title));
}
public static void zip(InputStream is, OutputStream os) {
GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(os);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) != -1) {
gzip.write(buf, 0, len);
gzip.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
closeIO(is, gzip);
}
}
public static void unzip(InputStream is, OutputStream os) {
GZIPInputStream gzip = null;
try {
gzip = new GZIPInputStream(is);
byte[] buf = new byte[1024];
int len;
while ((len = gzip.read(buf)) != -1) {
os.write(buf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
closeIO(gzip, os);
}
}
public static String formatFileSize(Context context, long size) {
return Formatter.formatFileSize(context, size);
}
public static void Stream2File(InputStream is, File file) {
byte[] b = new byte[1024];
int len;
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
closeIO(is, os);
}
}
public static boolean createFolder(String filePath) {
return createFolder(filePath, false);
}
public static boolean createFolder(String filePath, boolean recreate) {
String folderName = getFolderName(filePath);
if (folderName == null || folderName.length() == 0 || folderName.trim().length() == 0) {
return false;
}
File folder = new File(folderName);
if (folder.exists()) {
if (recreate) {
deleteFile(folderName);
return folder.mkdirs();
} else {
return true;
}
} else {
return folder.mkdirs();
}
}
public static String getFileName(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
}
public static long getFileSize(String filepath) {
if (TextUtils.isEmpty(filepath)) {
return -1;
}
File file = new File(filepath);
return (file.exists() && file.isFile() ? file.length() : -1);
}
public static boolean rename(String filepath, String newName) {
File file = new File(filepath);
return file.exists() && file.renameTo(new File(newName));
}
public static String getFolderName(String filePath) {
if (filePath == null || filePath.length() == 0 || filePath.trim().length() == 0) {
return filePath;
}
int filePos = filePath.lastIndexOf(File.separator);
return (filePos == -1) ? "" : filePath.substring(0, filePos);
}
public static ArrayList<File> getFilesArray(String path) {
File file = new File(path);
File files[] = file.listFiles();
ArrayList<File> listFile = new ArrayList<File>();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
listFile.add(files[i]);
}
if (files[i].isDirectory()) {
listFile.addAll(getFilesArray(files[i].toString()));
}
}
}
return listFile;
}
public static boolean deleteFiles(String folder) {
if (folder == null || folder.length() == 0 || folder.trim().length() == 0) {
return true;
}
File file = new File(folder);
if (!file.exists()) {
return true;
}
if (file.isFile()) {
return file.delete();
}
if (!file.isDirectory()) {
return false;
}
for (File f : file.listFiles()) {
if (f.isFile()) {
f.delete();
} else if (f.isDirectory()) {
deleteFile(f.getAbsolutePath());
}
}
return file.delete();
}
public static void openImage(Context mContext, String imagePath) {
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromFile(new File(imagePath));
intent.setDataAndType(uri, "image/*");
mContext.startActivity(intent);
}
public static void openVideo(Context mContext, String videoPath) {
Intent intent = new Intent("android.intent.action.VIEW");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("oneshot", 0);
intent.putExtra("configchange", 0);
Uri uri = Uri.fromFile(new File(videoPath));
intent.setDataAndType(uri, "video/*");
mContext.startActivity(intent);
}
public static void openURL(Context mContext, String url) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
mContext.startActivity(intent);
}
public static void downloadFile(Context context, String fileurl) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileurl));
request.setDestinationInExternalPublicDir("/Download/", fileurl.substring(fileurl.lastIndexOf("/") + 1));
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
}
public static boolean isSDCardAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
public static String getAppExternalPath(Context context) {
/* StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory().getAbsolutePath());
sb.append(File.separator);
sb.append("Android/data/");
sb.append(packageName);
return sb.toString();*/
return context.getObbDir().getAbsolutePath();
}
@Deprecated
public static String getExtraPath(String folder) {
String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + folder;
File file = new File(storagePath);
if (!file.exists()) {
file.mkdir();
}
return storagePath;
}
}
StringUtils.java
字符串工具类相关方法:
getChsAscii : 汉字转成ASCII码
convert : 单字解析
getSelling : 词组解析
parseEmpty : 将null转化为""
isEmpty : 是否是空字符串
chineseLength : 中文长度
strLength : 字符串长度
subStringLength : 获取指定长度的字符所在位置
isChinese : 是否是中文
isContainChinese : 是否包含中文
strFormat2 : 不足2位前面补0
convert2Int : 类型安全转换
decimalFormat : 指定小数输出
public class StringUtils {
/**
* The pyvalue.
*/
private static int[] pyvalue = new int[]{-20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032,
-20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728,
-19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261,
-19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961,
-18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490,
-18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988,
-17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692,
-17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733,
-16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419,
-16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959,
-15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631,
-15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180,
-15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941,
-14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857,
-14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353,
-14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094,
-14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831,
-13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329,
-13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860,
-12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300,
-12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358,
-11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014,
-10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309,
-10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254};
/**
* The pystr.
*/
public static String[] pystr = new String[]{"a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian",
"biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", "chao", "che",
"chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou", "cu", "cuan",
"cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du",
"duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang",
"gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang",
"hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian",
"jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken",
"keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng",
"li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai",
"man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai",
"nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan",
"nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu",
"qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re",
"ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha",
"shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun",
"shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao",
"tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi",
"xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi",
"yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha",
"zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui",
"zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo"};
public static int getChsAscii(String chs) {
int asc = 0;
try {
byte[] bytes = chs.getBytes("gb2312");
/*if (bytes == null || bytes.length > 2 || bytes.length <= 0) {
throw new RuntimeException("illegal resource string");
}*/
if (bytes.length == 1) {
asc = bytes[0];
}
if (bytes.length == 2) {
int hightByte = 256 + bytes[0];
int lowByte = 256 + bytes[1];
asc = (256 * hightByte + lowByte) - 256 * 256;
}
} catch (Exception e) {
System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);
}
return asc;
}
public static String convert(String str) {
String result = null;
int ascii = getChsAscii(str);
if (ascii > 0 && ascii < 160) {
result = String.valueOf((char) ascii);
} else {
for (int i = (pyvalue.length - 1); i >= 0; i--) {
if (pyvalue[i] <= ascii) {
result = pystr[i];
break;
}
}
}
return result;
}
public String getSelling(String chs) {
String key, value;
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < chs.length(); i++) {
key = chs.substring(i, i + 1);
if (key.getBytes().length >= 2) {
value = convert(key);
if (value == null) {
value = "unknown";
}
} else {
value = key;
}
buffer.append(value);
}
return buffer.toString();
}
public static String parseEmpty(String str) {
if (str == null || "null".equals(str.trim())) {
str = "";
}
return str.trim();
}
public static boolean isEmpty(String str) {
return str == null || str.trim().length() == 0;
}
public static int chineseLength(String str) {
int valueLength = 0;
String chinese = "[\u0391-\uFFE5]";
if (!isEmpty(str)) {
for (int i = 0; i < str.length(); i++) {
String temp = str.substring(i, i + 1);
if (temp.matches(chinese)) {
valueLength += 2;
}
}
}
return valueLength;
}
public static int strLength(String str) {
int valueLength = 0;
String chinese = "[\u0391-\uFFE5]";
if (!isEmpty(str)) {
for (int i = 0; i < str.length(); i++) {
String temp = str.substring(i, i + 1);
if (temp.matches(chinese)) {
valueLength += 2;
} else {
valueLength += 1;
}
}
}
return valueLength;
}
public static int subStringLength(String str, int maxL) {
int currentIndex = 0;
int valueLength = 0;
String chinese = "[\u0391-\uFFE5]";
for (int i = 0; i < str.length(); i++) {
String temp = str.substring(i, i + 1);
if (temp.matches(chinese)) {
valueLength += 2;
} else {
valueLength += 1;
}
if (valueLength >= maxL) {
currentIndex = i;
break;
}
}
return currentIndex;
}
public static Boolean isChinese(String str) {
Boolean isChinese = true;
String chinese = "[\u0391-\uFFE5]";
if (!isEmpty(str)) {
for (int i = 0; i < str.length(); i++) {
String temp = str.substring(i, i + 1);
isChinese = temp.matches(chinese);
}
}
return isChinese;
}
public static Boolean isContainChinese(String str) {
Boolean isChinese = false;
String chinese = "[\u0391-\uFFE5]";
if (!isEmpty(str)) {
for (int i = 0; i < str.length(); i++) {
String temp = str.substring(i, i + 1);
isChinese = temp.matches(chinese);
}
}
return isChinese;
}
public static String strFormat2(String str) {
try {
if (str.length() <= 1) {
str = "0" + str;
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public static int convert2Int(Object value, int defaultValue) {
if (value == null || "".equals(value.toString().trim())) {
return defaultValue;
}
try {
return Double.valueOf(value.toString()).intValue();
} catch (Exception e) {
e.printStackTrace();
return defaultValue;
}
}
public static String decimalFormat(String s, String format) {
DecimalFormat decimalFormat = new DecimalFormat(format);
return decimalFormat.format(s);
}
}
SystemUtils.java
系统工具类相关方法:
sendSMS : 调用系统发送短信
forwardToDial : 跳转到拨号
sendMail : 发邮件
openWeb : 打开浏览器
openContacts : 打开联系人
openSettings : 打开系统设置
@SuppressLint("SimpleDateFormat")
public final class SystemUtils {
public static void sendSMS(Context cxt, String smsBody) {
Uri smsToUri = Uri.parse("smsto:");
Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
intent.putExtra("sms_body", smsBody);
cxt.startActivity(intent);
}
public static void forwardToDial(Activity activity, String phoneNumber) {
if (activity != null && !TextUtils.isEmpty(phoneNumber)) {
activity.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
}
}
public static void sendMail(Context mContext, String mailID) {
Uri uri = Uri.parse("mailto:" + mailID);
mContext.startActivity(new Intent(Intent.ACTION_SENDTO, uri));
}
public static void openWeb(Context context, String url) {
Uri uri = Uri.parse(url);
context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
public static void openContacts(Activity context, int requestCode) {
Uri uri = Uri.parse("content://contacts/people");
context.startActivityForResult(new Intent(Intent.ACTION_PICK, uri), requestCode);
}
public static void openSettings(Activity context, String action) {
Intent intent = new Intent();
ComponentName comp = new ComponentName("com.android.settings", action);
intent.setComponent(comp);
intent.setAction("android.intent.action.VIEW");
context.startActivityForResult(intent, 0);
}
public static void hideKeyBoard(Activity aty) {
((InputMethodManager) aty.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(aty.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
/* public static void openInputKeyBoard(Context mContext, EditText mEditText){
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 closeInputKeyBoard(Context mContext, EditText mEditText){
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}*/
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())) {
return appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
}
}
return false;
}
public static boolean isSleeping(Context context) {
KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
return kgMgr.inKeyguardRestrictedInputMode();
}
public static void installApk(Context context, File apkfile) {
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setType("application/vnd.android.package-archive");
intent.setData(Uri.fromFile(apkfile));
intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
private static final String suSearchPaths[] = {"/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/"};
public static boolean isRooted() {
File file;
boolean flag1 = false;
for (String suSearchPath : suSearchPaths) {
file = new File(suSearchPath + "su");
if (file.isFile() && file.exists()) {
flag1 = true;
break;
}
}
return flag1;
}
public static boolean isRunningOnEmulator() {
return Build.BRAND.contains("generic")
|| Build.DEVICE.contains("generic")
|| Build.PRODUCT.contains("sdk")
|| Build.HARDWARE.contains("goldfish")
|| Build.MANUFACTURER.contains("Genymotion")
|| Build.PRODUCT.contains("vbox86p")
|| Build.DEVICE.contains("vbox86p")
|| Build.HARDWARE.contains("vbox86");
}
public static void goHome(Context context) {
Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
context.startActivity(mHomeIntent);
}
public static String hexdigest(byte[] paramArrayOfByte) {
final char[] hexDigits = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102};
try {
MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
localMessageDigest.update(paramArrayOfByte);
byte[] arrayOfByte = localMessageDigest.digest();
char[] arrayOfChar = new char[32];
for (int i = 0, j = 0; ; i++, j++) {
if (i >= 16) {
return new String(arrayOfChar);
}
int k = arrayOfByte[i];
arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
arrayOfChar[++j] = hexDigits[(k & 0xF)];
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static int getDeviceUsableMemory(Context cxt) {
ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo mi = new MemoryInfo();
am.getMemoryInfo(mi);
return (int) (mi.availMem / (1024 * 1024));
}
public static int gc(Context cxt) {
//long i = getDeviceUsableMemory(cxt);
int count = 0;
ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> serviceList = am.getRunningServices(100);
if (serviceList != null)
for (RunningServiceInfo service : serviceList) {
if (service.pid == android.os.Process.myPid())
continue;
try {
android.os.Process.killProcess(service.pid);
count++;
} catch (Exception e) {
e.getStackTrace();
//continue;
}
}
List<RunningAppProcessInfo> processList = am.getRunningAppProcesses();
if (processList != null)
for (RunningAppProcessInfo process : processList) {
if (process.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
String[] pkgList = process.pkgList;
for (String pkgName : pkgList) {
try {
am.killBackgroundProcesses(pkgName);
count++;
} catch (Exception e) {
e.getStackTrace();
//continue;
}
}
}
}
return count;
}
public static String getProcessName(Context appContext) {
String currentProcessName = null;
int pid = android.os.Process.myPid();
ActivityManager manager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
if (processInfo.pid == pid) {
currentProcessName = processInfo.processName;
break;
}
}
return currentProcessName;
}
public static void createDeskShortCut(Context cxt, String shortCutName, int icon, Class<?> cls) {
Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
shortcutIntent.putExtra("duplicate", false);
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortCutName);
Parcelable ico = Intent.ShortcutIconResource.fromContext(cxt.getApplicationContext(), icon);
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, ico);
Intent intent = new Intent(cxt, cls);
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
cxt.sendBroadcast(shortcutIntent);
}
public static void createShortcut(Context ctx, String shortCutName, int iconId, Intent presentIntent) {
Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
shortcutIntent.putExtra("duplicate", false);
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortCutName);
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(ctx, iconId));
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, presentIntent);
ctx.sendBroadcast(shortcutIntent);
}
public static void shareText(Context ctx, String title, String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
//intent.putExtra(Intent.EXTRA_SUBJECT, title);
intent.putExtra(Intent.EXTRA_TEXT, text);
ctx.startActivity(Intent.createChooser(intent, title));
/* List<ResolveInfo> ris = getShareTargets(ctx);
if (ris != null && ris.size() > 0) {
ctx.startActivity(Intent.createChooser(intent, title));
}*/
}
public static void shareFile(Context ctx, String title, String filePath) {
FileUtils.shareFile(ctx, title, filePath);
}
public static List<ResolveInfo> getShareTargets(Context ctx) {
Intent intent = new Intent(Intent.ACTION_SEND, null);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setType("text/plain");
PackageManager pm = ctx.getPackageManager();
return pm.queryIntentActivities(intent, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
}
public static String getCurrentLanguage() {
return Locale.getDefault().getLanguage();
}
public static String getLanguage(Context ctx) {
if (ctx != null) {
return ctx.getResources().getConfiguration().locale.getLanguage();
}
return null;
}
//<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
public static boolean isGpsEnabled(Context context) {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public static void showSoftInputMethod(Context context, EditText editText) {
if (context != null && editText != null) {
editText.requestFocus();
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(editText, 0);
}
}
public static void closeSoftInputMethod(Context context, EditText editText) {
if (context != null && editText != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
}
public static void showSoftInput(Context context) {
InputMethodManager inputMethodManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
public static void closeSoftInput(Context context) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null && ((Activity) context).getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
public static void toWeChatScan(Context context) {
try {
Uri uri = Uri.parse("weixin://dl/scan");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
} catch (Exception e) {
Toast.makeText(context, R.string.wechaterr, Toast.LENGTH_SHORT).show();
}
}
public static void toAliPayScan(Context context) {
try {
Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=10000007");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
} catch (Exception e) {
Toast.makeText(context, R.string.alipayerr, Toast.LENGTH_SHORT).show();
}
}
public static void toAliPayPayCode(Context context) {
try {
Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=20000056");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
} catch (Exception e) {
Toast.makeText(context, R.string.alipayerr, Toast.LENGTH_SHORT).show();
}
}
public static int getRandomNumber(int min, int max) {
return new Random().nextInt(max) % (max - min + 1) + min;
}
}