In order to facilitate the search, it has been roughly classified as follows:

  • Size related
    • Convert DP to PXdp2px,px2dp
    • Convert SP to PXsp2px,px2sp
    • Various unit conversionsapplyDimension
    • Get the width and height of the View from onCreate()getViewMeasure
    • Measure the View size in advance in ListViewmeasureView
  • Mobile phone related
    • Determine if the device is a mobile phoneisPhone
    • Obtain the IMIE of the current device, which must be used together with the isPhonegetDeviceIMEI
    • Get phone status informationgetPhoneStatus
    • Whether you have an SD cardhaveSDCard
    • Obtaining a MAC AddressgetMacAddress
    • Acquire mobile phone manufacturers, such as XiaomigetManufacturer
    • Obtain the phone model, such as MI2SCgetModel
    • Make a phone callcallDial
    • Send a text messagesendSms
    • Get mobile Phone ContactsgetAllContactInfo
    • The mobile phone contacts screen is displayed and the contact number is displayed
    • Get the SMS and save it to XMLgetAllSMS
  • Network related
    • The network Settings screen is displayedopenSetting
    • Check whether the network is connectedisOnline
    • Check whether wifi is connectedisWifi
    • Obtain the mobile network operator name, such as China Unicom, China Mobile, China TelecomgetNetworkOperatorName
    • Return the mobile terminal typegetPhoneType
    • Determine the network type (2G,3G,4G) connected to the phonegetNetWorkClass
    • Determine the current phone network type (WIFI 2,3,4 gigabytes)getNetWorkStatus
  • App related
    • Install the Apk in the specified pathinstallApk
    • Uninstall the App with the specified package nameuninstallApp
    • Get App namegetAppName
    • Get the current App version numbergetVersonName
    • Get the current App version CodegetVersionCode
    • Open the App with the specified package nameopenOtherApp
    • The App application information page for the specified package name is displayedshowAppInfo
    • Share Apk informationshareApkInfo
    • A wrapper class that gets App information (package name, version number, App information, icon, name, etc.)getAppInfos
    • Determine whether the current App is in the foreground or backgroundisApplicationBackground
  • Related to the screen
    • Get phone resolutiongetDeviceWidth,getDeviceHeight
    • Gets the status bar heightgetStatusBarHeight
    • Gets the status bar height + ActionBar heightgetTopBarHeight
    • Get screen shotssnapShotWithStatusBar,snapShotWithoutStatusBar
    • To set the transparent status bar, call it before setContentView
  • Keyboard related
    • Avoid blocking input panel
    • Dynamic hide soft keyboardhideSoftInput
    • Click a blank area of the screen to hide the soft keyboard
    • Dynamic display of soft keyboardshowSoftInput
    • Switch the keyboard display statetoggleSoftInput
  • Canonical correlation
  • Encryption and decryption correlation
    • MD5 encryptionencryptMD5
    • SHA encryptionencryptSHA
  • Not classified
    • Obtain whether the service is enabledisRunningService
  • Update the Log

Do this sort just want to use it as a small dictionary of Android, when encounter some trivial problems, no longer face Baidu or Google to query the use of API, time-consuming and laborious, if there is here, we feel free to go. Hope it day by day grow up, looking forward to your Star and improvement of use if you want to put them into tools or anything can be, then I will encapsulate tools and share it, but this is only to provide access to, after all the md much more comfortable than the class files, including a lot of code also various search, to me, also want to thank you all for the summary, Most of the code has been verified to work, please inform us of any errors.

Categories have been uploaded to Github, Portal → look forward to your Star and improvement

Good, nonsense not much say, begin to drive, doodle……

Size related

Convert DP to PX

/** * public static int dp2px(Context) float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; Return (int) (dpValue * scale + 0.5f); } /** * public static int px2dp(Context, Context) float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; Return (int) (pxValue/scale + 0.5f); }Copy the code

Convert SP to PX

/** * public static int sp2px(Context, Context) float spValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; Return (int) (spValue * fontScale + 0.5f); } /** * public static int px2sp(Context, Context) float pxValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; Return (int) (pxValue/fontScale + 0.5f); }Copy the code

Various unit conversions

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_PT: return value * metrics. case TypedValue.COMPLEX_UNIT_IN: return value * metrics.xdpi; Case TypedValue.COMPLEX_UNIT_MM: return value * metrics. Xdpi * (1.0f / 25.4f); case TypedValue.COMPLEX_UNIT_MM: return value * metrics. } return 0; }Copy the code

Get the width and height of the View from onCreate()

/ / 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()}; }Copy the code

Measure the View size in advance in ListView

// Notify parent layout, occupied width, height; /** * Measure the size of the ListView in advance, / / 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); } 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); }Copy the code

Mobile phone related

Determine if the device is a mobile phone

Public static Boolean isPhone(Context Context) {TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); return telephony.getPhoneType() ! = TelephonyManager.PHONE_TYPE_NONE; }Copy the code

Obtain the IMIE of the current device, which must be used together with the isPhone

Public static String getDeviceIMEI(Context Context) {String deviceId; 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; }Copy the code

Get phone status information

The following information is displayed: * DeviceId(IMEI) = 99000311726612 * DeviceSoftwareVersion = 00 * Line1Number = * NetworkCountryIso = CN * NetworkOperator = 46003 * NetworkOperatorName = China Telecom * NetworkType = 6 * honeType = 2 * SimCountryIso = CN * SimOperator = 46003 * SimOperatorName = China Telecom * 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; }Copy the code

Whether you have an SD card

/** * Public static Boolean haveSDCard() {return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); }Copy the code

Obtaining a MAC Address

Public static String getMacAddress(Context Context) {String macAddress; 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; }Copy the code

Acquire mobile phone manufacturers, such as Xiaomi

/** * public static String getManufacturer() {String MANUFACTURER = build.manufacturer; return MANUFACTURER; }Copy the code

Obtain the phone model, such as MI2SC

Private String getModel() {String model = Android.os.build.model; private String getModel() {String model = android.os.build.model; if (model ! = null) { model = model.trim().replaceAll("\\s*", ""); } else { model = ""; } return model; }Copy the code

Make a phone call

// Add permissions /** * Dial a call */ public static void callDial(Context Context, String phoneNumber) { context.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber))); }Copy the code

Send a text message

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); }Copy the code

Get mobile Phone Contacts

Public static List> getAllContactInfo(Context Context) {systemclock. sleep(3000); ArrayList> list = new ArrayList>(); / / 1. Taken content parsing ContentResolver resolver. = the context getContentResolver (); Contacts // raw_contacts // view_data address: data // 3. Generated query address Uri raw_uri = Uri. Parse (" content: / / com. Android. Contacts/raw_contacts "); Uri date_uri = Uri.parse("content://com.android.contacts/data"); // projection: raw_contacts; contact_id; Cursor = resolver.query(raw_URI, new String[] {"contact_id"}, null, null, null); // 5. Parse cursor while (cursor.movetonext ()) {// 6. String contact_id = cursor.getString(0); // cursor.getString(cursor.getColumnIndex("contact_id")); //getColumnIndex // : Query the index value of a cursor. Contact_id is null if (! TextUtils.isEmpty(contact_id)) {//null "" // 7. // selection: selection criteria // sortOrder: sorting parameters // null pointer: 1. Null C = resolver.query(date_uri, new String[] {"data1", "mimetype"}, "raw_contact_id=?" , new String[] { contact_id }, null); HashMap map = new HashMap(); Parse c while (c.movetonext ()) {// 9. String data1 = c.goetString (0); String mimetype = c.getString(1); / / 10. According to the type to judge access data1 data and save the if (mimetype. Equals (" VND. Android. The cursor. The item/phone_v2 ")) {/ / phone map. The put (" phone ", data1); } else if (mimetype. Equals (" VND. Android. The cursor. The item/name ")) {/ / name map. The put (" name ", data1); }} // 11. Add data to collection list.add(map); // close cursor c.close(); }} // 12. Close cursor cursor.close(); return list; }Copy the code

The mobile phone contacts screen is displayed and the contact number is displayed

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 = getContentResolver(); Cursor cursor = contentResolver.query(uri, null, null, null, null); while (cursor.moveToNext()) { num = cursor.getString(cursor.getColumnIndex("data1")); } cursor.close(); num = num.replaceAll("-", ""); // Replace the operation,555-6 -> 5556}}Copy the code

Get the SMS and save it to XML

Public static void getAllSMS(Context Context) {//1. Get SMS / / 1.1 have taken content parsing ContentResolver resolver. = the context getContentResolver (); Parse ("content:// SMS "); //1.2 Obtain the content provider address SMS, SMS table address :null Do not write //1.3 Obtain the query path Uri Uri = uri. parse("content:// SMS "); Projection: projection projection: projection projection: projection projection: projection projection: projection projection: projection projection: projection projection: projection projection: projection projection: projection projection: projection projection: projection projection: projection projection Cursor = resolver.query(URI, new String[]{"address", "date", "type", "body"}, null, null, null); // Set maximum progress int count = cursor.getCount(); Back up SMS messages. //2.1 Obtaining XML Serializer XmlSerializer = xml.newserializer (); Try {//2.2 Set the path to save the XML file // OS: save the location //encoding: Coding format xmlSerializer. SetOutput (new FileOutputStream (new File ("/MNT/sdcard/backupsms. XML ")), "utf-8"); / / set the header information / 2.3 / standalone: independence save xmlSerializer. StartDocument (" utf-8 ", true); //2.4 Set the root tag xmlSerializer. StartTag (null, "SMSS "); //1.5. parse cursor while (cursor.movetonext ()) {systemclock. sleep(1000); //2.5 Set the label xmlSerializer. StartTag (null, "SMS "); //2.6 Setting the text content label xmlSerializer. StartTag (null, "address"); String address = cursor.getString(0); //2.7 Setting the text content 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 Refreshing data to a file xmlserializer.flush (); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }}Copy the code

Network related

The network Settings screen is displayed

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); }Copy the code

Check whether the network is connected

Public static Boolean isOnline(Context Context) {ConnectivityManager = (ConnectivityManager) context .getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info ! = null && info.isConnected()) { return true; } return false; }Copy the code

Check whether wifi is connected

Public static Boolean isWifi(Context Context) {ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); return cm ! = null && cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; }Copy the code

Obtain the mobile network operator name, such as China Unicom, China Mobile, China Telecom

/** * Get the mobile network operator name, For example, China Unicom, China Mobile, China Telecom */ public static String getNetworkOperatorName(Context Context) {TelephonyManager TelephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); return telephonyManager.getNetworkOperatorName(); }Copy the code

Return the mobile terminal type

// PHONE_TYPE_NONE :0 Mobile phone type unknown // PHONE_TYPE_GSM :1 Mobile phone type GSM, Mobile and Unicom // PHONE_TYPE_CDMA :2 Mobile phone type CDMA, Phone // PHONE_TYPE_SIP:3 /** * Returns the mobile terminal type */ public static int getPhoneType(Context Context) {TelephonyManager telephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); return telephonyManager.getPhoneType(); }Copy the code

Determine the network type (2G,3G,4G) connected to the phone

// China Unicom 3G is UMTS or HSDPA, China Mobile and China Unicom 2G is GPRS or EGDE, China Telecom 2G is CDMA, 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; } /** * Check the network type (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; }}Copy the code

Determine the current phone network type (WIFI 2,3,4 gigabytes)

/** * determine the current phone network type (WIFI or 2,3,4 gb), */ 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; }Copy the code

App related

Install the Apk in the specified path

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); }Copy the code

Uninstall the App with the specified package name

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); }Copy the code

Get App name

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; }Copy the code

Get the current App version number

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; }Copy the code

Get the current App version 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; }Copy the code

Open the App with the specified package name

/** * open the specified packageName App */ public void openOtherApp(String packageName){PackageManager manager = getPackageManager(); Intent launchIntentForPackage = manager.getLaunchIntentForPackage(packageName); if (launchIntentForPackage ! = null) { startActivity(launchIntentForPackage); }}Copy the code

The App application information page for the specified package name is displayed

Public void showAppInfo(String packageName) {Intent Intent = new Intent(); public void showAppInfo(String packageName) {Intent Intent = new Intent(); intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); intent.setData(Uri.parse("package:" + packageName)); startActivity(intent); }Copy the code

Share Apk information

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); }Copy the code

A wrapper class that gets App information (package name, version number, App information, icon, name, etc.)

Public class AppEnging {public static List getAppInfos(Context Context) {public static List getAppInfos(Context Context) { List list = new ArrayList(); / / / / application information package manager PackageManager PM = context. GetPackageManager (); List installedPackages = pm.getInstalledPackages(0); For (PackageInfo PackageInfo: installedPackages) {// obtain the packageName. String packageName = packageinfo.packagename; String versionName = packageInfo.versionName; / / get application ApplicationInfo ApplicationInfo = packageInfo. ApplicationInfo; int uid = applicationInfo.uid; Drawable icon = ApplicationInfo. loadIcon(PM); Drawable icon = ApplicationInfo. loadIcon(PM); / / get the name of the application the String name = applicationInfo. LoadLabel (PM). The toString (); Boolean isUser; // Whether it is a user program. // Whether it is a system program. int flags = applicationInfo.flags; If ((applicationInfo.FLAG_SYSTEM & flags) == applicationInfo.FLAG_SYSTEM) {// isUser = false; } else {// user program isUser = true; } // Whether to install to SD card Boolean isSD; If ((applicationInfo.flag_external_storage & flags) == applicationInfo.flag_external_storage) {// Install SD card isSD = true; } else {// Install to phone isSD = false; } // Add to bean AppInfo AppInfo = new AppInfo(name, icon, packageName, versionName, isSD, isUser); List.add (appInfo); } return list; Class AppInfo {// private String name; Private Drawable icon; Private String packagName; // Version number private String versionName; 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; }}Copy the code

Determine whether the current App is in the foreground or background

// Public static Boolean isApplicationBackground(final Context Context); // Public static Boolean isApplicationBackground(final Context 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())) { return true; } } return false; }Copy the code

Related to the screen

Get phone resolution

Public static int getDeviceWidth(Context Context) {WindowManager WindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); / / create a piece of white paper windowManager. GetDefaultDisplay (.) getMetrics (outMetrics); // Return outMetrics. WidthPixels; } public static int getDeviceHeight(Context Context) {WindowManager WindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); / / create a piece of white paper windowManager. GetDefaultDisplay (.) getMetrics (outMetrics); // Return outMetrics. HeightPixels; }Copy the code

Gets the status bar height

Public int getStatusBarHeight() {int result = 0; int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = getResources().getDimensionPixelSize(resourceId); } return result; }Copy the code

Gets the status bar height + ActionBar height

/** * Get status bar height + Title bar height */ public static int getTopBarHeight(Activity Activity) {return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); }Copy the code

Get screen shots

/** * Get the current screen shot, Include status bar */ 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; } /** * get the current screen shot, */ 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; }Copy the code

To set the transparent status bar, call it before setContentView

If (build.version.sdk_int >= build.version_codes.kitkat) {// Transparent status bar getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); / / transparent navigation getWindow (). AddFlags (WindowManager. LayoutParams. FLAG_TRANSLUCENT_NAVIGATION); } / / must join the following properties in the top control layout content appears in the status bar under android: clipToPadding = "true" android: fitsSystemWindows = "true"Copy the code

Keyboard related

Avoid blocking input panel

/ / in the manifest. Set in the XML activity in the android: windowSoftInputMode = "stateVisible | adjustResize"Copy the code

Dynamic hide soft keyboard

Public static void hideSoftInput(Activity Activity) {View View = activity.getwindow ().peekdecorView (); / / Public static void hideSoftInput(Activity Activity) {View View = activity.getwindow ().  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); }Copy the code

Click a blank area of the screen to hide the soft keyboard

// Method 1: */ @override public Boolean onTouchEvent(MotionEvent) {if (null! = this.getCurrentFocus()) { InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0); } return super.onTouchEvent(event); } // Method 2: The coordinate of the EditText relative to the coordinate of the user clicking to determine whether to hide the keyboard, @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); } /** * 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; } /** * Get InputMethodManager, hide soft keyboard */ private void hideKeyboard(IBinder token) {if (token! = null) { InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS); }}Copy the code

Dynamic display of soft keyboard

Public static void showSoftInput(Context Context, EditText edit) {edit.setfocusable (true); / / 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); }Copy the code

Switch the keyboard display state

Public static void toggleSoftInput(Context Context, EditText Edit) {edit.setfocusable (true); /** * 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); }Copy the code

Canonical correlation

Regular utility class

Public Class RegularUtils {// Verify mobile number 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}$"; Private static final String REGEX_TEL = "^0\\d{2,3}[-]? \ \ d {7, 8} "; / / verification email private static final String REGEX_EMAIL = "^ \ \ w + (+ / - +. \ \ w) * @ \ \ w + ([-] \ \ w +) * \ \. \ \ w + ([-] \ \ w +) * $"; Private static Final String REGEX_URL = "HTTP (s)? ://([\\w-]+\\.) +[\\w-]+(/[\\w-./?%&=]*)?" ; Private static Final String REGEX_CHZ = "^[\\ U4E00 -\ u9FA5]+$"; // Verify the user name. The value can be a-z, a-z, 0-9,"_". Private static Final String REGEX_USERNAME = "^[\\ W \\ U4e00 -\ u9fa5]{6,20}(?Copy the code

Encryption and decryption correlation

MD5 encryption

/** * MD5 encryption */ public static String encryptMD5(String data) throws Exception {MessageDigest MD5 = MessageDigest.getInstance("MD5"); return new BigInteger(md5.digest(data.getBytes())).toString(16); }Copy the code

SHA encryption

/** * SHA encryption */ public static String encryptSHA(String data) throws Exception {MessageDigest SHA = MessageDigest.getInstance("SHA"); return new BigInteger(sha.digest(data.getBytes())).toString(32); }Copy the code

Not classified

Obtain whether the service is enabled

Public static Boolean isRunningService(String className, ActivityManager = (ActivityManager) {// process manager, ActivityManager context.getSystemService(Context.ACTIVITY_SERVICE); / / get the running service List runningServices = activityManager. GetRunningServices (1000); //maxNum Returns the maximum number of running services. The maximum number of running services is returned. RunningServices) {/ / access controls labeled the ComponentName service = runningServiceInfo. Service; // Get the full class name of the running service String className2 = service.getClassName(); If (classname.equals (className2)) {return true; if (classname.equals (className2)) {return true; } } return false; }Copy the code

Update the Log

2016/07/31 Added click blank area of screen to hide soft keyboard

2016/07/31 Added the directory jump function (however, Jane book does not support it, so it is not updated here)

2016/08/01 Added To obtain the current App version Code

2016/08/01 New directory display method name