Android开发人员不得不收集的代码(不断更新中...)
生活随笔
收集整理的這篇文章主要介紹了
Android开发人员不得不收集的代码(不断更新中...)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 尺寸相關
- dp與px轉換
- sp與px轉換
- 各種單位轉換
- 在onCreate()即可獲取View的寬高
- ListView中提前測量View尺寸
- 手機相關
- 判斷設備是否是手機
- 獲取當前設備的IMIE,需與上面的isPhone一起使用
- 獲取手機狀態信息
- 是否有SD卡
- 獲取MAC地址
- 獲取手機廠商,如Xiaomi
- 獲取手機型號,如MI2SC
- 跳轉至撥號界面
- 撥打電話
- 發送短信
- 獲取手機聯系人
- 直接打開手機聯系人界面,并獲取聯系人號碼
- 獲取手機短信并保存到xml中
- 網絡相關
- 打開網絡設置界面
- 判斷是否網絡連接
- 判斷wifi是否連接狀態
- 獲取移動網絡運營商名稱,如中國聯通、中國移動、中國電信
- 返回移動終端類型
- 判斷手機連接的網絡類型(2G,3G,4G)
- 判斷當前手機的網絡類型(WIFI還是2,3,4G)
- App相關
- 安裝指定路徑下的Apk
- 卸載指定包名的App
- 獲取App名稱
- 獲取當前App版本號
- 獲取當前App版本Code
- 打開指定包名的App
- 打開指定包名的App應用信息界面
- 分享Apk信息
- 獲取App信息的一個封裝類(包名、版本號、應用信息、圖標、名稱等)
- 判斷當前App處于前臺還是后臺
- 屏幕相關
- 獲取手機分辨率
- 獲取狀態欄高度
- 獲取狀態欄高度+標題欄(ActionBar)高度
- 獲取屏幕截圖
- 設置透明狀態欄,需在setContentView之前調用
- 鍵盤相關
- 避免輸入法面板遮擋
- 動態隱藏軟鍵盤
- 點擊屏幕空白區域隱藏軟鍵盤
- 動態顯示軟鍵盤
- 切換鍵盤顯示與否狀態
- 正則相關
- 正則工具類
- 加解密相關
- MD5加密
- SHA加密
- 未歸類
- 獲取服務是否開啟
- 更新Log
尺寸相關
dp與px轉換
/** * dp轉px */ public static int dp2px(Context context, float dpValue) {final float scale = context.getResources().getDisplayMetrics().density;return (int) (dpValue * scale + 0.5f); }/** * px轉dp */ public static int px2dp(Context context, float pxValue) {final float scale = context.getResources().getDisplayMetrics().density;return (int) (pxValue / scale + 0.5f); }sp與px轉換
/** * sp轉px */ public static int sp2px(Context context, float spValue) {final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;return (int) (spValue * fontScale + 0.5f); }/** * px轉sp */ public static int px2sp(Context context, float pxValue) {final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;return (int) (pxValue / fontScale + 0.5f); }各種單位轉換?
// 該方法存在于TypedValue /** * 各種單位轉換 */ public static float applyDimension(int unit, float value, DisplayMetrics metrics) {switch (unit) {case TypedValue.COMPLEX_UNIT_PX:return value;case TypedValue.COMPLEX_UNIT_DIP:return value * metrics.density;case TypedValue.COMPLEX_UNIT_SP:return value * metrics.scaledDensity;case TypedValue.COMPLEX_UNIT_PT:return value * metrics.xdpi * (1.0f / 72);case TypedValue.COMPLEX_UNIT_IN:return value * metrics.xdpi;case TypedValue.COMPLEX_UNIT_MM:return value * metrics.xdpi * (1.0f / 25.4f);}return 0; }在onCreate()即可獲取View的寬高
/** * 在onCreate()即可獲取View的寬高 */ public static int[] getViewMeasure(View view) {int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);view.measure(widthMeasureSpec, heightMeasureSpec);return new int[]{view.getMeasuredWidth(), view.getMeasuredHeight()}; }ListView中提前測量View尺寸
// 通知父布局,占用的寬,高; /** * ListView中提前測量View尺寸,如headerView */ private void measureView(View view) {ViewGroup.LayoutParams p = view.getLayoutParams();if (p == null) {p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);}//第一個參數spec =0,mode是UNSPECIFIED(未指定),父元素不對子元素施加任何束縛,第二個參數,是外邊距和內邊距
int width = ViewGroup.getChildMeasureSpec(0, 0, p.width); int height; int tempHeight = p.height;
if (tempHeight > 0) {
height = MeasureSpec.makeMeasureSpec(tempHeight, MeasureSpec.EXACTLY);
} else {
height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
view.measure(width, height);
}
?
手機相關?
判斷設備是否是手機
/** * 判斷設備是否是手機 */ public static boolean isPhone(Context context) {TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);return telephony.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE; }獲取當前設備的IMIE,需與上面的isPhone一起使用
/** * 獲取當前設備的IMIE,需與上面的isPhone一起使用 */ public static String getDeviceIMEI(Context context) {String deviceId;if (isPhone(context)) {TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);deviceId = telephony.getDeviceId();} else {deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);}return deviceId; }獲取手機狀態信息
// 需添加權限<uses-permission android:name="android.permission.READ_PHONE_STATE"/> /** * 獲取手機狀態信息 * * 返回如下 * 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 */ public static String getPhoneStatus(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";return str; }是否有SD卡
/** * 是否有SD卡 */ public static boolean haveSDCard() {return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); }獲取MAC地址
// 需添加權限<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> /** * 獲取MAC地址 */ public static String getMacAddress(Context context) {String macAddress;WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);WifiInfo info = wifi.getConnectionInfo();macAddress = info.getMacAddress();if (null == macAddress) {return "";}macAddress = macAddress.replace(":", "");return macAddress; }獲取手機廠商,如Xiaomi
/** * 獲取手機廠商,如Xiaomi */ public static String getOsName() {String MANUFACTURER = Build.MANUFACTURER;return MANUFACTURER; }獲取手機型號,如MI2SC?
/** * 獲取手機型號,如MI2SC */ private String getModel() {String model = android.os.Build.MODEL;if (model != null) {model = model.trim().replaceAll("\\s*", "");} else {model = "";}return model; }跳轉至撥號界面
/** * 跳轉至撥號界面 */ public static void callDial(Context context, String phoneNumber) {context.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber))); }撥打電話
/** * 撥打電話 */ public static void call(Context context, String phoneNumber) {context.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber))); }發送短信?
/** * 發送短信 */ public static void sendSms(Context context, String phoneNumber, String content) {Uri uri = Uri.parse("smsto:" + (TextUtils.isEmpty(phoneNumber) ? "" : phoneNumber));Intent intent = new Intent(Intent.ACTION_SENDTO, uri);intent.putExtra("sms_body", TextUtils.isEmpty(content) ? "" : content);context.startActivity(intent); }?獲取手機聯系人?
/** * 獲取手機聯系人 */ public static List<HashMap<String, String>> getAllContactInfo(Context context) {SystemClock.sleep(3000);ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();// 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, new String[] { "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, new String[] { "data1","mimetype" }, "raw_contact_id=?",new String[] { contact_id }, null);HashMap<String, String> map = new HashMap<String, String>();// 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);} else if (mimetype.equals("vnd.android.cursor.item/name")) {// 姓名map.put("name", data1);}}// 11.添加到集合中數據 list.add(map);// 12.關閉cursor c.close();}}// 12.關閉cursor cursor.close();return list; }直接打開手機聯系人界面,并獲取聯系人號碼
// 在按鈕點擊事件中設置Intent, 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, 1); @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中 */ public static void getAllSMS(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, new String[]{"address", "date", "type", "body"}, null, null, null);//設置最大進度int count = cursor.getCount();//獲取短信的個數//2.備份短信//2.1獲取xml序列器XmlSerializer xmlSerializer = Xml.newSerializer();try {//2.2設置xml文件保存的路徑//os : 保存的位置//encoding : 編碼格式xmlSerializer.setOutput(new FileOutputStream(new File("/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 block e.printStackTrace();} }??
網絡相關
打開網絡設置界面
/** * 打開網絡設置界面 */ public static void openSetting(Activity activity) {Intent intent = new Intent("/");ComponentName cm = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");intent.setComponent(cm);intent.setAction("android.intent.action.VIEW");activity.startActivityForResult(intent, 0); }判斷是否網絡連接
/** * 判斷是否網絡連接 */ public static boolean isOnline(Context context) {ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Activity.CONNECTIVITY_SERVICE);NetworkInfo info = manager.getActiveNetworkInfo();if (info != null && info.isConnected()) {return true;}return false; }判斷wifi是否連接狀態
/** * 判斷wifi是否連接狀態 */ public static boolean isWifi(Context context) {ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);return cm != null && cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; }獲取移動網絡運營商名稱,如中國聯通、中國移動、中國電信
/** * 獲取移動網絡運營商名稱,如中國聯通、中國移動、中國電信 */ public static String getNetworkOperatorName(Context context) {TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);return telephonyManager.getNetworkOperatorName(); }返回移動終端類型?
// PHONE_TYPE_NONE :0 手機制式未知 // PHONE_TYPE_GSM :1 手機制式為GSM,移動和聯通 // PHONE_TYPE_CDMA :2 手機制式為CDMA,電信 // PHONE_TYPE_SIP:3 /** * 返回移動終端類型 */ public static int getPhoneType(Context context) {TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);return telephonyManager.getPhoneType(); }判斷手機連接的網絡類型(2G,3G,4G)
// 聯通的3G為UMTS或HSDPA,移動和聯通的2G為GPRS或EGDE,電信的2G為CDMA,電信的3G為EVDO public class Constants {/*** Unknown network class*/public static final int NETWORK_CLASS_UNKNOWN = 0;/*** wifi net work*/public static final int NETWORK_WIFI = 1;/*** "2G" networks*/public static final int NETWORK_CLASS_2_G = 2;/*** "3G" networks*/public static final int NETWORK_CLASS_3_G = 3;/*** "4G" networks*/public static final int NETWORK_CLASS_4_G = 4; } /** * 判斷手機連接的網絡類型(2G,3G,4G) */ public static int getNetWorkClass(Context context) {TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);switch (telephonyManager.getNetworkType()) {case TelephonyManager.NETWORK_TYPE_GPRS:case TelephonyManager.NETWORK_TYPE_EDGE:case TelephonyManager.NETWORK_TYPE_CDMA:case TelephonyManager.NETWORK_TYPE_1xRTT:case TelephonyManager.NETWORK_TYPE_IDEN:return Constants.NETWORK_CLASS_2_G;case TelephonyManager.NETWORK_TYPE_UMTS:case TelephonyManager.NETWORK_TYPE_EVDO_0:case TelephonyManager.NETWORK_TYPE_EVDO_A:case TelephonyManager.NETWORK_TYPE_HSDPA:case TelephonyManager.NETWORK_TYPE_HSUPA:case TelephonyManager.NETWORK_TYPE_HSPA:case TelephonyManager.NETWORK_TYPE_EVDO_B:case TelephonyManager.NETWORK_TYPE_EHRPD:case TelephonyManager.NETWORK_TYPE_HSPAP:return Constants.NETWORK_CLASS_3_G;case TelephonyManager.NETWORK_TYPE_LTE:return Constants.NETWORK_CLASS_4_G;default:return Constants.NETWORK_CLASS_UNKNOWN;} }判斷當前手機的網絡類型(WIFI還是2,3,4G)?
/** * 判斷當前手機的網絡類型(WIFI還是2,3,4G),需要用到上面的方法 */ public static int getNetWorkStatus(Context context) {int netWorkType = Constants.NETWORK_CLASS_UNKNOWN;ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();if (networkInfo != null && networkInfo.isConnected()) {int type = networkInfo.getType();if (type == ConnectivityManager.TYPE_WIFI) {netWorkType = Constants.NETWORK_WIFI;} else if (type == ConnectivityManager.TYPE_MOBILE) {netWorkType = getNetWorkClass(context);}}return netWorkType; }?
App相關
安裝指定路徑下的Apk?
/** * 安裝指定路徑下的Apk */ public void installApk(String filePath) {Intent intent = new Intent();intent.setAction("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");startActivityForResult(intent, 0); }卸載指定包名的App
/** * 卸載指定包名的App */ public void uninstallApp(String packageName) {Intent intent = new Intent();intent.setAction("android.intent.action.DELETE");intent.addCategory("android.intent.category.DEFAULT");intent.setData(Uri.parse("package:" + packageName));startActivityForResult(intent, 0); }獲取App名稱
/** * 獲取App名稱 */ public static String getAppName(Context context) {try {PackageManager packageManager = context.getPackageManager();PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);int labelRes = packageInfo.applicationInfo.labelRes;return context.getResources().getString(labelRes);} catch (NameNotFoundException e) {e.printStackTrace();}return null; }獲取當前App版本號
/** * 獲取當前App版本號 */ public static String getVersionName(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;}return versionName; }獲取當前App版本Code
- /**
*獲取當前App版本Code
*/public static int getVersionCode(Context context) {int versionCode = 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;}return versionCode;
}/**
*打開指定包名的App
*/
public void openOtherApp(String packageName){PackageManager manager = getPackageManager();Intent launchIntentForPackage = manager.getLaunchIntentForPackage(packageName);if (launchIntentForPackage != null) {startActivity(launchIntentForPackage);}
}
打開指定包名的App應用信息界面?
/** * 打開指定包名的App應用信息界面 */ public void showAppInfo(String packageName) {Intent intent = new Intent();intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");intent.setData(Uri.parse("package:" + packageName));startActivity(intent); }分享Apk信息?
/** * 分享Apk信息 */ public void shareApkInfo(String info) {Intent intent = new Intent();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信息的一個封裝類(包名、版本號、應用信息、圖標、名稱等) */ public class AppEnging {public static List<AppInfo> getAppInfos(Context context) {List<AppInfo> list = new ArrayList<AppInfo>();//獲取應用程序信息//包的管理者PackageManager pm = context.getPackageManager();//獲取系統中安裝到所有軟件信息List<PackageInfo> installedPackages = pm.getInstalledPackages(0);for (PackageInfo packageInfo : installedPackages) {//獲取包名String packageName = packageInfo.packageName;//獲取版本號String versionName = packageInfo.versionName;//獲取applicationApplicationInfo applicationInfo = packageInfo.applicationInfo;int uid = applicationInfo.uid;//獲取應用程序的圖標Drawable icon = applicationInfo.loadIcon(pm);//獲取應用程序的名稱String name = applicationInfo.loadLabel(pm).toString();//是否是用戶程序//獲取應用程序中相關信息,是否是系統程序和是否安裝到SD卡boolean isUser;int flags = applicationInfo.flags;if ((applicationInfo.FLAG_SYSTEM & flags) == applicationInfo.FLAG_SYSTEM) {//系統程序isUser = false;} else {//用戶程序isUser = true;}//是否安裝到SD卡boolean isSD;if ((applicationInfo.FLAG_EXTERNAL_STORAGE & flags) == applicationInfo.FLAG_EXTERNAL_STORAGE) {//安裝到了SD卡isSD = true;} else {//安裝到手機中isSD = false;}//添加到bean中AppInfo appInfo = new AppInfo(name, icon, packageName, versionName, isSD, isUser);//將bean存放到list集合 list.add(appInfo);}return list;} }// 封裝軟件信息的bean類 class AppInfo {//名稱private String name;//圖標private Drawable icon;//包名private String packagName;//版本號private String versionName;//是否安裝到SD卡private boolean isSD;//是否是用戶程序private boolean isUser;public AppInfo() {super();}public AppInfo(String name, Drawable icon, String packagName,String versionName, boolean isSD, boolean isUser) {super();this.name = name;this.icon = icon;this.packagName = packagName;this.versionName = versionName;this.isSD = isSD;this.isUser = isUser;} }判斷當前App處于前臺還是后臺?
// 需添加<uses-permission android:name="android.permission.GET_TASKS"/> // 并且必須是系統應用該方法才有效 /** * 判斷當前App處于前臺還是后臺 */ public static boolean isApplicationBackground(final Context context) {ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);@SuppressWarnings("deprecation")List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);if (!tasks.isEmpty()) {ComponentName topActivity = tasks.get(0).topActivity;if (!topActivity.getPackageName().equals(context.getPackageName())) {return true;}}return false; }?
屏幕相關
獲取手機分辨率?
/** * 獲取屏幕的寬度px */ public static int getDeviceWidth(Context context) {WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);DisplayMetrics outMetrics = new DisplayMetrics();// 創建了一張白紙windowManager.getDefaultDisplay().getMetrics(outMetrics);// 給白紙設置寬高return outMetrics.widthPixels; }/** * 獲取屏幕的高度px */ public static int getDeviceHeight(Context context) {WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);DisplayMetrics outMetrics = new DisplayMetrics();// 創建了一張白紙windowManager.getDefaultDisplay().getMetrics(outMetrics);// 給白紙設置寬高return outMetrics.heightPixels; }獲取狀態欄高度?
/** * 獲取狀態欄高度 */ public int getStatusBarHeight() {int result = 0;int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");if (resourceId > 0) {result = getResources().getDimensionPixelSize(resourceId);}return result; }獲取狀態欄高度+標題欄(ActionBar)高度
/** * 獲取狀態欄高度+標題欄(ActionBar)高度 */ public static int getTopBarHeight(Activity activity) {return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); }獲取屏幕截圖?
/** * 獲取當前屏幕截圖,包含狀態欄 */ public static Bitmap snapShotWithStatusBar(Activity activity) {View view = activity.getWindow().getDecorView();view.setDrawingCacheEnabled(true);view.buildDrawingCache();Bitmap bmp = view.getDrawingCache();int width = getScreenWidth(activity);int height = getScreenHeight(activity);Bitmap bp = null;bp = Bitmap.createBitmap(bmp, 0, 0, width, height);view.destroyDrawingCache();return bp; }/** * 獲取當前屏幕截圖,不包含狀態欄 */ public static Bitmap snapShotWithoutStatusBar(Activity activity) {View view = activity.getWindow().getDecorView();view.setDrawingCacheEnabled(true);view.buildDrawingCache();Bitmap bmp = view.getDrawingCache();Rect frame = new Rect();activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);int statusBarHeight = frame.top;int width = getScreenWidth(activity);int height = getScreenHeight(activity);Bitmap bp = null;bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height- statusBarHeight);view.destroyDrawingCache();return bp; }設置透明狀態欄,需在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"?動態隱藏軟鍵盤
/** * 動態隱藏軟鍵盤 */ public static void hideSoftInput(Activity activity) {View view = activity.getWindow().peekDecorView();if (view != null) {InputMethodManager inputmanger = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);} }/** * 動態隱藏軟鍵盤 */ public static void hideSoftInput(Context context, EditText edit) {edit.clearFocus();InputMethodManager inputmanger = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);inputmanger.hideSoftInputFromWindow(edit.getWindowToken(), 0); }?點擊屏幕空白區域隱藏軟鍵盤?
// 方法1:在onTouch中處理,未獲焦點則隱藏 /** * 在onTouch中處理,未獲焦點則隱藏 */ @Override public boolean onTouchEvent(MotionEvent event) {if (null != this.getCurrentFocus()) {InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);}return super.onTouchEvent(event); }// 方法2:根據EditText所在坐標和用戶點擊的坐標相對比,來判斷是否隱藏鍵盤,需重寫dispatchTouchEvent @Override public boolean dispatchTouchEvent(MotionEvent ev) {if (ev.getAction() == MotionEvent.ACTION_DOWN) {View v = getCurrentFocus();if (isShouldHideKeyboard(v, ev)) {hideKeyboard(v.getWindowToken());}}return super.dispatchTouchEvent(ev); }/** * 根據EditText所在坐標和用戶點擊的坐標相對比,來判斷是否隱藏鍵盤 */ private boolean isShouldHideKeyboard(View v, MotionEvent event) {if (v != null && (v instanceof EditText)) {int[] l = {0, 0};v.getLocationInWindow(l);int left = 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);}return false; }/** * 獲取InputMethodManager,隱藏軟鍵盤 */ private void hideKeyboard(IBinder token) {if (token != null) {InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);} }動態顯示軟鍵盤
/** * 動態顯示軟鍵盤 */ public static void showSoftInput(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); }切換鍵盤顯示與否狀態
/** * 切換鍵盤顯示與否狀態 */ public static void toggleSoftInput(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); }??
正則相關?
正則工具類
public class RegularUtils {//驗證手機號private static final String 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/xxxxxxxxprivate static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";//驗證郵箱private static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";//驗證urlprivate static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?";//驗證漢字private static final String REGEX_CHZ = "^[\\u4e00-\\u9fa5]+$";//驗證用戶名,取值范圍為a-z,A-Z,0-9,"_",漢字,不能以"_"結尾,用戶名必須是6-20位private static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)$";//驗證IP地址private static final String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";//If u want more please visit http://toutiao.com/i6231678548520731137//*** @param string 待驗證文本* @return 是否符合手機號格式*/public static boolean isMobile(String string) {return isMatch(REGEX_MOBILE, string);}/*** @param string 待驗證文本* @return 是否符合座機號碼格式*/public static boolean isTel(String string) {return isMatch(REGEX_TEL, string);}/*** @param string 待驗證文本* @return 是否符合郵箱格式*/public static boolean isEmail(String string) {return isMatch(REGEX_EMAIL, string);}/*** @param string 待驗證文本* @return 是否符合網址格式*/public static boolean isURL(String string) {return isMatch(REGEX_URL, string);}/*** @param string 待驗證文本* @return 是否符合漢字*/public static boolean isChz(String string) {return isMatch(REGEX_CHZ, string);}/*** @param string 待驗證文本* @return 是否符合用戶名*/public static boolean isUsername(String string) {return isMatch(REGEX_USERNAME, string);}/*** @param regex 正則表達式字符串* @param string 要匹配的字符串* @return 如果str 符合 regex的正則表達式格式,返回true, 否則返回 false;*/public static boolean isMatch(String regex, String string) {return !TextUtils.isEmpty(string) && Pattern.matches(regex, string);} }?
?
加解密相關
?MD5加密
/** * MD5加密 */ public static String encryptMD5(String data) throws Exception {MessageDigest md5 = MessageDigest.getInstance("MD5");return new BigInteger(md5.digest(data.getBytes())).toString(16); }SHA加密
/** * SHA加密 */ public static String encryptSHA(String data) throws Exception {MessageDigest sha = MessageDigest.getInstance("SHA");return new BigInteger(sha.digest(data.getBytes())).toString(32); }?
未歸類?
獲取服務是否開啟
/** * 獲取服務是否開啟 */ public static boolean isRunningService(String className, Context context) {//進程的管理者,活動的管理者ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);//獲取正在運行的服務List<RunningServiceInfo> runningServices = activityManager.getRunningServices(1000);//maxNum 返回正在運行的服務的上限個數,最多返回多少個服務//遍歷集合for (RunningServiceInfo runningServiceInfo : runningServices) {//獲取控件的標示ComponentName service = runningServiceInfo.service;//獲取正在運行的服務的全類名String className2 = service.getClassName();//將獲取到的正在運行的服務的全類名和傳遞過來的服務的全類名比較,一直表示服務正在運行 返回true,不一致表示服務沒有運行 返回falseif (className.equals(className2)) {return true;}}return false; }?
轉載于:https://www.cnblogs.com/earl-yongchang/p/5792834.html
總結
以上是生活随笔為你收集整理的Android开发人员不得不收集的代码(不断更新中...)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ListFragment的使用
- 下一篇: Weblogic java.lang.