ToDo-檢測裝置設備

如下程式碼可檢試裝置的螢幕大小, CPU核心數, 記憶體大小, 及支援的Sensor

public class MainActivity extends AppCompatActivity {
    String str;
    TextView txt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt=(TextView)findViewById(R.id.txt);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        str=String.format("螢幕大小 : %d * %d\n\n", metrics.widthPixels, metrics.heightPixels);

        int cores=0;
        try {
            cores = new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).length;
        } catch (SecurityException e) {}
        catch (NullPointerException e) {}

        str+=String.format("CPU 核心數 : %d\n", cores);

        ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
        ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        am.getMemoryInfo(memInfo);
        str+=String.format("Memory : %.2f G\n\n", memInfo.totalMem/1024/1024/1024.0f);


        SensorManager manager=(SensorManager)getSystemService(SENSOR_SERVICE);
        List list=manager.getSensorList(Sensor.TYPE_ALL);
        str+="支援Sensor\n";
        for (Sensor s: list){
            str+=String.format("設備名稱 : %s, 版本 : %s, 供應商 : %s\n", s.getName(), s.getVersion(), s.getVendor());
        }
        txt.setText(str);
    }
    private static final FileFilter CPU_FILTER = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            String path = pathname.getName();
            if (path.startsWith("cpu")) {
                for (int i = 3; i < path.length(); i++) {
                    if (path.charAt(i) < '0' || path.charAt(i) > '9') {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
    };
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *