[範例情境]
1.Android缺少工作管理員,無法得知背景有哪些程式正在執行
2.請撰寫可捕捉系統執行工作(Task)&服務(Service)資訊的程式
[情境分析]
1.1個Activity
2.1個Layout
SETP 1:新建專案
SETP 2:修改AndroidMainfest.xml
SETP 3:配置Layout
﹡主畫面main.xml之配置
1. 加入Button,之後會透過觸發Click event取得系統執行之工作與服務
2. 加入2個ListView,之後會用來分別呈現取得之執行工作、執行服務資訊
﹡用來裝載ListView之piggy_simple_list_item.xml配置
1. 有別於前面的配置UI,這裡是描述ListView的外觀
ps:若懶得新增piggy_simple_list_item.xml,也可使用Android預設之ListView樣式,在SETP 4撰寫程式碼時,指向android.R.layout.simple_list_item_1即可
SETP 4:撰寫程式碼
package com.example.android.homework8;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Homework8 extends Activity {
private Button bt1;
private ListView mListView01;
private ListView mListView02;
private ArrayAdapter aryAdapter1,aryAdapter2;
/*Task*/
private ArrayListarylistService;
private int intGetTaskServiceCounter=30;
public List mRunningTasks;
private ActivityManager mActivityManager;
/*Service*/
private ArrayListarylistTask;
private int intGetTaskCounter=30;
public List mRunningTaskServices;
//private ActivityManager mActivityManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt1 = (Button)findViewById(R.id.Button01);
mListView01 = (ListView)findViewById(R.id.ListView01);
mListView02 = (ListView)findViewById(R.id.ListView02);
bt1.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
mActivityManager = (ActivityManager)Homework8.this.getSystemService(ACTIVITY_SERVICE);//取得工作和服務都用同一個ActivityManager
/*取得執行工作資訊*/
arylistTask = new ArrayList();
mRunningTasks = mActivityManager.getRunningTasks(intGetTaskCounter);
int i = 1;
/* 以迴圈及baseActivity方式取得工作名稱與ID */
for (ActivityManager.RunningTaskInfo amTask : mRunningTasks)
arylistTask.add("" + (i++) + ": "+ amTask.baseActivity.getClassName() + "(ID=" + amTask.id +")");
aryAdapter1 = new ArrayAdapter(Homework8.this, R.layout.piggy_simple_list_item, arylistTask);
mListView01.setAdapter(aryAdapter1);
/*取得執行服務資訊*/
arylistService = new ArrayList();
mRunningTaskServices = mActivityManager.getRunningServices(intGetTaskServiceCounter);
int j = 1;
/* 以迴圈及RunningServiceInfo物件取得服務名稱與ID */
for (RunningServiceInfo amTask : mRunningTaskServices)
arylistService.add("" + (j++) + ": "+ amTask.process + "(ID=" + amTask.pid +")");
aryAdapter2 = new ArrayAdapter(Homework8.this, R.layout.piggy_simple_list_item, arylistService);
mListView02.setAdapter(aryAdapter2); }
});
}
}
SETP 5:執行
初始畫面 |
成功執行之畫面 |