转载自http://blog.sina.com.cn/s/blog_4d58929f0100wgfg.html
package com.test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.MemoryInfo; import android.app.ActivityManager.RunningAppProcessInfo; import android.app.ListActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.os.SystemClock; import android.text.format.Formatter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class Activity01 extends ListActivity { private ListView listV; // TextView textV1; // TextView textV2; private ActivityManager am; private List<ApplicationInfo> allAppList; PackageUtil packageUtil; ProcessMemoryUtil processMemoryUtil=new ProcessMemoryUtil(); String [] list=new String[30]; //为进程获取基本的信息 private static final int INDEX_FIRST = -1; private static final int INDEX_CPU = INDEX_FIRST + 2; private static final int INDEX_RSS = INDEX_FIRST + 6; private static final int INDEX_NAME = INDEX_FIRST + 9; private static final int Length_ProcStat = 9; private List<String[]> PMUList = null; private String getProcessRunningInfo() { Log.i("fetch_process_info", "start. . . . "); String result = null; CMDExecute cmdexe = new CMDExecute(); try { String[] args = {"/system/bin/top", "-n", "1"}; result = cmdexe.run(args, "/system/bin/"); } catch (IOException ex) { Log.i("fetch_process_info", "ex=" + ex.toString()); } return result; } private int parseProcessRunningInfo(String infoString) { String tempString = ""; boolean bIsProcInfo = false; String[] rows = null; String[] columns = null; rows = infoString.split("[\n]+"); // 使用正则表达式分割字符串 for (int i = 0; i < rows.length; i++) { tempString = rows[i]; if (tempString.indexOf("PID") == -1) { if (bIsProcInfo == true) { tempString = tempString.trim(); columns = tempString.split("[ ]+"); if (columns.length == Length_ProcStat) { PMUList.add(columns); } } } else { bIsProcInfo = true; } } return PMUList.size(); } // 初始化所有进程的CPU和内存列表,用于检索每个进程的信息 public void initPMUtil() { PMUList = new ArrayList<String[]>(); //String resultString = getProcessRunningInfo(); // Log.i("listsize:",parseProcessRunningInfo(resultString)+""); } // 根据进程名获取CPU和内存信息 public String getMemInfoByName(String procName) { String result = ""; String tempString = ""; for (Iterator<String[]> iterator = PMUList.iterator(); iterator.hasNext();) { String[] item = (String[]) iterator.next(); tempString = item[INDEX_NAME]; if (tempString != null && tempString.equals(procName)) { result = "CPU:" +item[INDEX_CPU] + " 内存:" + item[INDEX_RSS]; break; } } return result; } public class ListAdapter extends BaseAdapter { List<Programe> list = new ArrayList<Programe>(); LayoutInflater la; Context context; public ListAdapter(List<Programe> list ,Context context){ this.list = list; this.context = context; } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return list.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null) { la = LayoutInflater.from(context); convertView=la.inflate(R.layout.list_item, null); holder = new ViewHolder(); holder.imgage=(ImageView) convertView.findViewById(R.id.image); holder.text = (TextView) convertView.findViewById(R.id.text); holder.text2 = (TextView) convertView.findViewById(R.id.text2); holder.text3 = (TextView) convertView.findViewById(R.id.text3); holder.text4 = (TextView) convertView.findViewById(R.id.text4); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } final Programe pr = (Programe)list.get(position); //设置图标 holder.imgage.setImageDrawable(pr.getIcon()); //设置程序名 holder.text.setText(pr.getName()); //CPU holder.text2.setText(pr.getCpumen()); holder.text3.setText(pr.getCpu()); holder.text4.setText(pr.getMem()); return convertView; } } class ViewHolder{ TextView text,text2,text3,text4; ImageView imgage; } public List<Programe> getRunningProcess(){ PackageUtil pi = new PackageUtil(this); ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); //获取正在运行的应用 List<RunningAppProcessInfo> run = am.getRunningAppProcesses(); //获取包管理器,在这里主要通过包名获取程序的图标和程序名 PackageManager pm =this.getPackageManager(); List<Programe> list = new ArrayList<Programe>(); for(RunningAppProcessInfo ra : run){ //这里主要是过滤系统的应用和电话应用,当然你也可以把它注释掉。 if(ra.processName.equals("system") || ra.processName.equals("com.android.phone")||ra.processName.length()==0||ra.processName.equals("com.asiainfo.android:remote")||ra.processName.equals("com.google.android.apps.maps:FriendService")||ra.processName.equals("com.z4mod.z4root:three")||ra.processName.equals("com.google.android.apps.maps:driveabout") ){ continue; } Programe pr = new Programe(); Log.i("error(ra.processName):",ra.processName); Log.i("qwe",ra.processName); // pr.setIcon(pi.getInfo(ra.processName).loadIcon(pm)); Log.i("whathappened?",pi.getInfo(ra.processName).loadLabel(pm).toString()); pr.setName("--"+pi.getInfo(ra.processName).loadLabel(pm).toString()+"--"); pr.setCpumen(processMemoryUtil.getMemInfoByName(ra.processName)); pr.setIcon(pi.getInfo(ra.processName).loadIcon(pm)); pr.setMem(" 内存:"+getPidMemory(ra.pid).substring(7,getPidMemory(ra.pid).length()).trim()); pr.setCpu("CPU:"+getPidCpu(ra.pid)); System.out.println(pi.getInfo(ra.processName).loadLabel(pm).toString()+"(pid="+ra.pid+"):"+pr.getCpu() +" VmRSS:"+pr.getMem() +"CPU="+getPidCpu(ra.pid)); list.add(pr); } return list; } //获得手机当前任务列表 public void getTask() { //try{ am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); //arylistTask=new ArrayList<String>(); List<ActivityManager.RunningTaskInfo> rTask=am.getRunningTasks(30); int i=1; String taskName="com.test"; for(ActivityManager.RunningTaskInfo amTask : rTask) { taskName=amTask.baseActivity.getPackageName(); // list[i]=taskName; // Log.i("list[i]=", taskName); // arylistTask.add((i++)+":"+taskName+"(ID="+amTask.id+") "+processMemoryUtil.getMemInfoByName(taskName)); // Log.i("cpu,内存:",processMemoryUtil.getMemInfoByName(taskName)); } } //显示消息 public void textToast(String str,boolean isLong) { if(isLong==true) { Toast.makeText(this, str, Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } } //获取手机mac地址 public String getMacInfo(){ String other="adr=null"; WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if(wifiInfo.getMacAddress()!=null) other=wifiInfo.getMacAddress(); return other; } //获得已开机时间 private String getTimes() { long ut = SystemClock.elapsedRealtime() / 1000; if (ut == 0) { ut = 1; } int m = (int) ((ut / 60) % 60); int h = (int) ((ut / 3600)); return "您已经开机"+h + " 小时" + m + " 分钟"; } //获得手机电量 private BroadcastReceiver batteryReceiver=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int level = intent.getIntExtra("level", 0); Log.i("手机电量:",level+"%"); } }; //ROM容量 public long[] getRomMemroy() { long[] romInfo = new long[2]; //Total rom memory romInfo[0] = getTotalInternalMemorySize(); //Available rom memory File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); romInfo[1] = blockSize * availableBlocks; Log.i("ROM总容量:",romInfo[0]/(1024)+"KB"); Log.i("ROM可用容量:",romInfo[1]/(1024)+"KB"); // getVersion(); return romInfo; } public long getTotalInternalMemorySize() { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } //sd卡容量 public long[] getSDCardMemory() { long[] sdCardInfo=new long[2]; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { File sdcardDir = Environment.getExternalStorageDirectory(); StatFs sf = new StatFs(sdcardDir.getPath()); long bSize = sf.getBlockSize(); long bCount = sf.getBlockCount(); long availBlocks = sf.getAvailableBlocks(); sdCardInfo[0] = bSize * bCount;//总大小 Log.i("SD卡总容量:",sdCardInfo[0]/(1024)+"KB"); sdCardInfo[1] = bSize * availBlocks;//可用大小 Log.i("SD卡可用容量:",sdCardInfo[1]/(1024)+"KB"); } return sdCardInfo; } // 获取android当前可用内存大小 private String getAvailMemory() { //mi.availMem; 当前系统的可用内存 ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); MemoryInfo mi = new MemoryInfo(); am.getMemoryInfo(mi); return Formatter.formatFileSize(this.getBaseContext(), mi.availMem);// 将获取的内存大小规格化 } //指定进程占用内存 public String getPidMemory(int pid) { String str1 = "/proc/"+pid+"/status"; String str2=""; try { FileReader fr = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader(fr, 8192); while ((str2 = localBufferedReader.readLine()) != null) { if(str2.indexOf("VmRSS")>=0) { // Log.i("进程占用内存:", "---" + str2); return ""+str2; } } } catch (IOException e) { } return str2; } //指定进程占用CPU public String getPidCpu(int pid) { long singleCpu1=getSingleCpuTime(pid); long totalCpu1=getTotalCpuTime(); long singleCpu2=getSingleCpuTime(pid); long totalCpu2=getTotalCpuTime(); long xtotalCpu=totalCpu2-totalCpu1; long xsingleCpu=singleCpu2-singleCpu1; if(xtotalCpu>0&&xsingleCpu>0) { if(100*xsingleCpu/xtotalCpu<100) return 100*xsingleCpu/xtotalCpu+"%"; else return "100%"; } else return "0%"; } //获取CPU时间差使用量 public long getTotalCpuTime() { String str1 = "/proc/stat"; String str2=""; long sum=0; try { FileReader fr = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader(fr, 8192); while ((str2 = localBufferedReader.readLine()) != null) { if(str2.indexOf("cpu")>=0) { String [] temp=str2.split(" "); for(int x=2;x<temp.length;x++) { sum +=Long.valueOf(temp[x]).longValue(); } return sum; } } } catch (IOException e) { } return sum; } //获取单个进程CPU时间差使用量 public long getSingleCpuTime(int pid) { String str1 = "/proc/"+pid+"/stat"; String str2=""; long sum=0; try { FileReader fr = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader(fr, 8192); while ((str2 = localBufferedReader.readLine()) != null) { String [] temp=str2.split(" "); for(int x=13;x<17;x++) { sum +=Long.valueOf(temp[x]).longValue(); } return sum; } } catch (IOException e) {} return sum; } //获得系统总内存 private String getTotalMemory() { String str1 = "/proc/meminfo";// 系统内存信息文件 String str2; String[] arrayOfString; long initial_memory = 0; try { FileReader localFileReader = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192); str2 = localBufferedReader.readLine();// 读取meminfo第一行,系统总内存大小 arrayOfString = str2.split("\\s+"); for (String num : arrayOfString) { } initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存,单位是KB,乘以1024转换为Byte localBufferedReader.close(); } catch (IOException e) {} return Formatter.formatFileSize(getBaseContext(), initial_memory);// Byte转换为KB或者MB,内存大小规格化 } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); listV=(ListView)findViewById(R.id.list); setTitle("总内存:"+this.getTotalMemory()+" 可用内存:"+this.getAvailMemory()); registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); //注册电量监控 processMemoryUtil.initPMUtil(); Log.i("开机时间:",getTimes()); this.getTask(); //requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); getSDCardMemory(); getRomMemroy(); List<Programe> list = getRunningProcess(); ListAdapter adapter = new ListAdapter(list,this); //setContentView(R.layout.list_item); getListView().setAdapter(adapter); } }