如何在android中使用getRunningAppProcesses()?

时间:2012-12-09 22:41:48

标签: android android-activity

我有以下代码:

package com.example.task;

import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainTask extends Activity {

private Button BprocessesShow;
private TextView processesShow;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_task);

    ActivityManager manager =       (ActivityManager)getSystemService(ACTIVITY_SERVICE);
     final List<ActivityManager.RunningAppProcessInfo> runningProcesses = manager.getRunningAppProcesses();


    BprocessesShow=(Button) this.findViewById(R.id.BshowProcesses);
    processesShow=(TextView) this.findViewById(R.id.showProcesses);     


    BprocessesShow.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {


            processesShow.setText((CharSequence) runningProcesses);
        }
    });

}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main_task, menu);
    return true;
}

}

我想要做的就是,当用户按下按钮时,我想向他/她显示他手机上的所有正在运行的进程......当我在我的手机上运行此应用程序时该应用程序崩溃和所有我得到的是一条消息不幸的是,任务(这是我的名字的应用程序)已经停止...任何帮助都会非常有用!!

1 个答案:

答案 0 :(得分:1)

在这一行

processesShow.setText((CharSequence) runningProcesses);

您正在将List转换为CharSequence。尝试以下几点:

StringBuilder b = new StringBuilder();
for (ActivityManager.RunningAppProcessInfo process: runningProcesses) {
    b.append(processs.processName);
    b.append("\n");
}
processesShow.setText(b.toString());