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

标签 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 中列出所有正在运行的进程?

非常感谢

最佳答案

您不能转换 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]);

关于android - 如何将 Object[] 转换为 String[ ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28769120/

相关文章:

android - 如何在呈现 SplashScreen 期间运行 MainActivity

android - CheckBox inside a View inside 一个 ListView

java - Android - 我如何检测 Android 将进入屏幕锁定模式,我需要在该阶段完成一项工作

android - LibGDX 错误 : Program type already present

java - 更改 R.java 文件内容

android - 为什么我不能在我的 ListFragment 中使用 setListShown?或者如何在从异步任务加载列表时显示进度指示器?

Listview 上的 Android 子项

Android:在 ListView 的 onItemClick 事件中使用 AlertDialog

Android ListView 选择器颜色

android - Android Studio 上的 Google+ 登录 - GoogleAuthException : BadUsername