如何将Object []转换为String []

时间:2015-02-27 15:54:00

标签: android android-listview

为了列出listview中所有正在运行的应用程序,我需要将一个对象数组转换为一个字符串数组。

使用此代码,我会读出所有正在运行的进程:

 private String[] runningProcesses() {
    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List l = am.getRunningAppProcesses();
    Iterator i = l.iterator();
    PackageManager pm = this.getPackageManager();
    while (i.hasNext()) {
        ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
        try {
            c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
            Log.w("LABEL", c.toString());



        } catch (Exception e) {
            //Name Not FOund Exception
        }
    }


    Object[] object = l.toArray();

如何将object转换为string[]以列出listView中所有正在运行的进程?

非常感谢

1 个答案:

答案 0 :(得分:3)

您无法直接将List<RunningAppProcessInfo>转换为String[]。而是将标签(您正在记录)存储到单独的List中,并在返回时将其转换为数组。

List<String> labels = new ArrayList<String>();

while (i.hasNext()) {
    ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
    try {
        c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
        Log.w("LABEL", c.toString());
        labels.add(c.toString());
    } catch (Exception e) {
        //Name Not FOund Exception
    }
}

// convert to array and return
return labels.toArray(new String[0]);