文章目录
AppUtils.java
-
-
- AppUtils.java
- DeviceUtils.java
- NetUtils.java
- DateUtil.java
- DensityUtil.java
- FileUtils.java
- StringUtils.java
- SystemUtils.java
- SPUtils.java
- VerificationUtils.java
- L.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; } // 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; } // @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; } // @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; } }NetUtils.java
- 网络工具类
getNetworkType : 获取网络类型 getNetworkTypeName : 获取网络名称 isConnected : 检查网络状态 isNetworkAvailable : 网络可用性 isWiFi : 是否wifi openNetSetting : 打开网络设置界面 setWifiEnabled : 设置wifi状态 setDataEnabled : 设置数据流量状态 getWifiScanResults : 获取wifi列表 getScanResultsByBSSID : 过滤扫描结果 getWifiConnectionInfo : 获取wifi连接信息
public class NetUtils { public static final String NETWORK_TYPE_WIFI = "wifi"; public static final String NETWORK_TYPE_3G = "3g"; public static final String NETWORK_TYPE_2G = "2g"; public static final String NETWORK_TYPE_WAP = "wap"; public static final String NETWORK_TYPE_UNKNOWN = "unknown"; public static final String NETWORK_TYPE_DISCONNECT = "disconnect"; public static int getNetworkType(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager == null ? null : connectivityManager.getActiveNetworkInfo(); return networkInfo == null ? -1 : networkInfo.getType(); } public static String getNetworkTypeName(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo; String type = NETWORK_TYPE_DISCONNECT; if (manager == null || (networkInfo = manager.getActiveNetworkInfo()) == null) { return type; } if (networkInfo.isConnected()) { String typeName = networkInfo.getTypeName(); if ("WIFI".equalsIgnoreCase(typeName)) { type = NETWORK_TYPE_WIFI; } else if ("MOBILE".equalsIgnoreCase(typeName)) { //String proxyHost = android.net.Proxy.getDefaultHost();//deprecated String proxyHost = System.getProperty("http.proxyHost"); type = TextUtils.isEmpty(proxyHost) ? (isFastMobileNetwork(context) ? NETWORK_TYPE_3G : NETWORK_TYPE_2G) : NETWORK_TYPE_WAP; } else { type = NETWORK_TYPE_UNKNOWN; } } return type; } public static boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info != null && info.isConnected()) { if (info.getState() == NetworkInfo.State.CONNECTED) { return true; } } return false; } public static boolean isNetworkAvailable(Context context) { if (context == null) { return false; } try { ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getActiveNetworkInfo(); return info.isAvailable(); } } catch (Exception e) { return false; } return false; } public static boolean isWiFi(Context cxt) { ConnectivityManager cm = (ConnectivityManager) cxt.getSystemService(Context.CONNECTIVITY_SERVICE); // wifi的状态:ConnectivityManager.TYPE_WIFI // 3G的状态:ConnectivityManager.TYPE_MOBILE return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; } //unchecked public static void openNetSetting(Activity act) { Intent intent = new Intent(); ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings"); intent.setComponent(cm); intent.setAction("android.intent.action.VIEW"); act.startActivityForResult(intent, 0); } /** * Whether is fast mobile network */ private static boolean isFastMobileNetwork(Context context) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager == null) { return false; } switch (telephonyManager.getNetworkType()) { case TelephonyManager.NETWORK_TYPE_1xRTT: return false; case TelephonyManager.NETWORK_TYPE_CDMA: return false; case TelephonyManager.NETWORK_TYPE_EDGE: return false; case TelephonyManager.NETWORK_TYPE_EVDO_0: return true; case TelephonyManager.NETWORK_TYPE_EVDO_A: return true; case TelephonyManager.NETWORK_TYPE_GPRS: return false; case TelephonyManager.NETWORK_TYPE_HSDPA: return true; case TelephonyManager.NETWORK_TYPE_HSPA: return true; case TelephonyManager.NETWORK_TYPE_HSUPA: return true; case TelephonyManager.NETWORK_TYPE_UMTS: return true; case TelephonyManager.NETWORK_TYPE_EHRPD: return true; case TelephonyManager.NETWORK_TYPE_EVDO_B: return true; case TelephonyManager.NETWORK_TYPE_HSPAP: return true; case TelephonyManager.NETWORK_TYPE_IDEN: return false; case TelephonyManager.NETWORK_TYPE_LTE: return true; case TelephonyManager.NETWORK_TYPE_UNKNOWN: return false; default: return false; } } public static void setWifiEnabled(Context context, boolean enabled) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(enabled); } public static void setDataEnabled(Context context, boolean enabled) { ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); Class<?> conMgrClass = null; Field iConMgrField = null; Object iConMgr = null; Class<?> iConMgrClass = null; Method setMobileDataEnabledMethod = null; try { conMgrClass = Class.forName(conMgr.getClass().getName()); iConMgrField = conMgrClass.getDeclaredField("mService"); iConMgrField.setAccessible(true); iConMgr = iConMgrField.get(conMgr); iConMgrClass = Class.forName(iConMgr.getClass().getName()); setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConMgr, enabled); } catch (Exception e) { e.printStackTrace(); } } public static List<ScanResult> getWifiScanResults(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); return wifiManager.startScan() ? wifiManager.getScanResults() : null; } public static ScanResult getScanResultsByBSSID(Context context, String bssid) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); ScanResult scanResult = null; boolean f = wifiManager.startScan(); if (!f) { getScanResultsByBSSID(context, bssid); } List<ScanResult> list = wifiManager.getScanResults(); if (list != null) { for (int i = 0; i < list.size(); i++) { scanResult = list.get(i); if (scanResult.BSSID.equals(bssid)) { break; } } } return scanResult; } public static WifiInfo getWifiConnectionInfo(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); return wifiManager.getConnectionInfo(); } }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)); /* Listris = 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; } // 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; } }SPUtils.java
- SP 临时存储工具类
getInstance: 获取SP实例 put : SP中写入数据 getString : SP中读取String getInt : SP中读取int getLong : SP中读取long getFloat : SP中读取float getBoolean : SP中读取boolean getAll : SP中获取所有键值对 remove : SP中移除该key contains : SP中是否存在该key clear : SP中清除所有数据
public class SPUtils { private static Map<String, SPUtils> sSPMap = new HashMap<>(); private SharedPreferences sp; /** * 获取SP实例 * * @return {@link SPUtils} */ public static SPUtils getInstance() { return getInstance(""); } /** * 获取SP实例 * * @param spName sp名 * @return {@link SPUtils} */ public static SPUtils getInstance(String spName) { if (isSpace(spName)) spName = "spUtils"; SPUtils sp = sSPMap.get(spName); if (sp == null) { sp = new SPUtils(spName); sSPMap.put(spName, sp); } return sp; } private SPUtils(String spName) { sp = ServerApplication.CONTEXT.getSharedPreferences(spName, Context.MODE_PRIVATE); } /** * SP中写入String * * @param key 键 * @param value 值 */ public void put(@NonNull String key, @NonNull String value) { sp.edit().putString(key, value).apply(); } /** * SP中读取String * * @param key 键 * @return 存在返回对应值,不存在返回默认值{@code null} */ public String getString(@NonNull String key) { return getString(key, ""); } /** * SP中读取String * * @param key 键 * @param defaultValue 默认值 * @return 存在返回对应值,不存在返回默认值{@code defaultValue} */ public String getString(@NonNull String key, @NonNull String defaultValue) { return sp.getString(key, defaultValue); } /** * SP中写入int * * @param key 键 * @param value 值 */ public void put(@NonNull String key, int value) { sp.edit().putInt(key, value).apply(); } /** * SP中读取int * * @param key 键 * @return 存在返回对应值,不存在返回默认值-1 */ public int getInt(@NonNull String key) { return getInt(key, -1); } /** * SP中读取int * * @param key 键 * @param defaultValue 默认值 * @return 存在返回对应值,不存在返回默认值{@code defaultValue} */ public int getInt(@NonNull String key, int defaultValue) { return sp.getInt(key, defaultValue); } /** * SP中写入long * * @param key 键 * @param value 值 */ public void put(@NonNull String key, long value) { sp.edit().putLong(key, value).apply(); } /** * SP中读取long * * @param key 键 * @return 存在返回对应值,不存在返回默认值-1 */ public long getLong(@NonNull String key) { return getLong(key, -1L); } /** * SP中读取long * * @param key 键 * @param defaultValue 默认值 * @return 存在返回对应值,不存在返回默认值{@code defaultValue} */ public long getLong(@NonNull String key, long defaultValue) { return sp.getLong(key, defaultValue); } /** * SP中写入float * * @param key 键 * @param value 值 */ public void put(@NonNull String key, float value) { sp.edit().putFloat(key, value).apply(); } /** * SP中读取float * * @param key 键 * @return 存在返回对应值,不存在返回默认值-1 */ public float getFloat(@NonNull String key) { return getFloat(key, -1f); } /** * SP中读取float * * @param key 键 * @param defaultValue 默认值 * @return 存在返回对应值,不存在返回默认值{@code defaultValue} */ public float getFloat(@NonNull String key, float defaultValue) { return sp.getFloat(key, defaultValue); } /** * SP中写入boolean * * @param key 键 * @param value 值 */ public void put(@NonNull String key, boolean value) { sp.edit().putBoolean(key, value).apply(); } /** * SP中读取boolean * * @param key 键 * @return 存在返回对应值,不存在返回默认值{@code false} */ public boolean getBoolean(@NonNull String key) { return getBoolean(key, false); } /** * SP中读取boolean * * @param key 键 * @param defaultValue 默认值 * @return 存在返回对应值,不存在返回默认值{@code defaultValue} */ public boolean getBoolean(@NonNull String key, boolean defaultValue) { return sp.getBoolean(key, defaultValue); } /** * SP中写入String集合 * * @param key 键 * @param values 值 */ public void put(@NonNull String key, @NonNull Set<String> values) { sp.edit().putStringSet(key, values).apply(); } /** * SP中读取StringSet * * @param key 键 * @return 存在返回对应值,不存在返回默认值{@code null} */ public Set<String> getStringSet(@NonNull String key) { return getStringSet(key, Collections.<String>emptySet()); } /** * SP中读取StringSet * * @param key 键 * @param defaultValue 默认值 * @return 存在返回对应值,不存在返回默认值{@code defaultValue} */ public Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue) { return sp.getStringSet(key, defaultValue); } /** * SP中获取所有键值对 * * @return Map对象 */ public Map<String, ?> getAll() { return sp.getAll(); } /** * SP中移除该key * * @param key 键 */ public void remove(@NonNull String key) { sp.edit().remove(key).apply(); } /** * SP中是否存在该key * * @param key 键 * @return {@code true}: 存在 {@code false}: 不存在 */ public boolean contains(@NonNull String key) { return sp.contains(key); } /** * SP中清除所有数据 */ public void clear() { sp.edit().clear().apply(); } private static boolean isSpace(String s) { if (s == null) return true; for (int i = 0, len = s.length(); i < len; ++i) { if (!Character.isWhitespace(s.charAt(i))) { return false; } } return true; } }VerificationUtils.java
验证工具类
matcherRealName: 判断姓名格式 matcherPhoneNum: 判断手机号格式 (匹配11数字,并且13-19开头) matcherAccount: 判断账号格式 (4-20位字符) matcherPassword: 判断密码格式 (6-12位字母或数字) matcherPassword2: 判断密码格式 (6-12位字母或数字,必须同时包含字母和数字) matcherEmail: 判断邮箱格式 matcherIP: 判断IP地址 matcherUrl: 判断URL (http,https,ftp) matcherVehicleNumber: 判断中国民用车辆号牌 matcherIdentityCard: 判断身份证号码格式 isNumeric: 是否数值型 testRegex: 是否匹配正则 checkPostcode: 匹配中国邮政编码
public class VerificationUtils { public static boolean matcherRealName(String value) { String regex = "^([\\u4e00-\\u9fa5]+|([a-zA-Z]+\\s?)+)$"; return testRegex(regex, value); } public static boolean matcherPhoneNum(String value) { String regex = "^(\\+?\\d{2}-?)?(1[0-9])\\d{9}$"; return testRegex(regex, value); } public static boolean matcherAccount(String value) { String regex = "[\\u4e00-\\u9fa5a-zA-Z0-9\\-]{4,20}"; return testRegex(regex, value); } public static boolean matcherPassword(String value) { String regex = "^[a-zA-Z0-9]{6,12}$"; return testRegex(regex, value); } public static boolean matcherPassword2(String value) { String regex = "(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}"; return testRegex(regex, value); } public static boolean matcherEmail(String value) { // String regex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)" + // "+[a-zA-Z]{2,}$"; String regex = "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+" + "(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+" + "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"; return testRegex(regex, value); } public static boolean matcherIP(String value) { String regex = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\" + "d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\" + "d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b"; return testRegex(regex, value.toLowerCase()); } public static boolean matcherUrl(String value) { //String regex = "^(([hH][tT]{2}[pP][sS]?)|([fF][tT][pP]))\\:\\/\\/[wW]{3}\\.[\\w-]+\\.\\w{2,4}(\\/.*)?$"; String regex = "^(([hH][tT]{2}[pP][sS]?)|([fF][tT][pP]))\\:\\/\\/[\\w-]+\\.\\w{2,4}(\\/.*)?$"; return testRegex(regex, value.toLowerCase()); } public static boolean matcherVehicleNumber(String value) { String regex = "^[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云藏陕甘青宁新渝]?[A-Z][A-HJ-NP-Z0-9学挂港澳练]{5}$"; return testRegex(regex, value.toLowerCase()); } public static boolean matcherIdentityCard(String value) { // String regex = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|" + // "(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|" + // "\\d{3}[Xx])$)$"; // return testRegex(regex, value); IDCardTester idCardTester = new IDCardTester(); return idCardTester.test(value); } private static class IDCardTester { public boolean test(String content) { if (TextUtils.isEmpty(content)) { return false; } final int length = content.length(); if (15 == length) { try { return isOldCNIDCard(content); } catch (NumberFormatException e) { e.printStackTrace(); return false; } } else if (18 == length) { return isNewCNIDCard(content); } else { return false; } } final int[] WEIGHT = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; final char[] VALID = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}; public boolean isNewCNIDCard(String numbers) { numbers = numbers.toUpperCase(); int sum = 0; for (int i = 0; i < WEIGHT.length; i++) { final int cell = Character.getNumericValue(numbers.charAt(i)); sum += WEIGHT[i] * cell; } int index = sum % 11; return VALID[index] == numbers.charAt(17); } public boolean isOldCNIDCard(String numbers) { String yymmdd = numbers.substring(6, 11); boolean aPass = numbers.equals(String.valueOf(Long.parseLong(numbers))); boolean yPass = true; try { new SimpleDateFormat("yyMMdd").parse(yymmdd); } catch (Exception e) { e.printStackTrace(); yPass = false; } return aPass && yPass; } } public static boolean isNumeric(String input) { if (TextUtils.isEmpty(input)) { return false; } char[] chars = input.toCharArray(); int sz = chars.length; boolean hasExp = false; boolean hasDecPoint = false; boolean allowSigns = false; boolean foundDigit = false; int start = (chars[0] == '-' || chars[0] == '+') ? 1 : 0; if (sz > start + 1) { if (chars[start] == '0' && chars[start + 1] == 'x') { int i = start + 2; if (i == sz) { return false; } for (; i < chars.length; i++) { if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F')) { return false; } } return true; } } sz--; int i = start; while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { if (chars[i] >= '0' && chars[i] <= '9') { foundDigit = true; allowSigns = false; } else if (chars[i] == '.') { if (hasDecPoint || hasExp) { return false; } hasDecPoint = true; } else if (chars[i] == 'e' || chars[i] == 'E') { if (hasExp) { return false; } if (!foundDigit) { return false; } hasExp = true; allowSigns = true; } else if (chars[i] == '+' || chars[i] == '-') { if (!allowSigns) { return false; } allowSigns = false; foundDigit = false; } else { return false; } i++; } if (i < chars.length) { if (chars[i] >= '0' && chars[i] <= '9') { return true; } if (chars[i] == 'e' || chars[i] == 'E') { return false; } if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) { return foundDigit; } if (chars[i] == 'l' || chars[i] == 'L') { return foundDigit && !hasExp; } return false; } return !allowSigns && foundDigit; } public static boolean testRegex(String regex, String inputValue) { return Pattern.compile(regex).matcher(inputValue).matches(); } public static boolean checkPostcode(String postcode) { String regex = "[1-9]\\d{5}"; return Pattern.matches(regex, postcode); } }L.java
日志工具类
init: 初始化日志开关和TAG(默认日志为开,TAG为"ghost") v: VERBOSE d: DEBUG i: INFO w: WARN e: ERROR a: ASSERT json: 输出json xml: 输出xml
public class L { private static String TAG = "ghost"; private static boolean LOG_DEBUG = true; private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final int VERBOSE = 2; private static final int DEBUG = 3; private static final int INFO = 4; private static final int WARN = 5; private static final int ERROR = 6; private static final int ASSERT = 7; private static final int JSON = 8; private static final int XML = 9; private static final int JSON_INDENT = 4; public static void init(boolean isDebug, String tag) { TAG = tag; LOG_DEBUG = isDebug; } public static void v(String msg) { log(VERBOSE, null, msg); } public static void v(String tag, String msg) { log(VERBOSE, tag, msg); } public static void d(String msg) { log(DEBUG, null, msg); } public static void d(String tag, String msg) { log(DEBUG, tag, msg); } public static void i(Object... msg) { StringBuilder sb = new StringBuilder(); for (Object obj : msg) { sb.append(obj); sb.append(","); } log(INFO, null, String.valueOf(sb)); } public static void w(String msg) { log(WARN, null, msg); } public static void w(String tag, String msg) { log(WARN, tag, msg); } public static void e(String msg) { log(ERROR, null, msg); } public static void e(String tag, String msg, Throwable tr) { log(ERROR, tag, msg + '\n' + Log.getStackTraceString(tr)); } public static void a(String msg) { log(ASSERT, null, msg); } public static void a(String tag, String msg) { log(ASSERT, tag, msg); } public static void json(String json) { log(JSON, null, json); } public static void json(String tag, String json) { log(JSON, tag, json); } public static void xml(String xml) { log(XML, null, xml); } public static void xml(String tag, String xml) { log(XML, tag, xml); } private static void log(int logType, String tagStr, Object objects) { String[] contents = wrapperContent(tagStr, objects); String tag = contents[0]; String msg = contents[1]; String headString = contents[2]; if (LOG_DEBUG) { switch (logType) { case VERBOSE: case DEBUG: case INFO: case WARN: case ERROR: case ASSERT: printDefault(logType, tag, headString + msg); break; case JSON: printJson(tag, msg, headString); break; case XML: printXml(tag, msg, headString); break; default: break; } } } private static void printDefault(int type, String tag, String msg) { if (TextUtils.isEmpty(tag)) { tag = TAG; } printLine(tag, true); int maxLength = 4000; int countOfSub = msg.length(); if (countOfSub > maxLength) { for (int i = 0; i < countOfSub; i += maxLength) { if (i + maxLength < countOfSub) { printSub(type, tag, msg.substring(i, i + maxLength)); } else { printSub(type, tag, msg.substring(i, countOfSub)); } } } else { printSub(type, tag, msg); } printLine(tag, false); } private static void printSub(int type, String tag, String msg) { switch (type) { case VERBOSE: Log.v(tag, msg); break; case DEBUG: Log.d(tag, msg); break; case INFO: Log.i(tag, msg); break; case WARN: Log.w(tag, msg); break; case ERROR: Log.e(tag, msg); break; case ASSERT: Log.wtf(tag, msg); break; } } private static void printJson(String tag, String json, String headString) { if (TextUtils.isEmpty(json)) { d("Empty/Null json content"); return; } if (TextUtils.isEmpty(tag)) { tag = TAG; } String message; try { if (json.startsWith("{")) { JSONObject jsonObject = new JSONObject(json); message = jsonObject.toString(JSON_INDENT); } else if (json.startsWith("[")) { JSONArray jsonArray = new JSONArray(json); message = jsonArray.toString(JSON_INDENT); } else { message = json; } } catch (JSONException e) { message = json; } printLine(tag, true); message = headString + LINE_SEPARATOR + message; String[] lines = message.split(LINE_SEPARATOR); for (String line : lines) { printSub(DEBUG, tag, "|" + line); } printLine(tag, false); } private static void printXml(String tag, String xml, String headString) { if (TextUtils.isEmpty(tag)) { tag = TAG; } if (xml != null) { try { Source xmlInput = new StreamSource(new StringReader(xml)); StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlOutput); xml = xmlOutput.getWriter().toString().replaceFirst(">", ">\n"); } catch (Exception e) { e.printStackTrace(); } xml = headString + "\n" + xml; } else { xml = headString + "Log with null object"; } printLine(tag, true); String[] lines = xml.split(LINE_SEPARATOR); for (String line : lines) { if (!TextUtils.isEmpty(line)) { printSub(DEBUG, tag, "|" + line); } } printLine(tag, false); } private static String[] wrapperContent(String tag, Object... objects) { if (TextUtils.isEmpty(tag)) { tag = TAG; } StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); StackTraceElement targetElement = stackTrace[5]; String className = targetElement.getClassName(); String[] classNameInfo = className.split("\\."); if (classNameInfo.length > 0) { className = classNameInfo[classNameInfo.length - 1] + ".java"; } String methodName = targetElement.getMethodName(); int lineNumber = targetElement.getLineNumber(); if (lineNumber < 0) { lineNumber = 0; } String methodNameShort = methodName.substring(0, 1).toUpperCase() + methodName.substring(1); String msg = (objects == null) ? "Log with null object" : getObjectsString(objects); String headString = "[(" + className + ":" + lineNumber + ")#" + methodNameShort + " ] "; return new String[]{tag, msg, headString}; } private static String getObjectsString(Object... objects) { if (objects.length > 1) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("\n"); for (int i = 0; i < objects.length; i++) { Object object = objects[i]; if (object == null) { stringBuilder.append("param").append("[").append(i).append("]").append(" = ").append("null").append("\n"); } else { stringBuilder.append("param").append("[").append(i).append("]").append(" = ").append(object.toString()).append("\n"); } } return stringBuilder.toString(); } else { Object object = objects[0]; return object == null ? "null" : object.toString(); } } private static void printLine(String tag, boolean isTop) { if (isTop) { Log.d(tag, "╔═══════════════════════════════════════════════════════════════════════════════════════"); } else { Log.d(tag, "╚═══════════════════════════════════════════════════════════════════════════════════════"); } } }