20. Android device tool DeviceUtil

Source: Internet
Author: User

20. Android device tool DeviceUtil
20. Android device tool DeviceUtil

Android device tool DeviceUtil dp conversion px conversion dp device width device height SD card judgment network judgment VersionName VersionCode DeviceId mobile phone brand Mobile Phone model system Android API level system Android version App process id App process Name Creation App cache folder Uri conversion File get all source code of DeviceUtil for meta data value in AndroidManifestxml

Dp conversion px

This method is required in custom View. For custom views, you cannot set dp (density) as in xml, but you can only set px (pixels ). For devices with different resolutions, set px and the display will not be the same. To set the dp in combination with the design drawing, you need to convert the dp to the px value and then set it.

/*** Convert dp to px * @ param context * @ param dpValue * @ return */public static int dp2px (Context context, float dpValue) {final float scale = context. getResources (). getDisplayMetrics (). density; return (int) (dpValue * scale + 0.5f );}
Px conversion dp
/*** Convert px to dp * @ param context * @ param pxValue * @ return */public static int px2dp (Context context, float pxValue) {final float scale = context. getResources (). getDisplayMetrics (). density; return (int) (pxValue/scale + 0.5f );}
Device width
/*** Get the device width (px) * @ param context * @ return */public static int deviceWidth (Context context) {return context. getResources (). getDisplayMetrics (). widthPixels ;}
Device height
/*** Get the device height (px) * @ param context * @ return */public static int deviceHeight (Context context) {return context. getResources (). getDisplayMetrics (). heightPixels ;}
SD card judgment
/*** SD card judgment * @ return */public static boolean isSDCardAvailable () {return Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED );}
Network judgment
/*** Whether the network exists * @ param context * @ return */public static boolean isNetworkConnected (Context context) {if (context! = Null) {ConnectivityManager mConnectivityManager = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager. getActiveNetworkInfo (); if (mNetworkInfo! = Null) {return mNetworkInfo. isAvailable () ;}} return false ;}
VersionName

Corresponds to versionName in build. gradle.

/* ** Return version name * corresponding to build. versionName ** @ param context * @ return */public static String getVersionName (Context context) {String versionName =; try {PackageManager packageManager = context. getPackageManager (); PackageInfo packInfo = packageManager. getPackageInfo (context. getPackageName (), 0); versionName = packInfo. versionName;} catch (Exception e) {e. printStackTrace ();} return versionName ;}
VersionCode

Corresponds to versionCode in build. gradle.

/*** Returns the build corresponding to the version number. versionCode ** @ param context * @ return */public static String getVersionCode (Context context) {String versionCode =; try {PackageManager packageManager = context. getPackageManager (); PackageInfo packInfo = packageManager. getPackageInfo (context. getPackageName (), 0); versionCode = String. valueOf (packInfo. versionCode);} catch (Exception e) {e. printStackTrace ();} return versionCode ;}
DeviceId

Each device has a unique identifier, which is the DeviceId.

/*** Obtain the unique identifier of the device. deviceId ** @ param context * @ return */public static String getDeviceId (Context context) {TelephonyManager tm = (TelephonyManager) context. getSystemService (Context. TELEPHONY_SERVICE); String deviceId = tm. getDeviceId (); if (deviceId = null) {return-;} else {return deviceId ;}}
Mobile phone brand
/*** Get the mobile phone BRAND ** @ return */public static String getPhoneBrand () {return android. OS. Build. BRAND ;}
Mobile phone model
/*** Get the mobile phone MODEL ** @ return */public static String getPhoneModel () {return android. OS. Build. MODEL ;}
Android API level
/*** Obtain the Android API level of the mobile phone (22, 23 ...) ** @ return */public static int getBuildLevel () {return android. OS. build. VERSION. SDK_INT ;}
Android
/*** Obtain the Android version (4.4, 5.0, 5.1...) of the mobile phone ...) ** @ return */public static String getBuildVersion () {return android. OS. build. VERSION. RELEASE ;}
App process id
/*** Get the id of the current App Process ** @ return */public static int getAppProcessId () {return android. OS. Process. myPid ();}
App process Name
/*** Get the Name of the current App process ** @ param context * @ param processId * @ return */public static String getAppProcessName (Context context, int processId) {String processName = null; ActivityManager am = (ActivityManager) context. getSystemService (Context. ACTIVITY_SERVICE); // obtain the List of processes running the App. l = am. getRunningAppProcesses (); Iterator I = l. iterator (); PackageManager pm = context. getPackageManager (); while (I. hasNext () {ActivityManager. runningAppProcessInfo info = (ActivityManager. runningAppProcessInfo) (I. next (); try {if (info. pid = processId) {CharSequence c = pm. getApplicationLabel (pm. getApplicationInfo (info. processName, PackageManager. GET_META_DATA); processName = info. processName; return processName ;}} catch (Exception e) {Log. e (DeviceUtil. class. getName (), e. getMessage (), e) ;}return processName ;}
Create App cache folder
/*** Create an App folder ** @ param appName * @ param application * @ return */public static String createAPPFolder (String appName, Application application) {return createAPPFolder (appName, application, null);}/*** create an App folder ** @ param appName * @ param application * @ param folderName * @ return */public static String createAPPFolder (String appName, Application application, string folderName) {File root = Environment. getExternalStorageDirectory (); File folder;/*** if an SD card exists */if (DeviceUtil. isSDCardAvailable () & root! = Null) {folder = new File (root, appName); if (! Folder. exists () {folder. mkdirs () ;}} else {/*** the SD card does not exist. Put it in the cache folder */root = application. getCacheDir (); folder = new File (root, appName); if (! Folder. exists () {folder. mkdirs () ;}} if (folderName! = Null) {folder = new File (folder, folderName); if (! Folder. exists () {folder. mkdirs () ;}} return folder. getAbsolutePath ();}
Uri conversion File
/*** Find File through Uri ** @ param context * @ param uri * @ return */public static File uri2File (Activity context, Uri uri) {File file; string [] project = {MediaStore. images. media. DATA}; Cursor actualImageCursor = context. getContentResolver (). query (uri, project, null); if (actualImageCursor! = Null) {int actual_image_column_index = actualImageCursor. getColumnIndexOrThrow (MediaStore. images. media. DATA); actualImageCursor. moveToFirst (); String img_path = actualImageCursor. getString (actual_image_column_index); file = new File (img_path);} else {file = new File (uri. getPath ();} if (actualImageCursor! = Null) actualImageCursor. close (); return file ;}
Obtain the value of meta data in AndroidManifest. xml.

AndroidManifest. xml

For examplemeta-dataThe name is DEBUG.


  

Build. gradle

Then assign the value to this DEBUG in build. gradle.

// Channel Flavors productFlavors {APPTest {applicationId com. zyy. camnter. newlife manifestPlaceholders = [DEBUG: debug]}

You can use the following method to obtain the value assigned by DEBUG in AndroidManifest. xml:

/*** Get AndroidManifest. xml
   
    
Value ** @ param context * @ param name * @ return */public static String getMetaData (Context context, String name) {String value = null; try {ApplicationInfo appInfo = context. getPackageManager (). getApplicationInfo (context. getPackageName (), PackageManager. GET_META_DATA); value = appInfo. metaData. getString (name);} catch (PackageManager. nameNotFoundException e) {e. printStackTrace ();} return value ;}
   
All source code of DeviceUtil
Public class DeviceUtil {/*** convert dp to px ** @ param context * @ param dpValue * @ return */public static int dp2px (Context context, float dpValue) {final float scale = context. getResources (). getDisplayMetrics (). density; return (int) (dpValue * scale + 0.5f );} /*** convert px to dp ** @ param context * @ param pxValue * @ return */public static int px2dp (Context context, float pxValue) {final float scal E = context. getResources (). getDisplayMetrics (). density; return (int) (pxValue/scale + 0.5f);}/*** get the device width (px) ** @ param context * @ return */public static int deviceWidth (Context context) {return context. getResources (). getDisplayMetrics (). widthPixels;}/*** get the device height (px) ** @ param context * @ return */public static int deviceHeight (Context context) {return context. getResources (). getDisplayM Etrics (). heightPixels;}/*** SD card judgment ** @ return */public static boolean isSDCardAvailable () {return Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED);}/*** whether the network exists ** @ param context * @ return */public static boolean isNetworkConnected (Context context) {if (context! = Null) {ConnectivityManager mConnectivityManager = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager. getActiveNetworkInfo (); if (mNetworkInfo! = Null) {return mNetworkInfo. isAvailable () ;}} return false;}/*** return version name * corresponding to build. versionName ** @ param context * @ return */public static String getVersionName (Context context) {String versionName =; try {PackageManager packageManager = context. getPackageManager (); PackageInfo packInfo = packageManager. getPackageInfo (context. getPackageName (), 0); versionName = packInfo. versionNam E;} catch (Exception e) {e. printStackTrace ();} return versionName;}/*** return version number * corresponding to build. versionCode ** @ param context * @ return */public static String getVersionCode (Context context) {String versionCode =; try {PackageManager packageManager = context. getPackageManager (); PackageInfo packInfo = packageManager. getPackageInfo (context. getPackageName (), 0); versionCode = String. value Of (packInfo. versionCode);} catch (Exception e) {e. printStackTrace ();} return versionCode;}/*** obtain the unique identifier of the device. deviceId ** @ param context * @ return */public static String getDeviceId (Context context) {TelephonyManager tm = (TelephonyManager) context. getSystemService (Context. TELEPHONY_SERVICE); String deviceId = tm. getDeviceId (); if (deviceId = null) {return-;} else {return deviceId ;}}/* ** Get the mobile phone brand ** @ return */public static String getPhoneBrand () {return android. OS. build. BRAND;}/*** get the mobile phone model ** @ return */public static String getPhoneModel () {return android. OS. build. MODEL;}/*** get the Android API level of the mobile phone (22, 23 ...) ** @ return */public static int getBuildLevel () {return android. OS. build. VERSION. SDK_INT;}/*** get the Android version of the mobile phone (4.4, 5.0, 5.1 ...) ** @ return */public static String GetBuildVersion () {return android. OS. build. VERSION. RELEASE;}/*** get the id of the current App process ** @ return */public static int getAppProcessId () {return android. OS. process. myPid ();}/*** get the Name of the current App process ** @ param context * @ param processId * @ return */public static String getAppProcessName (Context context, int processId) {String processName = null; ActivityManager am = (ActivityManager) context. getSyste MService (Context. ACTIVITY_SERVICE); // obtain the List of processes running the App. l = am. getRunningAppProcesses (); Iterator I = l. iterator (); PackageManager pm = context. getPackageManager (); while (I. hasNext () {ActivityManager. runningAppProcessInfo info = (ActivityManager. runningAppProcessInfo) (I. next (); try {if (info. pid = processId) {CharSequence c = pm. getApplicationLabel (pm. getApplicationInfo (info. processName, PackageManager. GET_META_DATA); processName = info. processName; return processName ;}} catch (Exception e) {Log. e (DeviceUtil. class. getName (), e. getMessage (), e) ;}return processName ;} /*** create an App folder ** @ param appName * @ param application * @ return */public static String createAPPFolder (String appName, Application application) {return createAPPFolder (appName, application, null );}/*** Create an App folder ** @ param appName * @ param application * @ param folderName * @ return */public static String createAPPFolder (String appName, Application application, String folderName) {File root = Environment. getExternalStorageDirectory (); File folder;/*** if SD card */if (DeviceUtil. isSDCardAvailable () & root! = Null) {folder = new File (root, appName); if (! Folder. exists () {folder. mkdirs () ;}} else {/*** the SD card does not exist. Put it in the cache folder */root = application. getCacheDir (); folder = new File (root, appName); if (! Folder. exists () {folder. mkdirs () ;}} if (folderName! = Null) {folder = new File (folder, folderName); if (! Folder. exists () {folder. mkdirs () ;}} return folder. getAbsolutePath ();}/*** find File ** @ param context * @ param Uri * @ return */public static File uri2File through uri (Activity context, Uri uri) {File file; String [] project = {MediaStore. images. media. DATA}; Cursor actualImageCursor = context. getContentResolver (). query (uri, project, null); if (actualImageCursor! = Null) {int actual_image_column_index = actualImageCursor. getColumnIndexOrThrow (MediaStore. images. media. DATA); actualImageCursor. moveToFirst (); String img_path = actualImageCursor. getString (actual_image_column_index); file = new File (img_path);} else {file = new File (uri. getPath ();} if (actualImageCursor! = Null) actualImageCursor. close (); return file;}/*** get AndroidManifest. xml
     
      
Value ** @ param context * @ param name * @ return */public static String getMetaData (Context context, String name) {String value = null; try {ApplicationInfo appInfo = context. getPackageManager (). getApplicationInfo (context. getPackageName (), PackageManager. GET_META_DATA); value = appInfo. metaData. getString (name);} catch (PackageManager. nameNotFoundException e) {e. printStackTrace ();} return value ;}}
     

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.