---
title: "手机查看助手"
author: "senlinwuran"
date: "2011-09-06T11:25:50Z"
tags: ["Android"]
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2011-09-06T11:25:50Z"
id: 1166443
url: "https://senlinwuran.iteye.com/blog/1166443"
---

1.手机信息查看助手可行性分析  
开始进入编写程序前，需要对需求的功能做一些可行性分析，以做到有的放矢，如果有些无法实现的功能，可以尽快调整。  
这里分析一下项目需要的功能，主要是信息查看和信息收集，如版本信息、硬件信息等，这些都可以通过读取系统文件或者运行系统命令获取，而像获取安装的软件信息和运行时信息则需要通过API提供的接口获取。实现API接口不是什么问题，主要把精力集中在如何实现运行系统命令，获取其返回的结果功能实现上。具体实现代码如下所示：  
public class CMDExecute {

public synchronized String run ( String \[] cmd,String workdirectory)  
throws IOException {  
String result = “ ” ;

try {  
processBuilder builder = new ProcessBuilder ( cmd );  
//设置一个路径  
if ( workdirectory ! = null )  
builder.directory ( new File ( workdirectory ) ) ;  
builder.redirectErrorStream (true) ;  
Process process = builder.start ( ) ;  
InputStream in = process.getInputStream ( ) ;  
byte\[] re = new byte\[1024] ;  
while ( in.read ( re ) ) ;  
result = result + new String ( re ) ;  
}  
in.close ( ) ;

} catch ( Exception ex ) {  
Ex.printStackTrace ( ) ;  
}  
Return result ;  
}

}  
1.2手机信息查看助手功能实现  
1.2.1手机信息查看助手主界面  
按照预设的规划，将4类信息的查看入口放在主界面上，其布局文件为mail.xml，基本上是用一个列表组件组成的，实现代码如下所示：  
&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
       android:/orientation="vertical" android:layout\_width="fill\_parent"  
       android:layout\_height="fill\_parent"&gt;

       &lt;ListView   
         android:layout\_width="fill\_parent"  
            android:layout\_height="fill\_parent"   
            android:id="@+id/itemlist" /&gt;  
&lt;/LinearLayout&gt;  
在这里mail.xml中使用的是LinearLayout布局，其中放置了一个ListView组件。

1.2.2查看系统信息实现  
当在运行的主界面单击第一行时，也就是“系统信息”这一行，将执行代码如下：  
case 0;  
intent.setClass(eoeInfosAssistant.this, System.class);  
startActivity(intent);  
break;  
代码运行后将显示系统（System）这个界面，这就是查看系统信息的主界面，其和主界面差不多，也就是列表显示几个需要查看的系统信息，

1.2.2.1操作系统版本  
单击图9所示的界面第一行“操作系统版本”项，则会打开一个新的界面，其对应的是ShowInfo.java文件，然后需要显示该设备的操作系统版本信息，而这个信息在/proc/version中有，可以直接调用。在可行性分析中给出的CMDExencute类来调用系统的cat命令获取该文件的内容，实现代码如下：  
Public static String fetch\_version\_info( ) {  
String result = null;  
CMDExecute cmdexe = new CMDExecute ( );  
Try {  
String\[ ] args = {"/system/bin/cat", "/proc/version" };  
result = cmdexe.run(args, "system/bin/");  
} catch (IOException ex) {  
ex.printStackTrace( );  
}  
Return result;  
}  
上述代码使用的是CMDExecute类，调用系统的“"/system/bin/cat"”工具，获取“"/proc/version"”中内容。其运行效果如图9。从图中显示的查寻结果可以看到，这个设备的系统版本是Linux version 2.6.25-018430-gfea26b0。  
     

1.2.2.2系统信息  
在Android中，想要获取系统信息，可以调用其提供的方法System.getProperty(propertyStr)，而系统信息诸如用户根目录（user.home）等都可以通过这个方法获取，实现代码如下：  
private static String initProperty(String description,String propertyStr) {  
if (buffer == null) {  
buffer = new StringBuffer();  
}  
buffer.append(description).append(":");  
buffer.append (System.getProperty(propertyStr)).append("\\n");  
return buffer.toString();  
}  
private static String getSystemProperty() {  
buffer = new StringBuffer();  
initProperty("java.vendor.url","java.vendor.url");  
initProperty("java.class.path","java.class.path");  
. . .  
return buffer.toString();  
}  
上述代码主要是通过调用系统提供的System.getProperty方法获取指定的系统信息，并合并成字符串返回。

1.2.2.3运营商信息  
运营商信息中包含IMEI、手机号码等，在Android中提供了运营商管理类（TelephonyManager），可以通过TelephonyManager来获取运营商相关的信息，实现的关键代码如下：  
public static String fetch\_tel\_status(Context cx) {  
String result = null;  
TelephonyManager tm = (TelephonyManager) cx  
.getSystemService(Context.TELEPHONY\_SERVICE);//  
string str = " ";  
str += "DeviceId(IMEI) = " + tm.getDetDeviceId() + "\\n";  
str += "DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion()+"\\n";  
. . .  
int mcc = cx.getResources().getConfiguration().mcc;  
int mcc = cx.getResources().getConfiguration().mcc;  
str +="IMSI MCC (Mobile Country Code): " +String.valueOf(mcc) + "\\n";  
str +="IMSI MCC (Mobile Country Code): " +String.valueOf(mnc) + "\\n";  
result = str;  
return result;  
}  
在上述的代码中，首先调用系统的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信息，实现代码如下：  
public static String fetch\_cpu\_info() {  
String result = null;  
CMDExecute cmdexe = new CMDExecute();  
try {  
String\[ ] args = { "/system/bin/cat", "/proc/cpuinfo" }  
result = cmdexe.run(args, "/system/bin/");  
Log.i("result","result=" + result);  
} catch (IOException ex) {  
ex.printStackTrace();  
}  
return result;  
}  
上述代码使用CMDExecute,调用系统中的"/system/bin/cat"命令查看"/proc/cpuinfo"中的内容，即可得到CPU信息。

1.2.3.2获取内存信息  
获取内存信息的方法和获取CPU信息的实现差不多，可以读取/proc/meminfo信息，另外还可以通过getSystemService(Context.ACTIVIT\_SERV-  
ICE)获取ActivityManager.MemoryInfo对象，进而获取可用内存信息，主要代码如下：  
/\**  
\*系统内存情况查看  
\*/  
public static String getMemoryInfo(Context context) {  
StringBuffer memoryInfo = new StringBuffer()；  
final ActivityManager activityManager = (AcctivityManager) context  
.getSystemService(Context.ACTIVITY\_SERVICE);  
ActivityManager. MemoryInfo outInfo = new ActivityManager. MemoryInfo();  
activityManager.getMemoryInfo(outInfo);  
memoryInfo.append("\\nTotal Available Memory :").append(  
outInfo.availMem &gt;&gt; 10).append("k");  
memoryInfo.append("\\nTotal Available Memory :").append(  
outInfo.availMem &gt;&gt; 20).append("k");  
memoryInfo.append("\\nIn low memory situation:").append(  
outInfo. Lowmemory);  
String result = null;  
CMDExecute cmdexe = new CMDExecute();  
try {  
String\[ ] args = { "/system/bin/cat", "/proc/meminfo" };  
result = cmdexe.run(args, "/system/bin/");  
} catch (IOException ex) {  
Log.i("fetch\_process\_info","ex=" + ex.toString());  
}  
Return memoryInfo.toString()+"\\n\\n"+result;  
}  
上述代码中首先通过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/cdf"}  
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;  
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）等信息，实现的关键代码如下：  
public static String getDisplayMetrics(Context cx) {  
String str = " ";  
DisplayMetrics dm = new DisplayMetrics();  
dm = cx.getApplicationContext().getResources().getDisplayMetrics();  
int screenWidth = dm.widthPixels;  
int screenHeight = dm.heightPixels;  
float density = dm.density;  
float xdpi = dm.xdpi;  
float ydpi = dm.ydpi;  
str += "The absolute width: " + String.valueOf(screenWidth) + "pixels\\n";  
str += "The absolute heightin: " + String.valueOf(screenHeight) + "pixels\\n";  
str += "The logical density of the display. : " + String.valueOf(density) + "\\n";  
str += "X dimension : " + String.valueOf(xdpi) +"pixels per inch\\n";  
str += "Y dimension : " + String.valueOf(ydpi) +"pixels per inch\\n";  
renturn str;  
}

1.2.4查看软件信息  
在Android上，可以在手机上随便安装自己喜欢的应用软件，查看软件信息的功能就是收集并显示已经安装的应用软件信息。  
在Android中，它提供了getPackageManager()、getInstalledApplications(0)方法，可以直接返回全部已经安装的应用列表。这个功能就是只需要获取列表，再进行显示在列表中就可以了。但是，如果安装的软件比较多，那么获取信息所花费的时间会比较多，为了更好地完善用户使用的体验，在获取列表时，需要在界面提示用户耐心等待，这就需要用到Android提供的另外一个功能Runnable。  
引入Runnable比较简单，只需要在定义类的时候实现Runnable接口就可以了，所以，这里的软件信息查看界面对应的Software.java类声明代码如下：  
public class Software extends Activity implements Runnable {  
. . .  
}  
然后需要在这个Activity启动的时候，引入进度条ProgressDialog来显示一个提示界面，onCreate代码如下所示：  
Public void onCreate(Bundle icicle) {  
    Super.onCreate(icicle);  
setContentView(R.layout.softwares);  
setTitle("软件信息")  
itemlist = (ListView) findViewById(R.id.itemlist);  
pd = ProgressDialog.show(this, "请稍候. .", "正在收集你已经安装的软件信息. . .", true,flase);  
Thread thread = new Thread(this);  
Thread.start();  
}  
该方法创建了一个ProgressDialog，并设定其提示信息。然后实现其线程的run()方法，该方法实现其真正执行的逻辑，实现代码如下：  
@Override  
Public void run() {  
    fetch\_installed\_apps();  
    handler.sendEmptyMessage(0);  
}  
上述代码调用自定义的fetch\_installed\_app()方法获取已经安装的应用信息，这个方法是比较消耗时间的，实现代码如下：  
public List fetch\_installed\_apps () {  
List&lt;ApplicationInfo&gt; packages = getPackageManager().getInstalledApplications(0);  
list = new ArrayList&lt;Ma&lt;String, Object&gt;&gt;(  
packages.size());  
Iterator&lt;ApplicationInfo&gt; l = packages.iterator();  
while (l.hasNext()) {  
Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();  
ApplicationInfo app = (ApplicationInfo) l.next();  
String packageName = app.packageName;  
         String label = " ";  
         try {  
            label = getPackageManager().getApplicationLabel(app).toString();  
         } catch (Exception e) {  
         Log.i("Exception", e.toString());  
         }  
map = new HashMap&lt;String, Object&gt;();  
map.put("name", label);  
map.put("desc", packageName);  
list.add(map);  
}  
Return list;  
}  
上述代码使用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 });  
Itemlist.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），再对其结果进一步分析，得到服务对应的进程名及其他信息，实现的关键代码如下：  
//正在运行的服务列表  
public static String getRunningServicesInfo(Context context) {  
StringBuffer serviceInfo = new StringBuffer();  
final ActivityManager activityManager = (ActivityManager) context  
.getSystemService(Context. ACTIVITY\_SERVICE);  
List&lt;RunningServiceInfo&gt; services = activityManager.getRunningServices(100);

Iterator&lt;RunningserviceInfo&gt; l = services.iterator();  
while (l.hasNext()) {  
RunningServiceInfo si = (RunningServiceInfo) l.next();  
serviceInfo.append("pid: ").append(si.pid);  
serviceInfo.append("\\nprocess: ").append(si. process);  
serviceInfo.append("\\nservice: ").append(si. service);  
serviceInfo.append("\\ncrashCount: ").append(si. crashCount);  
serviceInfo.append("\\nclicentCount: ").append(si. clicentCount);  
serviceInfo.append("\\nactiveSince:").append(ToolHelper.formatData(si.activeSince));  
serviceInfo.append("\\nlastActivityTime: ").append(ToolHelper.formatData(si.lastAct-  
ivityTime));  
serviceInfo.append("\\n\\n ");  
}  
return serviceInfo.toString();  
}  
上述代码调用activityManager.getRunningServices(100)获取正在运行的服务，并依次遍历得到每个服务对应的pid,进程等信息，

1.2.5.2获取正在运行的Task信息  
获取正在运行的Task信息调用的是activityManager.getRunningTasks(int maxNum)来获取对应的正在运行的任务信息列表（RunningTaskInfo），进而分析、显示任务信息，其关键代码如下：  
public static String getRunningTaskInfo(Context context) {  
StringBuffer sInfo = new StringBuffer();  
final ActivityManager activityManager = (ActivityManager) context  
.getSystemService(Context. ACTIVITY\_SERVICE);  
List&lt;RunningTaskInfo&gt; tasks = activityManager.getRunningTasks(100);  
Iterator&lt;RunningTaskInfo&gt; l = tasks.iterator();  
while (l.hasNext()) {  
RunningTaskInfo ti = (RunningTaskInfo) l.next();  
sInfo.append("id: ").append(ti.id);  
sInfo.append("\\nbaseActivity: ").append(ti. baseActivity.flattenToString());  
sInfo.append("\\nnumActivities: ").append(ti. nnumActivities);  
sInfo.append("\\nnumRunning: ").append(ti. numRunning);  
sInfo.append("\\ndescription: ").append(ti. description);  
sInfo.append("\\n\\n);  
}  
Return sInfo.toString();  
}  
上述代码调用系统提供的activityManager.getRunningTasks(100)方法获取任务列表，依次获取对应的id等信息，运行效果如图22。从图中显示可以看出，获取手机上正在运行的Task的列表和其对应的进程信息，这对用户了解设备运行情况非常有用。  
1.2.5.3获取正在运行的进程信息  
该段程序是通过CMD Executo的方式来运行系统命令。关键代码如下：  
public static String fetch\_process\_info() {  
Log.i("fetch\_process\_info","start. . . . ");  
String result = null;  
CMDExecutr cmdexe = new CMDExecute();  
try {  
String \[ ] args = { "/system/bin/top", "-n", "l" };  
result = cmdexe.run(args, "/system/bin/");  
} catch (IOException ex) {  
Log.i("fetch\_process\_info","ex=" + ex.toString());  
}  
return result;  
}  
通过这个功能可以非常详细地了解到正在运行的进程和各个进程所消耗的资源情况。

1.2.6文件浏览器  
文件浏览器的这个功能，用户可以遍历浏览整个文件系统，以便更好地了解手机设备状况。在主界面单击最后一行将执行下列代码：  
case 4:  
intent.setClass(eoeInfosAssistant.this, FSExplorer.class);  
startActivity(intent);  
break;  
对于如何进入子目录，并获取和显示其内部的文件夹和文件，也就是单击每行时响应的实现，代码如下：  
@Override  
public void onItemClick(AdapterView&lt;?&gt; parent, View v, int position, long id) {  
Log.i(TAG, "item clicked! \[" + position + "]");  
if (position == 0) {  
path = "/";  
refreshListItems(path);  
}else if(position ==1) {  
goToParent();  
} else {  
path = (String) list.get(position).get("path");  
File file = new File(path);  
if (file.isDirectory())  
refreshListItems(path);  
else  
Toast.makeText(FSExplorer.this,  
getString(R.string.is\_file)’  
Toast.LENGTH\_SHORT).show();  
}  
}