尺寸相关
dp与px转换dp2px、px2dp
sp与px转换sp2px、px2sp
各种单位转换applyDimension
在onCreate()即可强行获取View的尺寸forceGetViewSize
ListView中提前测量View尺寸measureView
设备相关
获取设备MAC地址getMacAddress
获取设备厂商,如XiaomigetManufacturer
获取设备型号,如MI2SCgetModel
获取设备SD卡是否可用isSDCardEnable
获取设备SD卡路径getSDCardPath
手机相关
判断设备是否是手机isPhone
获取手机的IMIEgetDeviceIMEI
获取手机状态信息getPhoneStatus
拨打电话callDial
发送短信sendSms
获取手机联系人getAllContactInfo
打开手机联系人界面点击联系人后便获取该号码getContantNum
获取手机短信并保存到xml中getAllSMS
网络相关
打开网络设置界面openWirelessSettings
判断是否网络连接isConnected
判断wifi是否连接状态isWifiConnected
获取移动网络运营商名称getNetworkOperatorName
获取移动终端类型getPhoneType
获取连接的网络类型(2G,3G,4G)getCurNetworkType
获取当前手机的网络类型(WIFI,2G,3G,4G)getNetWorkStatus
App相关
安装指定路径下的ApkinstallApk
卸载指定包名的AppuninstallApp
获取App名称getAppName
获取当前App版本号getVersonName
获取当前App版本CodegetVersionCode
打开指定包名的AppopenOtherApp
打开指定包名的App应用信息界面showAppInfo
分享Apk信息shareApkInfo
获取App信息的一个封装类(包名、版本号、应用信息、图标、名称等)getAppInfos
判断当前App处于前台还是后台isApplicationBackground
屏幕相关
获取手机分辨率getDeviceWidth、getDeviceHeight
获取状态栏高度getStatusBarHeight
获取状态栏高度+标题栏(ActionBar)高度getTopBarHeight
获取屏幕截图snapShotWithStatusBar、snapShotWithoutStatusBar
设置透明状态栏,需在setContentView之前调用
键盘相关
避免输入法面板遮挡
动态隐藏软键盘hideSoftInput
点击屏幕空白区域隐藏软键盘
动态显示软键盘showSoftInput
切换键盘显示与否状态toggleSoftInput
正则相关
正则工具类
加解密相关
MD5加密encryptMD5
SHA加密encryptSHA
未归类
获取服务是否开启isRunningService
更新Log
做这份整理只是想把它作为Android的一本小字典,当遇到一些琐碎问题时,不用再面向百度或者谷歌查询API的使用,费时费力,这里有的话,大家尽管撸走。希望它能逐日壮大起来,期待你的Star和完善,用途的话大家想把它们整理成工具类或者什么的话都可以,之后我也会封装工具类并分享之,但本篇只是提供查阅,毕竟看md比看类文件要爽多了,其中好多代码我也是各种搜刮来的,也要谢谢各位的总结,大部分代码已验证过可行,如有错误,请及时告之,开设QQ群提供讨论,群号:74721490
分类已上传至Github,传送门→期待你的Star和完善
好了,废话不多说,开始开车,嘟嘟......
尺寸相关
dp与px转换
/**
* dp转px
*/publicstaticintdp2px(Context context,floatdpValue){finalfloatscale = context.getResources().getDisplayMetrics().density;return(int) (dpValue * scale +0.5f);}/**
* px转dp
*/publicstaticintpx2dp(Context context,floatpxValue){finalfloatscale = context.getResources().getDisplayMetrics().density;return(int) (pxValue / scale +0.5f);}
sp与px转换
/**
* sp转px
*/publicstaticintsp2px(Context context,floatspValue){finalfloatfontScale = context.getResources().getDisplayMetrics().scaledDensity;return(int) (spValue * fontScale +0.5f);}/**
* px转sp
*/publicstaticintpx2sp(Context context,floatpxValue){finalfloatfontScale = context.getResources().getDisplayMetrics().scaledDensity;return(int) (pxValue / fontScale +0.5f);}
各种单位转换
/**
* 各种单位转换
* 该方法存在于TypedValue
*/publicstaticfloatapplyDimension(intunit,floatvalue, DisplayMetrics metrics){switch(unit) {caseTypedValue.COMPLEX_UNIT_PX:returnvalue;caseTypedValue.COMPLEX_UNIT_DIP:returnvalue * metrics.density;caseTypedValue.COMPLEX_UNIT_SP:returnvalue * metrics.scaledDensity;caseTypedValue.COMPLEX_UNIT_PT:returnvalue * metrics.xdpi * (1.0f/72);caseTypedValue.COMPLEX_UNIT_IN:returnvalue * metrics.xdpi;caseTypedValue.COMPLEX_UNIT_MM:returnvalue * metrics.xdpi * (1.0f/25.4f); }return0;}
在onCreate()即可强行获取View的尺寸
/**
* 在onCreate()即可强行获取View的尺寸
*/publicstaticint[] forceGetViewSize(View view) {intwidthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);intheightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(widthMeasureSpec, heightMeasureSpec);returnnewint[]{view.getMeasuredWidth(), view.getMeasuredHeight()};}
ListView中提前测量View尺寸
/**
* ListView中提前测量View尺寸
* 如headerView,用的时候拷贝到ListView中
*/privatevoidmeasureView(View view){ ViewGroup.LayoutParams p = view.getLayoutParams();if(p ==null) { p =newViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); }intwidth = ViewGroup.getChildMeasureSpec(0,0, p.width);intheight;inttempHeight = p.height;if(tempHeight >0) { height = MeasureSpec.makeMeasureSpec(tempHeight, MeasureSpec.EXACTLY); }else{ height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } view.measure(width, height);}
设备相关
获取设备MAC地址
/**
* 获取设备MAC地址
* 需添加权限
*/publicstaticStringgetMacAddress(Context context){ String macAddress =null; WifiManager wifi = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo();if(null!= info ) { macAddress = info.getMacAddress();if(null!= macAddress) { macAddress = macAddress.replace(":",""); } }returnmacAddress;}
获取设备厂商,如Xiaomi
/**
* 获取设备厂商,如Xiaomi
*/publicstaticStringgetManufacturer(){ String MANUFACTURER = Build.MANUFACTURER;returnMANUFACTURER;}
获取设备型号,如MI2SC
/**
* 获取设备型号,如MI2SC
*/publicstaticStringgetModel(){ String model = Build.MODEL;if(model !=null) { model = model.trim().replaceAll("\\s*",""); }else{ model =""; }returnmodel;}
获取设备SD卡是否可用
/**
* 获取设备SD卡是否可用
*/publicstaticbooleanisSDCardEnable(){returnEnvironment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());}
获取设备SD卡路径
/**
* 获取设备SD卡路径
*/publicstaticStringgetSDCardPath(){returnEnvironment.getExternalStorageDirectory().getAbsolutePath() + File.separator;}
手机相关
判断设备是否是手机
/**
* 判断设备是否是手机
*/publicstaticbooleanisPhone(Context context){ TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);returntm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;}
获取手机的IMIE
/**
* 获取当前设备的IMIE,需与上面的isPhone一起使用
* 需添加权限
*/publicstaticStringgetDeviceIMEI(Context context){ String deviceId;if(isPhone(context)) { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); deviceId = tm.getDeviceId(); }else{ deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); }returndeviceId;}
获取手机状态信息
/**
* 获取手机状态信息
* 需添加权限
* 返回如下
* DeviceId(IMEI) = 99000311726612
* DeviceSoftwareVersion = 00
* Line1Number =
* NetworkCountryIso = cn
* NetworkOperator = 46003
* NetworkOperatorName = 中国电信
* NetworkType = 6
* honeType = 2
* SimCountryIso = cn
* SimOperator = 46003
* SimOperatorName = 中国电信
* SimSerialNumber = 89860315045710604022
* SimState = 5
* SubscriberId(IMSI) = 460030419724900
* VoiceMailNumber = *86
*/publicstaticStringgetPhoneStatus(Context context){ TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); String str =""; str +="DeviceId(IMEI) = "+ tm.getDeviceId() +"\n"; str +="DeviceSoftwareVersion = "+ tm.getDeviceSoftwareVersion() +"\n"; str +="Line1Number = "+ tm.getLine1Number() +"\n"; str +="NetworkCountryIso = "+ tm.getNetworkCountryIso() +"\n"; str +="NetworkOperator = "+ tm.getNetworkOperator() +"\n"; str +="NetworkOperatorName = "+ tm.getNetworkOperatorName() +"\n"; str +="NetworkType = "+ tm.getNetworkType() +"\n"; str +="honeType = "+ tm.getPhoneType() +"\n"; str +="SimCountryIso = "+ tm.getSimCountryIso() +"\n"; str +="SimOperator = "+ tm.getSimOperator() +"\n"; str +="SimOperatorName = "+ tm.getSimOperatorName() +"\n"; str +="SimSerialNumber = "+ tm.getSimSerialNumber() +"\n"; str +="SimState = "+ tm.getSimState() +"\n"; str +="SubscriberId(IMSI) = "+ tm.getSubscriberId() +"\n"; str +="VoiceMailNumber = "+ tm.getVoiceMailNumber() +"\n";returnstr;}
拨打电话
// 需添加权限/**
* 拨打电话
*/publicstaticvoidcallDial(Context context, String phoneNumber){ context.startActivity(newIntent(Intent.ACTION_CALL, Uri.parse("tel:"+ phoneNumber)));}
发送短信
/**
* 发送短信
*/publicstaticvoidsendSms(Context context, String phoneNumber, String content){ Uri uri = Uri.parse("smsto:"+ (TextUtils.isEmpty(phoneNumber) ?"": phoneNumber)); Intent intent =newIntent(Intent.ACTION_SENDTO, uri); intent.putExtra("sms_body", TextUtils.isEmpty(content) ?"": content); context.startActivity(intent);}
获取手机联系人
/**
* 获取手机联系人
* 需添加权限
* 需添加权限
*/publicstaticList> getAllContactInfo(Context context) { SystemClock.sleep(3000); ArrayList> list =newArrayList>();// 1.获取内容解析者ContentResolver resolver = context.getContentResolver();// 2.获取内容提供者的地址:com.android.contacts// raw_contacts表的地址 :raw_contacts// view_data表的地址 : data// 3.生成查询地址Uri raw_uri = Uri.parse("content://com.android.contacts/raw_contacts"); Uri date_uri = Uri.parse("content://com.android.contacts/data");// 4.查询操作,先查询raw_contacts,查询contact_id// projection : 查询的字段Cursor cursor = resolver.query(raw_uri,newString[] {"contact_id"},null,null,null);// 5.解析cursorwhile(cursor.moveToNext()) {// 6.获取查询的数据String contact_id = cursor.getString(0);// cursor.getString(cursor.getColumnIndex("contact_id"));//getColumnIndex// : 查询字段在cursor中索引值,一般都是用在查询字段比较多的时候// 判断contact_id是否为空if(!TextUtils.isEmpty(contact_id)) {//null ""// 7.根据contact_id查询view_data表中的数据// selection : 查询条件// selectionArgs :查询条件的参数// sortOrder : 排序// 空指针: 1.null.方法 2.参数为nullCursor c = resolver.query(date_uri,newString[] {"data1","mimetype"},"raw_contact_id=?",newString[] { contact_id },null); HashMap map =newHashMap();// 8.解析cwhile(c.moveToNext()) {// 9.获取数据String data1 = c.getString(0); String mimetype = c.getString(1);// 10.根据类型去判断获取的data1数据并保存if(mimetype.equals("vnd.android.cursor.item/phone_v2")) {// 电话map.put("phone", data1); }elseif(mimetype.equals("vnd.android.cursor.item/name")) {// 姓名map.put("name", data1); } }// 11.添加到集合中数据list.add(map);// 12.关闭cursorc.close(); } }// 12.关闭cursorcursor.close();returnlist;}
打开手机联系人界面点击联系人后便获取该号码
/**
* 打开手机联系人界面点击联系人后便获取该号码
* 参照以下代码
*/privatevoidgetContantNum(){/*
Intent intent = new Intent();
intent.setAction("android.intent.action.PICK");
intent.addCategory("android.intent.category.DEFAULT");
intent.setType("vnd.android.cursor.dir/phone_v2");
startActivityForResult(intent, 0);
@Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri uri = data.getData();
String num = null;
// 创建内容解析者
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(uri,
null, null, null, null);
while (cursor.moveToNext()) {
num = cursor.getString(cursor.getColumnIndex("data1"));
}
cursor.close();
num = num.replaceAll("-", "");//替换的操作,555-6 -> 5556
}
}
*/}
获取手机短信并保存到xml中
/**
* 获取手机短信并保存到xml中
* 需添加权限
* 需添加权限
*/publicstaticvoidgetAllSMS(Context context){//1.获取短信//1.1获取内容解析者ContentResolver resolver = context.getContentResolver();//1.2获取内容提供者地址 sms,sms表的地址:null 不写//1.3获取查询路径Uri uri = Uri.parse("content://sms");//1.4.查询操作//projection : 查询的字段//selection : 查询的条件//selectionArgs : 查询条件的参数//sortOrder : 排序Cursor cursor = resolver.query(uri,newString[]{"address","date","type","body"},null,null,null);//设置最大进度intcount = cursor.getCount();//获取短信的个数//2.备份短信//2.1获取xml序列器XmlSerializer xmlSerializer = Xml.newSerializer();try{//2.2设置xml文件保存的路径//os : 保存的位置//encoding : 编码格式xmlSerializer.setOutput(newFileOutputStream(newFile("/mnt/sdcard/backupsms.xml")),"utf-8");//2.3设置头信息//standalone : 是否独立保存xmlSerializer.startDocument("utf-8",true);//2.4设置根标签xmlSerializer.startTag(null,"smss");//1.5.解析cursorwhile(cursor.moveToNext()) { SystemClock.sleep(1000);//2.5设置短信的标签xmlSerializer.startTag(null,"sms");//2.6设置文本内容的标签xmlSerializer.startTag(null,"address"); String address = cursor.getString(0);//2.7设置文本内容xmlSerializer.text(address); xmlSerializer.endTag(null,"address"); xmlSerializer.startTag(null,"date"); String date = cursor.getString(1); xmlSerializer.text(date); xmlSerializer.endTag(null,"date"); xmlSerializer.startTag(null,"type"); String type = cursor.getString(2); xmlSerializer.text(type); xmlSerializer.endTag(null,"type"); xmlSerializer.startTag(null,"body"); String body = cursor.getString(3); xmlSerializer.text(body); xmlSerializer.endTag(null,"body"); xmlSerializer.endTag(null,"sms"); System.out.println("address:"+ address +" date:"+ date +" type:"+ type +" body:"+ body); } xmlSerializer.endTag(null,"smss"); xmlSerializer.endDocument();//2.8将数据刷新到文件中xmlSerializer.flush(); }catch(Exception e) {// TODO Auto-generated catch blocke.printStackTrace(); }}
网络相关
打开网络设置界面
/**
* 打开网络设置界面
* 3.0以下打开设置界面
*/publicstaticvoidopenWirelessSettings(Context context){if(android.os.Build.VERSION.SDK_INT >10) { context.startActivity(newIntent(android.provider.Settings.ACTION_SETTINGS)); }else{ context.startActivity(newIntent(android.provider.Settings.ACTION_WIRELESS_SETTINGS)); }}
判断是否网络连接
/**
* 判断是否网络连接
* 需添加权限
*/publicstaticbooleanisConnected(Context context){ ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo();returninfo !=null&& info.isConnected();}
判断wifi是否连接状态
/**
* 判断wifi是否连接状态
* 需添加权限
*/publicstaticbooleanisWifiConnected(Context context){ ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE);returncm !=null&& cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;}
获取移动网络运营商名称
/**
* 获取移动网络运营商名称
* 如中国联通、中国移动、中国电信
*/publicstaticStringgetNetworkOperatorName(Context context){ TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE);returntm !=null? tm.getNetworkOperatorName() :null;}
获取移动终端类型
/**
* 获取移动终端类型
* PHONE_TYPE_NONE : 0 手机制式未知
* PHONE_TYPE_GSM : 1 手机制式为GSM,移动和联通
* PHONE_TYPE_CDMA : 2 手机制式为CDMA,电信
* PHONE_TYPE_SIP : 3
*/publicstaticintgetPhoneType(Context context){ TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE);returntm !=null? tm.getPhoneType() : -1;}
获取连接的网络类型(2G,3G,4G)
/**
* 获取连接的网络类型(2G,3G,4G)
* 联通的3G为UMTS或HSDPA,移动和联通的2G为GPRS或EGDE,电信的2G为CDMA,电信的3G为EVDO
*/publicstaticintgetNetTpye(Context context){ TelephonyManager telephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE);switch(telephonyManager.getNetworkType()) {caseTelephonyManager.NETWORK_TYPE_GPRS:caseTelephonyManager.NETWORK_TYPE_EDGE:caseTelephonyManager.NETWORK_TYPE_CDMA:caseTelephonyManager.NETWORK_TYPE_1xRTT:caseTelephonyManager.NETWORK_TYPE_IDEN:returnConstants.NETWORK_CLASS_2_G;caseTelephonyManager.NETWORK_TYPE_UMTS:caseTelephonyManager.NETWORK_TYPE_EVDO_0:caseTelephonyManager.NETWORK_TYPE_EVDO_A:caseTelephonyManager.NETWORK_TYPE_HSDPA:caseTelephonyManager.NETWORK_TYPE_HSUPA:caseTelephonyManager.NETWORK_TYPE_HSPA:caseTelephonyManager.NETWORK_TYPE_EVDO_B:caseTelephonyManager.NETWORK_TYPE_EHRPD:caseTelephonyManager.NETWORK_TYPE_HSPAP:returnConstants.NETWORK_CLASS_3_G;caseTelephonyManager.NETWORK_TYPE_LTE:returnConstants.NETWORK_CLASS_4_G;default:returnConstants.NETWORK_CLASS_UNKNOWN; }}publicclassConstants{// Unknown network classpublicstaticfinalintNETWORK_CLASS_UNKNOWN =0;// wifi networkpublicstaticfinalintNETWORK_WIFI =1;// "2G" networkspublicstaticfinalintNETWORK_CLASS_2_G =2;// "3G" networkspublicstaticfinalintNETWORK_CLASS_3_G =3;// "4G" networkspublicstaticfinalintNETWORK_CLASS_4_G =4;}
获取当前手机的网络类型(WIFI,2G,3G,4G)
/**
* 获取当前手机的网络类型(WIFI,2G,3G,4G)
* 需添加权限
* 需要用到上面的方法
*/publicstaticintgetCurNetworkType(Context context){intnetWorkType = Constants.NETWORK_CLASS_UNKNOWN; ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo();if(networkInfo !=null&& networkInfo.isConnected()) {inttype = networkInfo.getType();if(type == ConnectivityManager.TYPE_WIFI) { netWorkType = Constants.NETWORK_WIFI; }elseif(type == ConnectivityManager.TYPE_MOBILE) { netWorkType = getNetworkTpye(context); } }returnnetWorkType;}
App相关
安装指定路径下的Apk
/**
* 安装指定路径下的Apk
*/publicvoidinstallApk(String filePath){ Intent intent =newIntent(); intent.setAction("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.setDataAndType(Uri.fromFile(newFile(filePath)),"application/vnd.android.package-archive"); startActivityForResult(intent,0);}
卸载指定包名的App
/**
* 卸载指定包名的App
*/publicvoiduninstallApp(String packageName){ Intent intent =newIntent(); intent.setAction("android.intent.action.DELETE"); intent.addCategory("android.intent.category.DEFAULT"); intent.setData(Uri.parse("package:"+ packageName)); startActivityForResult(intent,0);}
获取App名称
/**
* 获取App名称
*/publicstaticStringgetAppName(Context context){try{ PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( context.getPackageName(),0);intlabelRes = packageInfo.applicationInfo.labelRes;returncontext.getResources().getString(labelRes); }catch(NameNotFoundException e) { e.printStackTrace(); }returnnull;}
获取当前App版本号
/**
* 获取当前App版本号
*/publicstaticStringgetVersionName(Context context){ String versionName =null; PackageManager pm = context.getPackageManager(); PackageInfo info =null;try{ info = pm.getPackageInfo(context.getApplicationContext().getPackageName(),0); }catch(NameNotFoundException e) { e.printStackTrace(); }if(info !=null) { versionName = info.versionName; }returnversionName;}
获取当前App版本Code
/**
* 获取当前App版本Code
*/publicstaticintgetVersionCode(Context context){intversionCode =0; PackageManager pm = context.getPackageManager(); PackageInfo info =null;try{ info = pm.getPackageInfo(context.getApplicationContext().getPackageName(),0); }catch(PackageManager.NameNotFoundException e) { e.printStackTrace(); }if(info !=null) { versionCode = info.versionCode; }returnversionCode;}
打开指定包名的App
/**
* 打开指定包名的App
*/publicvoidopenOtherApp(String packageName){ PackageManager manager = getPackageManager(); Intent launchIntentForPackage = manager.getLaunchIntentForPackage(packageName);if(launchIntentForPackage !=null) { startActivity(launchIntentForPackage); }}
打开指定包名的App应用信息界面
/**
* 打开指定包名的App应用信息界面
*/publicvoidshowAppInfo(String packageName){ Intent intent =newIntent(); intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); intent.setData(Uri.parse("package:"+ packageName)); startActivity(intent);}
分享Apk信息
/**
* 分享Apk信息
*/publicvoidshareApkInfo(String info){ Intent intent =newIntent(); intent.setAction("android.intent.action.SEND"); intent.addCategory("android.intent.category.DEFAULT"); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, info); startActivity(intent);}
获取App信息的一个封装类(包名、版本号、应用信息、图标、名称等)
/**
* 获取App信息的一个封装类(包名、版本号、应用信息、图标、名称等)
*/publicclassAppEnging{publicstaticListgetAppInfos(Context context){ List list =newArrayList();//获取应用程序信息//包的管理者PackageManager pm = context.getPackageManager();//获取系统中安装到所有软件信息List installedPackages = pm.getInstalledPackages(0);for(PackageInfo packageInfo : installedPackages) {//获取包名String packageName = packageInfo.packageName;//获取版本号String versionName = packageInfo.versionName;//获取applicationApplicationInfo applicationInfo = packageInfo.applicationInfo;intuid = applicationInfo.uid;//获取应用程序的图标Drawable icon = applicationInfo.loadIcon(pm);//获取应用程序的名称String name = applicationInfo.loadLabel(pm).toString();//是否是用户程序//获取应用程序中相关信息,是否是系统程序和是否安装到SD卡booleanisUser;intflags = applicationInfo.flags;if((applicationInfo.FLAG_SYSTEM & flags) == applicationInfo.FLAG_SYSTEM) {//系统程序isUser =false; }else{//用户程序isUser =true; }//是否安装到SD卡booleanisSD;if((applicationInfo.FLAG_EXTERNAL_STORAGE & flags) == applicationInfo.FLAG_EXTERNAL_STORAGE) {//安装到了SD卡isSD =true; }else{//安装到手机中isSD =false; }//添加到bean中AppInfo appInfo =newAppInfo(name, icon, packageName, versionName, isSD, isUser);//将bean存放到list集合list.add(appInfo); }returnlist; }}// 封装软件信息的bean类classAppInfo{//名称privateString name;//图标privateDrawable icon;//包名privateString packagName;//版本号privateString versionName;//是否安装到SD卡privatebooleanisSD;//是否是用户程序privatebooleanisUser;publicAppInfo(){super(); }publicAppInfo(String name, Drawable icon, String packagName, String versionName,booleanisSD,booleanisUser){super();this.name = name;this.icon = icon;this.packagName = packagName;this.versionName = versionName;this.isSD = isSD;this.isUser = isUser; }}
判断当前App处于前台还是后台
// 需添加// 并且必须是系统应用该方法才有效/**
* 判断当前App处于前台还是后台
*/publicstaticbooleanisApplicationBackground(finalContext context){ ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);@SuppressWarnings("deprecation") List tasks = am.getRunningTasks(1);if(!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity;if(!topActivity.getPackageName().equals(context.getPackageName())) {returntrue; } }returnfalse;}
屏幕相关
获取手机分辨率
/**
* 获取屏幕的宽度px
*/publicstaticintgetDeviceWidth(Context context){ WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics =newDisplayMetrics();// 创建了一张白纸windowManager.getDefaultDisplay().getMetrics(outMetrics);// 给白纸设置宽高returnoutMetrics.widthPixels;}/**
* 获取屏幕的高度px
*/publicstaticintgetDeviceHeight(Context context){ WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics =newDisplayMetrics();// 创建了一张白纸windowManager.getDefaultDisplay().getMetrics(outMetrics);// 给白纸设置宽高returnoutMetrics.heightPixels;}
获取状态栏高度
/**
* 获取状态栏高度
*/publicintgetStatusBarHeight(){intresult =0;intresourceId = getResources().getIdentifier("status_bar_height","dimen","android");if(resourceId >0) { result = getResources().getDimensionPixelSize(resourceId); }returnresult;}
获取状态栏高度+标题栏(ActionBar)高度
/**
* 获取状态栏高度+标题栏(ActionBar)高度
*/publicstaticintgetTopBarHeight(Activity activity){returnactivity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();}
获取屏幕截图
/**
* 获取当前屏幕截图,包含状态栏
*/publicstaticBitmapsnapShotWithStatusBar(Activity activity){ View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bmp = view.getDrawingCache();intwidth = getScreenWidth(activity);intheight = getScreenHeight(activity); Bitmap bp =null; bp = Bitmap.createBitmap(bmp,0,0, width, height); view.destroyDrawingCache();returnbp;}/**
* 获取当前屏幕截图,不包含状态栏
*/publicstaticBitmapsnapShotWithoutStatusBar(Activity activity){ View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bmp = view.getDrawingCache(); Rect frame =newRect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);intstatusBarHeight = frame.top;intwidth = getScreenWidth(activity);intheight = getScreenHeight(activity); Bitmap bp =null; bp = Bitmap.createBitmap(bmp,0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache();returnbp;}
设置透明状态栏,需在setContentView之前调用
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//透明状态栏getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//透明导航栏getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);}// 需在顶部控件布局中加入以下属性让内容出现在状态栏之下android:clipToPadding="true"android:fitsSystemWindows="true"
键盘相关
避免输入法面板遮挡
// 在manifest.xml中activity中设置android:windowSoftInputMode="stateVisible|adjustResize"
动态隐藏软键盘
/**
* 动态隐藏软键盘
*/publicstaticvoidhideSoftInput(Activity activity){ View view = activity.getWindow().peekDecorView();if(view !=null) { InputMethodManager inputmanger = (InputMethodManager) activity .getSystemService(Context.INPUT_METHOD_SERVICE); inputmanger.hideSoftInputFromWindow(view.getWindowToken(),0); }}/**
* 动态隐藏软键盘
*/publicstaticvoidhideSoftInput(Context context, EditText edit){ edit.clearFocus(); InputMethodManager inputmanger = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); inputmanger.hideSoftInputFromWindow(edit.getWindowToken(),0);}
点击屏幕空白区域隐藏软键盘
// 方法1:在onTouch中处理,未获焦点则隐藏/**
* 在onTouch中处理,未获焦点则隐藏
*/@OverridepublicbooleanonTouchEvent(MotionEvent event){if(null!=this.getCurrentFocus()) { InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);returnmInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),0); }returnsuper.onTouchEvent(event);}// 方法2:根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,需重写dispatchTouchEvent@OverridepublicbooleandispatchTouchEvent(MotionEvent ev){if(ev.getAction() == MotionEvent.ACTION_DOWN) { View v = getCurrentFocus();if(isShouldHideKeyboard(v, ev)) { hideKeyboard(v.getWindowToken()); } }returnsuper.dispatchTouchEvent(ev);}/**
* 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘
*/privatebooleanisShouldHideKeyboard(View v, MotionEvent event){if(v !=null&& (vinstanceofEditText)) {int[] l = {0,0}; v.getLocationInWindow(l);intleft = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();return!(event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom); }returnfalse;}/**
* 获取InputMethodManager,隐藏软键盘
*/privatevoidhideKeyboard(IBinder token){if(token !=null) { InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS); }}
动态显示软键盘
/**
* 动态显示软键盘
*/publicstaticvoidshowSoftInput(Context context, EditText edit){ edit.setFocusable(true); edit.setFocusableInTouchMode(true); edit.requestFocus(); InputMethodManager inputManager = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(edit,0);}
切换键盘显示与否状态
/**
* 切换键盘显示与否状态
*/publicstaticvoidtoggleSoftInput(Context context, EditText edit){ edit.setFocusable(true); edit.setFocusableInTouchMode(true); edit.requestFocus(); InputMethodManager inputManager = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);}
正则相关
正则工具类
publicclassRegularUtils{//验证手机号privatestaticfinalString REGEX_MOBILE ="^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$";//验证座机号,正确格式:xxx/xxxx-xxxxxxx/xxxxxxxxprivatestaticfinalString REGEX_TEL ="^0\\d{2,3}[- ]?\\d{7,8}";//验证邮箱privatestaticfinalString REGEX_EMAIL ="^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";//验证urlprivatestaticfinalString REGEX_URL ="http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?";//验证汉字privatestaticfinalString REGEX_CHZ ="^[\\u4e00-\\u9fa5]+$";//验证用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位privatestaticfinalString REGEX_USERNAME ="^[\\w\\u4e00-\\u9fa5]{6,20}(?
加解密相关
MD5加密
/**
* MD5加密
*/publicstaticStringencryptMD5(String data)throwsException{ MessageDigest md5 = MessageDigest.getInstance("MD5");returnnewBigInteger(md5.digest(data.getBytes())).toString(16);}
SHA加密
/**
* SHA加密
*/publicstaticStringencryptSHA(String data)throws Exception{ MessageDigest sha = MessageDigest.getInstance("SHA");returnnewBigInteger(sha.digest(data.getBytes())).toString(32);}
未归类
获取服务是否开启
/**
* 获取服务是否开启
*/publicstaticbooleanisRunningService(String className, Context context){//进程的管理者,活动的管理者ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);//获取正在运行的服务List runningServices = activityManager.getRunningServices(1000);//maxNum 返回正在运行的服务的上限个数,最多返回多少个服务//遍历集合for(RunningServiceInfo runningServiceInfo : runningServices) {//获取控件的标示ComponentName service = runningServiceInfo.service;//获取正在运行的服务的全类名String className2 = service.getClassName();//将获取到的正在运行的服务的全类名和传递过来的服务的全类名比较,一直表示服务正在运行 返回true,不一致表示服务没有运行 返回falseif(className.equals(className2)) {returntrue; } }returnfalse;}