android设备信息获取处理

来源:互联网 发布:java面向对象编程案例 编辑:程序博客网 时间:2024/05/18 22:46


设备相关信息:

计算设备尺寸:
public static double getScreenPhysicalSize(Activity ctx) {
        DisplayMetrics dm = new DisplayMetrics();
        ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);
        double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));
        return diagonalPixels / (160 * dm.density);
    }
    
    判断设备是否为平板
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }


设备是否root

public static boolean isDeviceRooted() {        return checkRootMethod1() || checkRootMethod2() || checkRootMethod3();    }    private static boolean checkRootMethod1() {        String buildTags = android.os.Build.TAGS;        return buildTags != null && buildTags.contains("test-keys");    }    private static boolean checkRootMethod2() {        String[] paths = {"/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su",                "/system/bin/failsafe/su", "/data/local/su"};        for (String path : paths) {            if (new File(path).exists()) return true;        }        return false;    }    private static boolean checkRootMethod3() {        Process process = null;        try {            process = Runtime.getRuntime().exec(new String[]{"/system/xbin/which", "su"});            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));            return in.readLine() != null;        } catch (Throwable t) {            return false;        } finally {            if (process != null) process.destroy();        }}


获取状态栏和标题栏的高度
获取状态栏高度:
getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。
于是,我们就可以算出状态栏的高度了。
Rect frame = new Rect();  
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
int statusBarHeight = frame.top;


获取标题栏高度:
getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
//statusBarHeight是上面所求的状态栏的高度  
int titleBarHeight = contentTop - statusBarHeight  

通过反射机制获取通知栏高度

public static int getStatusBarHeight(Context context){        Class<?> c = null;        Object obj = null;        Field field = null;        int x = 0, statusBarHeight = 0;        try {            c = Class.forName("com.android.internal.R$dimen");            obj = c.newInstance();            field = c.getField("status_bar_height");            x = Integer.parseInt(field.get(obj).toString());            statusBarHeight = context.getResources().getDimensionPixelSize(x);        } catch (Exception e1) {            e1.printStackTrace();        }        return statusBarHeight;    }
   
    
屏幕分辨率
private void initDisplayMetrics()
{
  /* 取得屏幕分辨率大小 */
        DisplayMetrics dm=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        this.width=dm.widthPixels;
        this.height=dm.heightPixels;
}

获取内存信息:
ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(outInfo);
//可用内存
outInfo.availMem
//是否在低内存状态
outInfo.lowMemory

使用Java获取系统内存信息;
void memery(){
String m1=(Runtime.getRuntime().maxMemory()/ (1024 * 1024)) + "MB" ;
String m2=(Runtime.getRuntime().totalMemory()/ (1024 * 1024)) + "MB" ;
String m3=(Runtime.getRuntime().freeMemory()/ (1024 * 1024)) + "MB"  ;
System.out.println("MaxMemory= "+m1+" totalMemory= "+m2+" freeMemory= "+m3);
}


ActivityManager mActManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
/** 获得系统正在运行的进程. */
List<RunningAppProcessInfo> mAllSysAppProcesses = mActManager.getRunningAppProcesses();


android 获取设备型号、OS版本号:
// .....  
    Build bd = new Build();  
    String model = bd.MODEL;
    android.os.Build.MODEL
    android.os.Build.VERSION.RELEASE

获取系统语言环境:
Locale.getDefault().getLanguage();  
language=Locale.getDefault().toString();//en_US zh_CN  

获取设备MAC地址:

private String getMac(Context context){
   WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
}

获取设备ip地址字符串形式表示
   

public String getLocalIpAddress() {      String strIP=null;         try {             for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {                 NetworkInterface intf = en.nextElement();                 for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {                     InetAddress inetAddress = enumIpAddr.nextElement();                     if (!inetAddress.isLoopbackAddress()) {                      strIP= inetAddress.getHostAddress().toString();                     }                 }             }         } catch (SocketException ex) {             Log.e("msg", ex.toString());         }         return strIP;     } 


   
   获取设备ip地址字符串形式表示
   
public String getLocalIpAddress() {      String strIP=null;         try {             for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {                 NetworkInterface intf = en.nextElement();                 for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {                     InetAddress inetAddress = enumIpAddr.nextElement();                     if (!inetAddress.isLoopbackAddress()) {                      strIP= inetAddress.getHostAddress().toString();                     }                 }             }         } catch (SocketException ex) {             Log.e("msg", ex.toString());         }         return strIP;     }  


获取Android设备的唯一识别码。由于设备杂乱,为了保证设备号唯一性,可以采用获取UUID方式。
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
    final String tmDevice, tmSerial, tmPhone, androidId;
    tmDevice = "" + tm.getDeviceId();
    tmSerial = "" + tm.getSimSerialNumber();
    androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
 
    UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
    String uniqueId = deviceUuid.toString();
    所有的设备都可以返回一个 TelephonyManager.getDeviceId()
所有的GSM设备 (测试设备都装载有SIM卡) 可以返回一个TelephonyManager.getSimSerialNumber()
所有的CDMA 设备对于 getSimSerialNumber() 却返回一个空值!
所有添加有谷歌账户的设备可以返回一个 ANDROID_ID
所有的CDMA设备对于 ANDROID_ID 和 TelephonyManager.getDeviceId() 返回相同的值(只要在设置时添加了谷歌账户)


//获取电池电量:
Intent batteryIntent = getApplicationContext().registerReceiver(null,  
        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));  
int currLevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);  
int total = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);  
int percent = currLevel * 100 / total;  

 //或者
private BroadcastReceiver batteryReceiver=new BroadcastReceiver(){  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            int level = intent.getIntExtra("level", 0);  
            //  level加%就是当前电量了  
    }  
    };  
    registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

//开机时间:
private String getOpenDeviceTimes() {  
    long ut = SystemClock.elapsedRealtime() / 1000;  
    if (ut == 0) {  
        ut = 1;  
    }  
    int m = (int) ((ut / 60) % 60);  
    int h = (int) ((ut / 3600));  
    return h + " " + mContext.getString(R.string.info_times_hour) + m + " "  
            + mContext.getString(R.string.info_times_minute);  
}  


获取CPU信息:
/proc/cpuinfo文件中第一行是CPU的型号,第二行是CPU的频率,可以通过读文件,读取这些数据!

public String[] getCpuInfo() {      String str1 = "/proc/cpuinfo";      String str2="";      String[] cpuInfo={"",""};      String[] arrayOfString;      try {          FileReader fr = new FileReader(str1);          BufferedReader localBufferedReader = new BufferedReader(fr, 8192);          str2 = localBufferedReader.readLine();          arrayOfString = str2.split("\\s+");          for (int i = 2; i < arrayOfString.length; i++) {              cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";          }          str2 = localBufferedReader.readLine();          arrayOfString = str2.split("\\s+");          cpuInfo[1] += arrayOfString[2];          localBufferedReader.close();      } catch (IOException e) {      }      return cpuInfo;  }  

/**     * Role:获取当前设置的电话号码     * <BR>Date:2012-3-12     * <BR>@author CODYY)peijiangping     */    public String getNativePhoneNumber() {        String NativePhoneNumber=null;        NativePhoneNumber=telephonyManager.getLine1Number();        return NativePhoneNumber;    }    /**     * Role:Telecom service providers获取手机服务商信息 <BR>     * 需要加入权限<uses-permission     * android:name="android.permission.READ_PHONE_STATE"/> <BR>     * Date:2012-3-12 <BR>     *     * @author CODYY)peijiangping     */    public String getProvidersName() {        String ProvidersName = null;        // 返回唯一的用户ID;就是这张卡的编号神马的        IMSI = telephonyManager.getSubscriberId();        // IMSI号前面3位460是国家,紧接着后面2位00 02是中国移动,01是中国联通,03是中国电信。        System.out.println(IMSI);        if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {            ProvidersName = "中国移动";        } else if (IMSI.startsWith("46001")) {            ProvidersName = "中国联通";        } else if (IMSI.startsWith("46003")) {            ProvidersName = "中国电信";        }        return ProvidersName;    }   //获取多个可用的存储设备    public static String getExternalStorageDirectory() {              //获取所以可用的存储路径              Map<String, String> map = System.getenv();              String[] values = new String[map.values().size()];              map.values().toArray(values);              String path = values[values.length - 1];              //获取外置存储卡位置              if (path.startsWith("/mnt/") && !Environment.getExternalStorageDirectory().getAbsolutePath().equals(path))                  return path;              else                  return Environment.getExternalStorageDirectory().getAbsolutePath();          }  
       
    获取存储可用空间:

private static final double KB = 1024.0;      private static final double MB = KB * KB;      private static final double GB = KB * KB * KB;            private static String showFileSize(double size) {          String fileSize;          if (size < KB)              fileSize = size + "B";          else if (size < MB)              fileSize = String.format("%.3f", size / KB) + "KB";          else if (size < GB)              fileSize = String.format("%.3f", size / MB) + "MB";          else              fileSize = String.format("%.3f", size / GB) + "GB";                return fileSize;      }      /** 显示SD卡剩余空间 */      public static String getSdcardAvailable() {          String result = "";          if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {              StatFs sf = new StatFs("/mnt/sdcard");              long blockSize = sf.getBlockSize();              long blockCount = sf.getBlockCount();              long availCount = sf.getAvailableBlocks();              return showFileSize(availCount * blockSize) + " \\ " + showFileSize(blockSize * blockCount);          }          return result;      }          /**     * 获取手机内部可用空间大小     * @return     */    static public long getAvailableInternalMemorySize() {        File path = Environment.getDataDirectory();        StatFs stat = new StatFs(path.getPath());        long blockSize = stat.getBlockSize();        long availableBlocks = stat.getAvailableBlocks();        return availableBlocks * blockSize;    }    /**     * 获取手机内部空间大小     * @return     */    static public long getTotalInternalMemorySize() {        File path = Environment.getDataDirectory();        StatFs stat = new StatFs(path.getPath());        long blockSize = stat.getBlockSize();        long totalBlocks = stat.getBlockCount();        return totalBlocks * blockSize;    }

获取内存使用情况:

 public static String getMemoryUsage() {        ActivityManager activityManager = (ActivityManager) DscaApplication.AppContext.getSystemService(Context.ACTIVITY_SERVICE);        MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();        activityManager.getMemoryInfo(memoryInfo);        long availMemory = memoryInfo.availMem / ONE_M_TO_BYTE;        long totalMemory = memoryInfo.totalMem / ONE_M_TO_BYTE;               return availMemory + "M/" + totalMemory + "M";    }



0 0
原创粉丝点击