web-dev-qa-db-fra.com

Comment détecter les informations système comme le système d'exploitation ou le type d'appareil

Les choses les plus importantes que je veux savoir sont le type d'appareil, la version du système d'exploitation, s'il a un clavier matériel et peut-être la résolution de l'écran. mais si vous connaissez d'autres informations de débogage utiles, veuillez les ajouter :)

J'ai trouvé cela pour la version OS:

string += "OS Version: " + System.getProperty("os.version");

Comment obtenir les autres propriétés?

63
Simon Heinen

edit: pour obtenir un aperçu complet des attributs utiles, je les ai tous combinés ensemble dans mon activité ErrorHandler (commencez à lire à la ligne 56): https://github.com/simon-heinen/SimpleUi/blob/master /SimpleUI/srcAndroid/simpleui/util/DeviceInformation.Java#L56

La taille de Windows et la présence du clavier étaient une bonne idée, j'ai ajouté quelques informations supplémentaires à des fins de débogage:

String s="Debug-infos:";
s += "\n OS Version: " + System.getProperty("os.version") + "(" + Android.os.Build.VERSION.INCREMENTAL + ")";
s += "\n OS API Level: " + Android.os.Build.VERSION.SDK_INT;
s += "\n Device: " + Android.os.Build.DEVICE;
s += "\n Model (and Product): " + Android.os.Build.MODEL + " ("+ Android.os.Build.PRODUCT + ")";
117
Simon Heinen

Voici toutes les informations sur l'appareil possibles dans Android en utilisant l'énumération et la classe d'utilité ci-dessous)

public enum Device {
        DEVICE_TYPE, DEVICE_SYSTEM_NAME, DEVICE_VERSION, DEVICE_SYSTEM_VERSION, DEVICE_TOKEN,
        /**
         *
         */
        DEVICE_NAME, DEVICE_UUID, DEVICE_MANUFACTURE, IPHONE_TYPE,
        /**
         *
         */
        CONTACT_ID, DEVICE_LANGUAGE, DEVICE_TIME_ZONE, DEVICE_LOCAL_COUNTRY_CODE,
        /**
         *
         */
        DEVICE_CURRENT_YEAR, DEVICE_CURRENT_DATE_TIME, DEVICE_CURRENT_DATE_TIME_ZERO_GMT,
        /**
         *
         */
        DEVICE_HARDWARE_MODEL, DEVICE_NUMBER_OF_PROCESSORS, DEVICE_LOCALE, DEVICE_NETWORK, DEVICE_NETWORK_TYPE,
        /**
         *
         */
        DEVICE_IP_ADDRESS_IPV4, DEVICE_IP_ADDRESS_IPV6, DEVICE_MAC_ADDRESS, DEVICE_TOTAL_CPU_USAGE,
        /**
         *
         */
        DEVICE_TOTAL_MEMORY, DEVICE_FREE_MEMORY, DEVICE_USED_MEMORY,
        /**
         *
         */
        DEVICE_TOTAL_CPU_USAGE_USER, DEVICE_TOTAL_CPU_USAGE_SYSTEM,
        /**
         *
         */
        DEVICE_TOTAL_CPU_IDLE, DEVICE_IN_INCH;
    }

-> Classe utilitaire:

 public class DeviceInfo {

        public static String getDeviceInfo(Context activity, Device device) {
            try {
                switch (device) {
                    case DEVICE_LANGUAGE:
                        return Locale.getDefault().getDisplayLanguage();
                    case DEVICE_TIME_ZONE:
                        return TimeZone.getDefault().getID();//(false, TimeZone.SHORT);
                    case DEVICE_LOCAL_COUNTRY_CODE:
                        return activity.getResources().getConfiguration().locale.getCountry();
                    case DEVICE_CURRENT_YEAR:
                        return "" + (Calendar.getInstance().get(Calendar.YEAR));
                    case DEVICE_CURRENT_DATE_TIME:
                        Calendar calendarTime = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
                        long time = (calendarTime.getTimeInMillis() / 1000);
                        return String.valueOf(time);
    //                    return DateFormat.getDateTimeInstance().format(new Date());
                    case DEVICE_CURRENT_DATE_TIME_ZERO_GMT:
                        Calendar calendarTime_zero = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"), Locale.getDefault());
                        return String.valueOf((calendarTime_zero.getTimeInMillis() / 1000));
    //                    DateFormat df = DateFormat.getDateTimeInstance();
    //                    df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    //                    return df.format(new Date());
                    case DEVICE_HARDWARE_MODEL:
                        return getDeviceName();
                    case DEVICE_NUMBER_OF_PROCESSORS:
                        return Runtime.getRuntime().availableProcessors() + "";
                    case DEVICE_LOCALE:
                        return Locale.getDefault().getISO3Country();
                    case DEVICE_IP_ADDRESS_IPV4:
                        return getIPAddress(true);
                    case DEVICE_IP_ADDRESS_IPV6:
                        return getIPAddress(false);
                    case DEVICE_MAC_ADDRESS:
                        String mac = getMACAddress("wlan0");
                        if (TextUtils.isEmpty(mac)) {
                            mac = getMACAddress("eth0");
                        }
                        if (TextUtils.isEmpty(mac)) {
                            mac = "DU:MM:YA:DD:RE:SS";
                        }
                        return mac;

                    case DEVICE_TOTAL_MEMORY:
                        if (Build.VERSION.SDK_INT >= 16)
                            return String.valueOf(getTotalMemory(activity));
                    case DEVICE_FREE_MEMORY:
                        return String.valueOf(getFreeMemory(activity));
                    case DEVICE_USED_MEMORY:
                        if (Build.VERSION.SDK_INT >= 16) {
                            long freeMem = getTotalMemory(activity) - getFreeMemory(activity);
                            return String.valueOf(freeMem);
                        }
                        return "";
                    case DEVICE_TOTAL_CPU_USAGE:
                        int[] cpu = getCpuUsageStatistic();
                        if (cpu != null) {
                            int total = cpu[0] + cpu[1] + cpu[2] + cpu[3];
                            return String.valueOf(total);
                        }
                        return "";
                    case DEVICE_TOTAL_CPU_USAGE_SYSTEM:
                        int[] cpu_sys = getCpuUsageStatistic();
                        if (cpu_sys != null) {
                            int total = cpu_sys[1];
                            return String.valueOf(total);
                        }
                        return "";
                    case DEVICE_TOTAL_CPU_USAGE_USER:
                        int[] cpu_usage = getCpuUsageStatistic();
                        if (cpu_usage != null) {
                            int total = cpu_usage[0];
                            return String.valueOf(total);
                        }
                        return "";
                    case DEVICE_MANUFACTURE:
                        return Android.os.Build.MANUFACTURER;
                    case DEVICE_SYSTEM_VERSION:
                        return String.valueOf(getDeviceName());
                    case DEVICE_VERSION:
                        return String.valueOf(Android.os.Build.VERSION.SDK_INT);
                    case DEVICE_IN_INCH:
                        return getDeviceInch(activity);
                    case DEVICE_TOTAL_CPU_IDLE:
                        int[] cpu_idle = getCpuUsageStatistic();
                        if (cpu_idle != null) {
                            int total = cpu_idle[2];
                            return String.valueOf(total);
                        }
                        return "";
                    case DEVICE_NETWORK_TYPE:
                        return getNetworkType(activity);
                    case DEVICE_NETWORK:
                        return checkNetworkStatus(activity);
                    case DEVICE_TYPE:
                        if (isTablet(activity)) {
                            if (getDeviceMoreThan5Inch(activity)) {
                                return "Tablet";
                            } else
                                return "Mobile";
                        } else {
                            return "Mobile";
                        }
                    case DEVICE_SYSTEM_NAME:
                        return "Android OS";
                    default:
                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return "";
        }

        public static String getDeviceId(Context context) {
            String device_uuid = Secure.getString(context.getContentResolver(), Secure.Android_ID);
            if (device_uuid == null) {
                device_uuid = "12356789"; // for emulator testing
            } else {
                try {
                    byte[] _data = device_uuid.getBytes();
                    MessageDigest _digest = Java.security.MessageDigest.getInstance("MD5");
                    _digest.update(_data);
                    _data = _digest.digest();
                    BigInteger _bi = new BigInteger(_data).abs();
                    device_uuid = _bi.toString(36);
                } catch (Exception e) {
                    if (e != null) {
                        e.printStackTrace();
                    }
                }
            }
            return device_uuid;
        }

        @SuppressLint("NewApi")
        private static long getTotalMemory(Context activity) {
            try {
                MemoryInfo mi = new MemoryInfo();
                ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
                activityManager.getMemoryInfo(mi);
                long availableMegs = mi.totalMem / 1048576L; // in megabyte (mb)

                return availableMegs;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }

        private static long getFreeMemory(Context activity) {
            try {
                MemoryInfo mi = new MemoryInfo();
                ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
                activityManager.getMemoryInfo(mi);
                long availableMegs = mi.availMem / 1048576L; // in megabyte (mb)

                return availableMegs;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }

        private static String getDeviceName() {
            String manufacturer = Build.MANUFACTURER;
            String model = Build.MODEL;
            if (model.startsWith(manufacturer)) {
                return capitalize(model);
            } else {
                return capitalize(manufacturer) + " " + model;
            }
        }

        private static String capitalize(String s) {
            if (s == null || s.length() == 0) {
                return "";
            }
            char first = s.charAt(0);
            if (Character.isUpperCase(first)) {
                return s;
            } else {
                return Character.toUpperCase(first) + s.substring(1);
            }
        }

        /**
         * Convert byte array to hex string
         *
         * @param bytes
         * @return
         */
        private static String bytesToHex(byte[] bytes) {
            StringBuilder sbuf = new StringBuilder();
            for (int idx = 0; idx < bytes.length; idx++) {
                int intVal = bytes[idx] & 0xff;
                if (intVal < 0x10)
                    sbuf.append("0");
                sbuf.append(Integer.toHexString(intVal).toUpperCase());
            }
            return sbuf.toString();
        }

        /**
         * Returns MAC address of the given interface name.
         *
         * @param interfaceName eth0, wlan0 or NULL=use first interface
         * @return mac address or empty string
         */
        @SuppressLint("NewApi")
        private static String getMACAddress(String interfaceName) {
            try {

                List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface intf : interfaces) {
                    if (interfaceName != null) {
                        if (!intf.getName().equalsIgnoreCase(interfaceName))
                            continue;
                    }
                    byte[] mac = intf.getHardwareAddress();
                    if (mac == null)
                        return "";
                    StringBuilder buf = new StringBuilder();
                    for (int idx = 0; idx < mac.length; idx++)
                        buf.append(String.format("%02X:", mac[idx]));
                    if (buf.length() > 0)
                        buf.deleteCharAt(buf.length() - 1);
                    return buf.toString();
                }
            } catch (Exception ex) {
                return "";
            } // for now eat exceptions
            return "";
            /*
             * try { // this is so Linux hack return
             * loadFileAsString("/sys/class/net/" +interfaceName +
             * "/address").toUpperCase().trim(); } catch (IOException ex) { return
             * null; }
             */
        }

        /**
         * Get IP address from first non-localhost interface
         *
         * @return address or empty string
         */
        private static String getIPAddress(boolean useIPv4) {
            try {
                List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface intf : interfaces) {
                    List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                    for (InetAddress addr : addrs) {
                        if (!addr.isLoopbackAddress()) {
                            String sAddr = addr.getHostAddress().toUpperCase();
                            boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                            if (useIPv4) {
                                if (isIPv4)
                                    return sAddr;
                            } else {
                                if (!isIPv4) {
                                    int delim = sAddr.indexOf('%'); // drop ip6 port
                                    // suffix
                                    return delim < 0 ? sAddr : sAddr.substring(0, delim);
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
            } // for now eat exceptions
            return "";
        }

        /*
         *
         * @return integer Array with 4 elements: user, system, idle and other cpu
         * usage in percentage.
         */
        private static int[] getCpuUsageStatistic() {
            try {
                String tempString = executeTop();

                tempString = tempString.replaceAll(",", "");
                tempString = tempString.replaceAll("User", "");
                tempString = tempString.replaceAll("System", "");
                tempString = tempString.replaceAll("IOW", "");
                tempString = tempString.replaceAll("IRQ", "");
                tempString = tempString.replaceAll("%", "");
                for (int i = 0; i < 10; i++) {
                    tempString = tempString.replaceAll("  ", " ");
                }
                tempString = tempString.trim();
                String[] myString = tempString.split(" ");
                int[] cpuUsageAsInt = new int[myString.length];
                for (int i = 0; i < myString.length; i++) {
                    myString[i] = myString[i].trim();
                    cpuUsageAsInt[i] = Integer.parseInt(myString[i]);
                }
                return cpuUsageAsInt;

            } catch (Exception e) {
                e.printStackTrace();
                Log.e("executeTop", "error in getting cpu statics");
                return null;
            }
        }

        private static String executeTop() {
            Java.lang.Process p = null;
            BufferedReader in = null;
            String returnString = null;
            try {
                p = Runtime.getRuntime().exec("top -n 1");
                in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while (returnString == null || returnString.contentEquals("")) {
                    returnString = in.readLine();
                }
            } catch (IOException e) {
                Log.e("executeTop", "error in getting first line of top");
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                    p.destroy();
                } catch (IOException e) {
                    Log.e("executeTop", "error in closing and destroying top process");
                    e.printStackTrace();
                }
            }
            return returnString;
        }

        public static String getNetworkType(final Context activity) {
            String networkStatus = "";

            final ConnectivityManager connMgr = (ConnectivityManager)
                    activity.getSystemService(Context.CONNECTIVITY_SERVICE);
            // check for wifi
            final Android.net.NetworkInfo wifi =
                    connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            // check for mobile data
            final Android.net.NetworkInfo mobile =
                    connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if (wifi.isAvailable()) {
                networkStatus = "Wifi";
            } else if (mobile.isAvailable()) {
                networkStatus = getDataType(activity);
            } else {
                networkStatus = "noNetwork";
            }
            return networkStatus;
        }

        public static String checkNetworkStatus(final Context activity) {
            String networkStatus = "";
            try {
                // Get connect mangaer
                final ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
                // // check for wifi
                final Android.net.NetworkInfo wifi =
                connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                // // check for mobile data
                final Android.net.NetworkInfo mobile =
                connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                if (wifi.isAvailable()) {
                networkStatus = "Wifi";
                } else if (mobile.isAvailable()) {
                networkStatus = getDataType(activity);
                } else {
                networkStatus = "noNetwork";
                networkStatus = "0";
               }


            } catch (Exception e) {
                e.printStackTrace();
                networkStatus = "0";
            }
            return networkStatus;

        } 

 public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    public static boolean getDeviceMoreThan5Inch(Context activity) {
        try {
            DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();
            // int width = displayMetrics.widthPixels;
            // int height = displayMetrics.heightPixels;

            float yInches = displayMetrics.heightPixels / displayMetrics.ydpi;
            float xInches = displayMetrics.widthPixels / displayMetrics.xdpi;
            double diagonalInches = Math.sqrt(xInches * xInches + yInches * yInches);
            if (diagonalInches >= 7) {
                // 5inch device or bigger
                return true;
            } else {
                // smaller device
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public static String getDeviceInch(Context activity) {
        try {
            DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();

            float yInches = displayMetrics.heightPixels / displayMetrics.ydpi;
            float xInches = displayMetrics.widthPixels / displayMetrics.xdpi;
            double diagonalInches = Math.sqrt(xInches * xInches + yInches * yInches);
            return String.valueOf(diagonalInches);
        } catch (Exception e) {
            return "-1";
        }
    }

    public static String getDataType(Context activity) {
        String type = "Mobile Data";
        TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
        switch (tm.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                type = "Mobile Data 3G";
                Log.d("Type", "3g");
                // for 3g HSDPA networktype will be return as
                // per testing(real) in device with 3g enable
                // data
                // and speed will also matters to decide 3g network type
                break;
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                type = "Mobile Data 4G";
                Log.d("Type", "4g");
                // No specification for the 4g but from wiki
                // i found(HSPAP used in 4g)
                break;
            case TelephonyManager.NETWORK_TYPE_GPRS:
                type = "Mobile Data GPRS";
                Log.d("Type", "GPRS");
                break;
            case TelephonyManager.NETWORK_TYPE_Edge:
                type = "Mobile Data Edge 2G";
                Log.d("Type", "Edge 2g");
                break;

        }

        return type;
        }
}

- Obtenez l'adresse IP sans utiliser la classe InetAddressUtils

    private static final String IPV4_BASIC_PATTERN_STRING =
                "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" + // initial 3 fields, 0-255 followed by .
                        "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; // final field, 0-255
    private static final Pattern IPV4_PATTERN =
                Pattern.compile("^" + IPV4_BASIC_PATTERN_STRING + "$");
    public static boolean isIPv4Address(final String input) {
            return IPV4_PATTERN.matcher(input).matches();
   }

   /**
     * Get IP address from first non-localhost interface
     *
     * @return address or empty string
     */
    private static String getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        //TODO 3.0.0
                        boolean isIPv4 = isIPv4Address(sAddr);
                        if (useIPv4) {
                            if (isIPv4)
                                return sAddr;
                        } else {
                            if (!isIPv4) {
                                int delim = sAddr.indexOf('%'); // drop ip6 port
                                // suffix
                                return delim < 0 ? sAddr : sAddr.substring(0, delim);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
        } // for now eat exceptions
        return "";
    }
26
Hits

Pour la résolution d'écran:

getWindow().getWindowManager().getDefaultDisplay().getWidth();
getWindow().getWindowManager().getDefaultDisplay().getHeight();

Pour la présence du clavier matériel:

boolean keyboardPresent = (getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS);
8
Dolph

vous pouvez essayer ceci>

import Android.os.Build;
import Android.os.StrictMode;
import Android.provider.Settings;

import Java.io.BufferedReader;
import Java.io.InputStream;
import Java.io.InputStreamReader;
import Java.util.regex.Matcher;
import Java.util.regex.Pattern;

public class Utilies {


    public static String Android_id = Settings.Secure.getString(App.getContext().getContentResolver(), Settings.Secure.Android_ID);

    public static void getInternet() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    public static String readKernelVersion() {
        try {
            Process p = Runtime.getRuntime().exec("uname -a");
            InputStream is = null;
            if (p.waitFor() == 0) {
                is = p.getInputStream();
            } else {
                is = p.getErrorStream();
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(is), 1024);
            String line = br.readLine();
            br.close();
            return line;
        } catch (Exception ex) {
            return "ERROR: " + ex.getMessage();
        }
    }


    public static String getDeviceModelNumber() {
        String manufacturer = Build.VERSION.CODENAME;
        String model = Build.MODEL;
        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }

    private static  String capitalize(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }
    // get System info.
    public static String OSNAME = System.getProperty("os.name");
    public static String OSVERSION = System.getProperty("os.version");
    public static String RELEASE = Android.os.Build.VERSION.RELEASE;
    public static String DEVICE = Android.os.Build.DEVICE;
    public static String MODEL = Android.os.Build.MODEL;
    public static String PRODUCT = Android.os.Build.PRODUCT;
    public static String BRAND = Android.os.Build.BRAND;
    public static String DISPLAY = Android.os.Build.DISPLAY;
    public static String CPU_ABI = Android.os.Build.CPU_ABI;
    public static String CPU_ABI2 = Android.os.Build.CPU_ABI2;
    public static String UNKNOWN = Android.os.Build.UNKNOWN;
    public static String HARDWARE = Android.os.Build.HARDWARE;
    public static String ID = Android.os.Build.ID;
    public static String MANUFACTURER = Android.os.Build.MANUFACTURER;
    public static String SERIAL = Android.os.Build.SERIAL;
    public static String USER = Android.os.Build.USER;
    public static String Host = Android.os.Build.Host;


}
4
Victor Ruiz C.

Essayez ceci pour obtenir des informations sur l'appareil.

String serviceType = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getActivity().getSystemService(serviceType);
String DeviceId, SubscriberId, NetworkOperator, OsVersion,SimOperatorName;
DeviceId = m_telephonyManager.getDeviceId();
SubscriberId = m_telephonyManager.getSubscriberId();
NetworkOperator = m_telephonyManager.getNetworkOperator();
OsVersion = m_telephonyManager.getDeviceSoftwareVersion();
SimOperatorName = m_telephonyManager.getSimOperatorName();

Afficher la sortie

Log.d("Device Information :", "\n DeviceId : " + DeviceId +
                            "\n SubscriberId : " + SubscriberId
                            + "\n NetworkOperator : " + NetworkOperator +
                            "\n SoftwareVersion : " + OsVersion+
                            "\n SimOperatorName : " + SimOperatorName);
1
Jaydeep Dobariya

Mise à jour sur la résolution d'écran: getHeight () et getWidth déconseillés dans l'API niveau 13 - HONEYCOMB_MR2; utilisez getSize (Point) à la place. Plus d'informations sur: http://developer.Android.com/reference/Android/view/Display.html

1
HalukO