2018-01-09Android開發人員不得不收集的程式碼
尺寸相關
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
*/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
*/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的尺寸
*/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尺寸
* 如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地址
* 需新增許可權
*/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
*/publicstaticStringgetManufacturer(){ String MANUFACTURER = Build.MANUFACTURER;returnMANUFACTURER;}
/**
* 獲取裝置型號,如MI2SC
*/publicstaticStringgetModel(){ String model = Build.MODEL;if(model !=null) { model = model.trim().replaceAll("\\s*",""); }else{ model =""; }returnmodel;}
/**
* 獲取裝置SD卡是否可用
*/publicstaticbooleanisSDCardEnable(){returnEnvironment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());}
/**
* 獲取裝置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,需與上面的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中
* 需新增許可權
* 需新增許可權
*/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是否連線狀態
* 需新增許可權
*/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)
* 聯通的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)
* 需新增許可權
* 需要用到上面的方法
*/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;}
/**
* 安裝指定路徑下的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
*/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名稱
*/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版本號
*/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
*/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
*/publicvoidopenOtherApp(String packageName){ PackageManager manager = getPackageManager(); Intent launchIntentForPackage = manager.getLaunchIntentForPackage(packageName);if(launchIntentForPackage !=null) { startActivity(launchIntentForPackage); }}
/**
* 開啟指定包名的App應用資訊介面
*/publicvoidshowAppInfo(String packageName){ Intent intent =newIntent(); intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); intent.setData(Uri.parse("package:"+ packageName)); startActivity(intent);}
/**
* 分享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處於前臺還是後臺
*/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)高度
*/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;}
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加密
*/publicstaticStringencryptMD5(String data)throwsException{ MessageDigest md5 = MessageDigest.getInstance("MD5");returnnewBigInteger(md5.digest(data.getBytes())).toString(16);}
/**
* 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;}
相關文章
- 開發人員不得不知的MySQL索引和查詢優化MySql索引優化
- 開發人員不得不會的MySQL多表聯合查詢方法!MySql
- 開發人員應該害怕低程式碼嗎?
- 開發人員使用遺留程式碼庫指南
- 為什麼開發人員喜歡低程式碼?
- 開發人員需做程式碼複查的5個原因
- 開發人員 vs 測試人員
- 開發人員愛開發
- Android 開發實用程式碼收集Android
- 隨著低程式碼的發展,程式設計不再僅適用於開發人員。程式設計
- 開發人員怎麼看實施人員
- 【專題】測試人員 VS 開發人員
- 低程式碼平臺是否會使開發人員多餘? - itpedia
- 面向Java開發人員的Flex開發指南JavaFlex
- 小程式構成、開發人員配置及開發週期
- 敏捷開發人員的責任敏捷
- 面試開發人員的有效方法面試
- 招聘.net開發人員
- 招聘SAP開發人員
- 別人就算了,開發人員都不知道低程式碼的起源就糟糕了!
- Java開發人員在程式設計中常見的雷!Java程式設計
- 如何發現優秀的IT開發人員
- 面向開發人員的最佳開源工具開源工具
- 揭開Web開發人員的最初困惑Web
- 測試人員與開發人員的比例究竟多少是合理的?
- 面對國內的低程式碼開發平臺,開發人員和企業該如何選擇?
- 開發人員的測試悖論
- 開發人員選擇 PHP 的原因PHP
- 開發人員越來越重視安全編碼
- 北京地區招聘條碼開發兼職人員
- 開發人員需要程式碼簽名證書來保護移動應用程式?
- 找 Laravel + VUE 開發人員LaravelVue
- Oracle開發人員守則Oracle
- 招聘兼職開發人員
- 找 jsp開發人員JS
- 軟體開發人員通病
- 每個Java開發人員應該知道的五種RESTful客戶端程式碼JavaREST客戶端
- 閱讀優秀程式碼是提高開發人員修為的一種捷徑