Android 시스템 정보 보기 항목

전재 하 다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("[
]+");        //                           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);            }         }

좋은 웹페이지 즐겨찾기