27、获取运行时信息(包括运行时的service、运作任务、正在运行的进程信息)

27、获取运行时信息(包括运行时的service、运行任务、正在运行的进程信息)

-------------------------------main.java------------------------


package com.example.running;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;


public class MainActivity extends ActionBarActivity implements OnItemClickListener {


public static final int RunningService = 1;
public static final int RunningTasks = 2;
public static final int RunningProcesses = 3;
ListView itemlist = null;
List<Map<String, Object>> list;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("运行时信息");
itemlist = (ListView) findViewById(R.id.itemlist);
refreshListItems();
}


private void refreshListItems() {
list = buildListForSimpleAdapter();
SimpleAdapter notes = new SimpleAdapter(this, list, R.layout.info_row,
new String[] { "name", "desc" }, new int[] { R.id.name,
R.id.desc });
itemlist.setAdapter(notes);
itemlist.setOnItemClickListener(this);
itemlist.setSelection(0);
}

private List<Map<String, Object>> buildListForSimpleAdapter() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(3);
// Build a map for the attributes
Map<String, Object> map = new HashMap<String, Object>();

map = new HashMap<String, Object>();
map.put("id", MainActivity.RunningService);
map.put("name", "运行的service");
map.put("desc", "正在运行的后台服务.");
list.add(map);



map = new HashMap<String, Object>();
map.put("id", MainActivity.RunningTasks);
  map.put("name", "运行任务");
map.put("desc", "正在运行的任务.");
list.add(map);


map = new HashMap<String, Object>();
map.put("id", MainActivity.RunningProcesses);
  map.put("name", "进程信息");
map.put("desc", "正在运行的进程.");
list.add(map);
 

return list;
}


@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent = new Intent();
Bundle info = new Bundle();
Map<String, Object> map = list.get(position);
info.putInt("id",  (Integer) map.get("id"));
info.putString("name", (String) map.get("name"));
info.putString("desc", (String) map.get("desc"));
intent.putExtra("android.intent.extra.info", info);
intent.setClass(MainActivity.this, ShowInfoActivity.class);
startActivityForResult(intent, 0);
}
}


----------------------------------ShowInfoActivity.java----------------------------


package com.example.running;


 
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;


public class ShowInfoActivity extends Activity implements Runnable {
private static final String TAG = "ShowInfo";


TextView info;
TextView title;
private ProgressDialog pd;
public String info_datas;
public boolean is_valid = false;
public int _id = 0;
public String _name = "";


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showinfo);
revParams();
info = (TextView) findViewById(R.id.info);
title = (TextView) findViewById(R.id.title);
setTitle("eoeInfosAssistant: " + _name);
title.setText(_name);
load_data();
}


private void load_data() {
pd = ProgressDialog.show(this, "Please Wait a moment..",
"fetch info datas...", true, false);
Thread thread = new Thread(this);
thread.start();
}


// 接收传递进来的信息
private void revParams() {
Log.i(TAG, "revParams.");
Intent startingIntent = getIntent();
if (startingIntent != null) {
Bundle infod = startingIntent
.getBundleExtra("android.intent.extra.info");
if (infod == null) {
is_valid = false;
} else {
_id = infod.getInt("id");
_name = infod.getString("name");
is_valid = true;
}
} else {
is_valid = false;
}
}


 


 


@Override
public void run() {
switch (_id) {
case MainActivity.RunningProcesses:
info_datas = FetchData.fetch_process_info();
break;
case MainActivity.RunningService:
info_datas = FetchData.getRunningServicesInfo(this);
break;
case MainActivity.RunningTasks:
info_datas = FetchData.getRunningTasksInfo(this);
break;
}


handler.sendEmptyMessage(0);
}


private Handler handler = new Handler() {
public void handleMessage(Message msg) {
pd.dismiss();
info.setText(info_datas);
}
};


}


---------------------------FetchData.java--------------------------------


package com.example.running;


import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.util.Log;


public class FetchData {
private static StringBuffer buffer;



// fetch_process_info
public static String fetch_process_info() {
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;
}
//RunningServicesInfo
public static String getRunningServicesInfo(Context context) {
StringBuffer serviceInfo = new StringBuffer();
final ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> services = activityManager.getRunningServices(100);


Iterator<RunningServiceInfo> 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("\nclientCount: ").append(si.clientCount);
serviceInfo.append("\nactiveSince: ").append(FetchData.formatData(si.activeSince));
serviceInfo.append("\nlastActivityTime: ").append(FetchData.formatData(si.lastActivityTime));
serviceInfo.append("\n\n");
}
return serviceInfo.toString();
}

//RunningServicesInfo
public static String getRunningTasksInfo(Context context) {
StringBuffer sInfo = new StringBuffer();
final ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = activityManager.getRunningTasks(100);
Iterator<RunningTaskInfo> 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.numActivities);
sInfo.append("\nnumRunning: ").append(ti.numRunning);
sInfo.append("\ndescription: ").append(ti.description);
sInfo.append("\n\n");
}
return sInfo.toString();
}

 
// formart data long to string
public static String formatData(long data) {
Date d = new Date(data);
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = format2.format(d);
return str;
}


}


------------------------CMDExecute.java--------------------------


package com.example.running;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;


public class CMDExecute {


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


try {
ProcessBuilder builder = new ProcessBuilder(cmd);
// set working directory
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) != -1) {
System.out.println(new String(re));
result = result + new String(re);
}
in.close();


} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}

。。。。。。。。。main.xml。。。。。。。。。。。。。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">


<ListView 
   android:layout_width="fill_parent"
android:layout_height="fill_parent" 
android:id="@+id/itemlist" />
 
</LinearLayout>


。。。。。。。。。。。。info_row.xml。。。。。。。。。。。。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/vw1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="4px"
    android:orientation="horizontal">    
   <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">


        <TextView android:id="@+id/name"
            android:textSize="18sp"
            android:textStyle="bold"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>


        <TextView android:id="@+id/desc"
            android:textSize="14sp"
            android:layout_width="fill_parent"
            android:paddingLeft="20px"
            android:layout_height="wrap_content"/>


    </LinearLayout>


</LinearLayout>


。。。。。。。。。showinfo.xml。。。。。。。。。。。。。

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" 
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="20px"
>


<TextView android:id="@+id/title" 
android:layout_width="fill_parent"
android:layout_height="wrap_content" 
android:textSize="20sp" 
android:paddingBottom="8dip"
android:text="" />

<TextView android:id="@+id/info" 
android:layout_width="fill_parent"
android:layout_height="wrap_content" 
android:text="" />

</LinearLayout>
</ScrollView>


、、、、、、、、、权限、因为要获取运行任务,所以加以下这条权限、、、、

<uses-permission android:name="android.permission.GET_TASKS"></uses-permission>


27、获取运行时信息(包括运行时的service、运作任务、正在运行的进程信息)

27、获取运行时信息(包括运行时的service、运作任务、正在运行的进程信息)

27、获取运行时信息(包括运行时的service、运作任务、正在运行的进程信息)

27、获取运行时信息(包括运行时的service、运作任务、正在运行的进程信息)