【转】Android 的cpu 硬盘 内存储器 网络设置 系统信息 硬件信息

【转】Android 的cpu 硬盘 内存 网络设置 系统信息 硬件信息【转】Android 的cpu 硬盘 内存 网络设置 系统信息

【转】Android 的cpu 硬盘 内存 网络设置 系统信息 硬件信息

【转】Android 的cpu 硬盘 内存 网络设置 系统信息 硬件信息
2011年06月02日
  1.手机信息查看助手可行性分析
    开始进入编写程序前,需要对需求的功能做一些可行性分析,以做到有的放矢,如果有些无法实现的功能,可以尽快调整。
    这里分析一下项目需要的功能,主要是信息查看和信息收集,如版本信息、硬件信息等,这些都可以通过读取系统文件或者运行系统命令获取,而像获取安装的软件信息和运行时信息则需要通过API提供的接口获取。实现API接口不是什么问题,主要把精力集中在如何实现运行系统命令,获取其返回的结果功能实现上。具体实现代码如下所示:
  public class CMDExecute {
  public synchronized String run(String [] cmd, String workdirectory) throws IOException {
  String result = "";
  try {
  ProcessBuilder builder = new ProcessBuilder(cmd);
  InputStream in = null;
  //设置一个路径
  if (workdirectory != null) {
  builder.directory(new File(workdirectory));
  builder.redirectErrorStream(true);
  Process process = builder.start();
  in = process.getInputStream();
  byte[] re = new byte[1024];
  while (in.read(re) != -1)
  result = result + new String(re);
  }
  if (in != null) {
  in.close();   
  }
  } catch (Exception ex) {
  ex.printStackTrace();
  }
  return result;
  }
  }
  1.2 手机信息查看助手功能实现
  1.2.1 手机信息查看助手主界面
    按照预设的规划,将4类信息的查看入口放在主界面上,其布局文件为main.xml,基本上是用一个列表组件组成的,实现代码如下所示:
  在这里main.xml中使用的是LinearLayout布局,其中放置了一个ListView组件。
  
  
  
  
  1.2.2 查看系统信息实现
    当在运行的主界面单击第一行时,也就是“系统信息”这一行,将执行代码如下:
  1 case 0:
  2   intent.setClass(eoeInfosAssistant.this, System.class);
  3   startActivity(intent);
  4   break;
  代码运行后将显示系统(System)这个界面,这就是查看系统信息的主界面,其和主界面差不多,也就是列表显示几个需要查看的系统信息
  1.2.2.1 操作系统版本
  单击图9所示(无图)的界面第一行“操作系统版本”项,则会打开一个新的界面,其对应的是ShowInfo.java文件,然后需要显示该设备的操作系统版本信息,而这个信息在/proc/version中有,可以直接调用。在可行性分析中给出的CMDExencute类来调用系统的cat命令获取该文件的内容,实现代码如下:
  1 public static String fetch_version_info() {
  2     String result = null;
  3     CMDExecute cmdexe = new CMDExecute();
  4     try {
  5         String[ ] args = {"/system/bin/cat", "/proc/version"};
  6         result = cmdexe.run(args, "system/bin/");
  7     } catch (IOException ex) {
  8         ex.printStackTrace();
  9     }
  10     return result;
  11 }
    上述代码使用的是CMDExecute类,调用系统的“"/system/bin/cat"”工具,获取“"/proc/version"”中内容。其运行效果如图9。从图中显示的查寻结果可以看到,这个设备的系统版本是Linux version 2.6.25-018430-gfea26b0。
  1.2.2.2 系统信息
    在Android中,想要获取系统信息,可以调用其提供的方法System.getProperty(propertyStr),而系统信息诸如用户根目录(user.home)等都可以通过这个方法获取,实现代码如下:
  1 public static StringBuffer buffer = null;
  2
  3  private static String initProperty(String description,String propertyStr) {
  4     if (buffer == null) {
  5         buffer = new StringBuffer();
  6     }
  7     buffer.append(description).append(":");
  8     buffer.append (System.getProperty(propertyStr)).append("\n");
  9     return buffer.toString();
  10 }
  11
  12  private static String getSystemProperty() {
  13     buffer = new StringBuffer();
  14     initProperty("java.vendor.url","java.vendor.url");
  15     initProperty("java.class.path","java.class.path");
  16     ...
  17     return buffer.toString();
  18 }
  上述代码主要是通过调用系统提供的System.getProperty方法获取指定的系统信息,并合并成字符串返回。
  1.2.2.3 运营商信息
    运营商信息中包含IMEI、手机号码等,在Android中提供了运营商管理类(TelephonyManager),可以通过TelephonyManager来获取运营商相关的信息,实现的关键代码如下:
  1 public static String fetch_tel_status(Context cx) {
  2     String result = null;
  3     TelephonyManager tm = (TelephonyManager) cx.getSystemService(Context.TELEPHONY_SERVICE);
  4     String str = " ";
  5     str += "DeviceId(IMEI) = " + tm.getDeviceId() + "\n";
  6     str += "DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion()+"\n";
  7     // TODO: Do something ...
  8      int mcc = cx.getResources().getConfiguration().mcc;
  9     int mnc = cx.getResources().getConfiguration().mnc;
  10     str +="IMSI MCC (Mobile Country Code): " +String.valueOf(mcc) + "\n";
  11     str +="IMSI MNC (Mobile Network Code): " +String.valueOf(mnc) + "\n";
  12     result = str;
  13     return result;
  14 }
    在上述的代码中,首先调用系统的getSystemService (Context.TELEPHONY_SERVICE)方法获取一个TelephonyManager对象tm,进而调用其方法getDeviceId()获取DeviceId信息,调用getDeviceSoftware Version()获取设备的软件版本信息等。
  1.2.3 查看硬件信息
  1.2.3.1 获取CPU信息
    可以在手机设备的/proc/cpuinfo中获取CPU信息,调用CMDEexecute执行系统的cat的命令,读取/proc/cpuinfo的内容,显示的就是其CPU信息,实现代码如下:
  1 public static String fetch_cpu_info() {
  2     String result = null;
  3     CMDExecute cmdexe = new CMDExecute();
  4     try {
  5         String[ ] args = {"/system/bin/cat", "/proc/cpuinfo"};
  6         result = cmdexe.run(args, "/system/bin/");
  7         Log.i("result", "result=" + result);
  8     } catch (IOException ex) {
  9         ex.printStackTrace();
  10     }
  11     return result;
  12 }
  上述代码使用CMDExecute,调用系统中的"/system/bin/cat"命令查看"/proc/cpuinfo"中的内容,即可得到CPU信息。
  1.2.3.2 获取内存信息
    获取内存信息的方法和获取CPU信息的实现差不多,可以读取/proc/meminfo信息,另外还可以通过getSystemService(Context.ACTIVIT_SERV-
  ICE)获取ActivityManager.MemoryInfo对象,进而获取可用内存信息,主要代码如下:
  
  
  
  
  View Code  1 /**
  2  *系统内存情况查看
  3  */
  4  public static String getMemoryInfo(Context context) {
  5     StringBuffer memoryInfo = new StringBuffer();
  6    
  7     final ActivityManager activityManager =
  8         (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
  9     ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
  10     activityManager.getMemoryInfo(outInfo);
  11    
  12     memoryInfo.append("\nTotal Available Memory :").append(outInfo.availMem >> 10).append("k");
  13     memoryInfo.append("\nTotal Available Memory :").append(outInfo.availMem >> 20).append("k");
  14     memoryInfo.append("\nIn low memory situation:").append(outInfo.lowMemory);
  15    
  16     String result = null;
  17     CMDExecute cmdexe = new CMDExecute();
  18     try {
  19         String[ ] args = {"/system/bin/cat", "/proc/meminfo"};
  20         result = cmdexe.run(args, "/system/bin/");
  21     } catch (IOException ex) {
  22         Log.i("fetch_process_info","ex=" + ex.toString());
  23     }
  24     return (memoryInfo.toString() + "\n\n" + result);
  25 }
  上述代码中首先通过ActivityManager对象获取其可用的内存,然后通过查看“/proc/meminfo”内容获取更详细的信息。
  1.2.3.3 获取磁盘信息
    手机设备的磁盘信息可以通过df命令获取,所以,这里获取磁盘信息的方法和前面类似,惟一不同的是,这个是直接执行命令,获取其命令的返回就可以了,关键代码如下:
  //磁盘信息
  public static String fetch_disk_info() {
  String result = null;
  CMDExecute cmdexe = new CMDExecute();
  try {
  String[ ] args = {"/system/bin/df"};
  result = cmdexe.run(args, "/system/bin/");
  Log.i("result", "result=" + result);
  } catch (IOException ex) {
  ex.printStackTrace();
  }
  return result;
  }
  1.2.3.4 获取网络信息
  要获取手机设备的网络信息,只要读取/system/bin/netcfg中的信息就可以了,关键代码如下:
  public static String fetch_netcfg_info() {
  String result = null;
  CMDExecute cmdexe = new CMDExecute();
  try {
  String[ ] args = {"/system/bin/netcfg"};
  result = cmdexe.run(args, "/system/bin/");
  } catch (IOException ex) {
  Log.i("fetch_process_info","ex=" + ex.toString());
  }
  return result;
  }
  1.2.3.5获取显示频信息
    除了显示手机的CPU、内存、磁盘信息外,还有个非常重要的硬件,显示频。在Android中,它提供了DisplayMetrics类,可以通过getApplication Context()、getResources()、getDisplayMetrics()初始化,进而读取其屏幕宽(widthPixels)、高(heightPixels)等信息,实现的关键代码如下:
  
  
  
  
  View Code  1 public static String getDisplayMetrics(Context cx) {
  2     String str = "";
  3     DisplayMetrics dm = new DisplayMetrics();
  4     dm = cx.getApplicationContext().getResources().getDisplayMetrics();
  5     int screenWidth = dm.widthPixels;
  6     int screenHeight = dm.heightPixels;
  7     float density = dm.density;
  8     float xdpi = dm.xdpi;
  9     float ydpi = dm.ydpi;
  10     str += "The absolute width: " + String.valueOf(screenWidth) + "pixels\n";
  11     str += "The absolute heightin: " + String.valueOf(screenHeight) + "pixels\n";
  12     str += "The logical density of the display. : " + String.valueOf(density) + "\n";
  13     str += "X dimension : " + String.valueOf(xdpi) +"pixels per inch\n";
  14     str += "Y dimension : " + String.valueOf(ydpi) +"pixels per inch\n";
  15     return str;
  16 }
  1.2.4 查看软件信息
  在Android上,可以在手机上随便安装自己喜欢的应用软件,查看软件信息的功能就是收集并显示已经安装的应用软件信息。Android提供了getPackageManager()、getInstalledApplications(0)方法,可以直接返回全部已经安装的应用列表。这个功能就是只需要获取列表,再进行显示在列表中就可以了。但是,如果安装的软件比较多,那么获取信息所花费的时间会比较多,为了更好地完善用户使用的体验,在获取列表时,需要在界面提示用户耐心等待,这就需要用到Android提供的另外一个功能Runnable。
  引入Runnable比较简单,只需要在定义类的时候实现Runnable接口就可以了,所以,这里的软件信息查看界面对应的Software.java类声明代码如下:
  public class Software extends Activity implements Runnable {
  . . .
  }
  然后需要在这个Activity启动的时候,引入进度条ProgressDialog来显示一个提示界面,onCreate代码如下所示:
  1 public void onCreate(Bundle icicle) {
  2     Super.onCreate(icicle);
  3     setContentView(R.layout.softwares);
  4     setTitle("软件信息");
  5     itemlist = (ListView) findViewById(R.id.itemlist);
  6     pd = ProgressDialog.show(this, "请稍候. .", "正在收集你已经安装的软件信息. . .", true, false);
  7     Thread thread = new Thread(this);
  8     thread.start();
  9 }
    该方法创建了一个ProgressDialog,并设定其提示信息。然后实现其线程的run()方法,该方法实现其真正执行的逻辑,实现代码如下:
  @Override
  Public void run() {
  fetch_installed_apps();
  handler.sendEmptyMessage(0);
  }
  上述代码调用自定义的fetch_installed_app()方法获取已经安装的应用信息,这个方法是比较消耗时间的,实现代码如下:
  
  
  
  
  View Code  1     public ArrayList fetch_installed_apps () {
  2         List packages = getPackageManager().getInstalledApplications(0);
  3         ArrayList> list = new ArrayList>(packages.size());
  4        
  5         Iterator l = packages.iterator();
  6         while (l.hasNext()) {
  7             HashMap map = new HashMap();
  8             ApplicationInfo app = (ApplicationInfo) l.next();
  9             String packageName = app.packageName;
  10             String label = " ";
  11             try {
  12                label = getPackageManager().getApplicationLabel(app).toString();
  13             } catch (Exception e) {
  14                 Log.i("Exception", e.toString()
  15             );
  16         }
  17         map = new HashMap();
  18         map.put("name", label);
  19         map.put("desc", packageName);
  20         list.add(map);
  21         }
  22         return list;
  23     }
    上述代码使用getPackageManager().getInstalledApplications(0)获取已经安装的软件信息,进而构造用来显示的列表(List)对象,同时,界面通过进度条(ProgressDialog)显示提示信息,运行效果如图18所示。
  当这个方法运行完成后,会调用handler.sendEmptyMessage(0)语句给handler发送一个通知消息,使其执行下面的动作,下面就是这个handler的实现方法:
  private Handler handler = new Handler() {
  public void handleMessage msg) {
  refreshListItems();
  pd.dismiss();
  };   }
    上述代码中,当其接收到run()线程传递的消失后,先调用refreshListItems()方法显示列表,最后调用进度条ProgressDialog的dismiss方法使其等待提示消失。而refreshListItems()的实现代码如下:
  private void refreshListItems() {
  list = fetch_installed_apps();
  SimpleAdapter notes = new SimpleAdater(
  this, list, R.layout.info_row,
  new String[] {"name", "desc"},new int[] {R.id.name,    R.id.desc});
  list.setAdapter(notes);
  setTitle("软件信息,已经安装" + list.size()+"款应用.");
  }
  这些代码,显示已经安装的应用列表的同时,在Title上显示一共安装了多少款应用
  1.2.5 获取运行时信息
    运行时的一些信息,包括后台运行的Service、Task,以及进程信息,其运行界面如图20。
  1.2.5.1 获取正在运行的Service信息
    可以通过调用context.getSystemService(Context.ACTIVITY_SERVICE)获取ActivityManager,进而通过系统提供的方法getRunningServices(int maxNum)获取正在运行的服务列表(RunningServiceInfo),再对其结果进一步分析,得到服务对应的进程名及其他信息,实现的关键代码如下:
  
  
  
  
  View Code  1 //正在运行的服务列表
  2 public static String getRunningServicesInfo(Context context) {
  3     StringBuffer serviceInfo = new StringBuffer();
  4     final ActivityManager activityManager = (ActivityManager) context
  5     .getSystemService(Context. ACTIVITY_SERVICE);
  6     List services = activityManager.getRunningServices(100);
  7
  8     Iterator l = services.iterator();
  9     while (l.hasNext()) {
  10         RunningServiceInfo si = (RunningServiceInfo) l.next();
  11         serviceInfo.append("pid: ").append(si.pid);
  12         serviceInfo.append("\nprocess: ").append(si. process);
  13         serviceInfo.append("\nservice: ").append(si. service);
  14         serviceInfo.append("\ncrashCount: ").append(si. crashCount);
  15         serviceInfo.append("\nclicentCount: ").append(si.clientCount);
  16         serviceInfo.append("\nactiveSince:").append(ToolHelper.formatData(si.activeSince));
  17         serviceInfo.append("\nlastActivityTime: ").append(ToolHelper.formatData(si.lastActivityTime));
  18         serviceInfo.append("\n\n ");
  19     }
  20     return serviceInfo.toString();
  21 }
  上述代码调用activityManager.getRunningServices(100)获取正在运行的服务,并依次遍历得到每个服务对应的pid,进程等信息,
  1.2.5.2 获取正在运行的Task信息
    获取正在运行的Task信息调用的是activityManager.getRunningTasks(int maxNum)来获取对应的正在运行的任务信息列表(RunningTaskInfo),进而分析、显示任务信息,其关键代码如下:
  
  
  
  
  View Code  1 public static String getRunningTaskInfo(Context context) {
  2     StringBuffer sInfo = new StringBuffer();
  3     final ActivityManager activityManager = (ActivityManager) context
  4     .getSystemService(Context. ACTIVITY_SERVICE);
  5     List tasks = activityManager.getRunningTasks(100);
  6     Iterator l = tasks.iterator();
  7     while (l.hasNext()) {
  8         RunningTaskInfo ti = (RunningTaskInfo) l.next();
  9         sInfo.append("id: ").append(ti.id);
  10         sInfo.append("\nbaseActivity: ").append(ti. baseActivity.flattenToString());
  11         sInfo.append("\nnumActivities: ").append(ti. nnumActivities);
  12         sInfo.append("\nnumRunning: ").append(ti. numRunning);
  13         sInfo.append("\ndescription: ").append(ti. description);
  14         sInfo.append("\n\n");
  15     }
  16     return sInfo.toString();
  17 }
    上述代码调用系统提供的activityManager.getRunningTasks(100)方法获取任务列表,依次获取对应的id等信息,运行效果如图22。从图中显示可以看出,获取手机上正在运行的Task的列表和其对应的进程信息,这对用户了解设备运行情况非常有用。
  1.2.5.3 获取正在运行的进程信息
  该段程序是通过CMD Execute的方式来运行系统命令。关键代码如下:
  1 public static String fetch_process_info() {
  2     Log.i("fetch_process_info","start. . . . ");
  3     String result = null;
  4     CMDExecutr cmdexe = new CMDExecute();
  5     try {
  6         String [ ] args = {"/system/bin/top", "-n", "1"};
  7         result = cmdexe.run(args, "/system/bin/");
  8     } catch (IOException ex) {
  9         Log.i("fetch_process_info","ex=" + ex.toString());
  10     }
  11     return result;
  12 }
  通过这个功能可以非常详细地了解到正在运行的进程和各个进程所消耗的资源情况。
  1.2.6 文件浏览器
    文件浏览器的这个功能,用户可以遍历浏览整个文件系统,以便更好地了解手机设备状况。在主界面单击最后一行将执行下列代码:
  case 4:
    intent.setClass(eoeInfosAssistant.this, FSExplorer.class);
    startActivity(intent);
    break;
    对于如何进入子目录,并获取和显示其内部的文件夹和文件,也就是单击每行时响应的实现,代码如下:
  
  
  
  
  View Code  1 @Override
  2 public void onItemClick(AdapterView parent, View v, int position, long id) {
  3     Log.i(TAG, "item clicked! [" + position + "]");
  4     if (position == 0) {
  5         path = "/";
  6         refreshListItems(path);
  7     }else if(position ==1) {
  8         goToParent();
  9     } else {
  10         path = (String) list.get(position).get("path");
  11         File file = new File(path);
  12         if (file.isDirectory())
  13             refreshListItems(path);
  14         else
  15             Toast.makeText(FSExplorer.this,getString(R.string.is_file), Toast.LENGTH_SHORT).show();
  16     }
  17 }
  2. Android编程获取手机型号,