【问题标题】:How to use AsyncTask to retrieve RAM consumption in realtime如何使用 AsyncTask 实时检索 RAM 消耗
【发布时间】:2018-06-25 05:34:25
【问题描述】:

我有一段代码要循环运行,以便将实时数据从中获取到我的片段中。

我如何使用AsyncTask 实时获取 RAM 消耗,因为我不想让我的 UI 线程为此忙碌。

ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
ActivityManager activityManager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
activityManager.getMemoryInfo(memInfo);
String TotalRam = String.valueOf(memInfo.totalMem);
int totaLram = Integer.parseInt(TotalRam);
String freeRam = String.valueOf(memInfo.availMem);
int freRAm = Integer.parseInt(freeRam);

【问题讨论】:

  • 如果我将它运行到一个循环中以实时获取数据,它将阻塞 UI 线程,这就是为什么我想使用 AsyncTask 但我对此很陌生并且之前从未使用过它需要一些指南来制作它完成

标签: java android performance android-fragments


【解决方案1】:

首先将您的 RAM 代码包装到一个方法中。

 int getRam(){

    ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
    ActivityManager activityManager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
    activityManager.getMemoryInfo(memInfo);
    String TotalRam = String.valueOf(memInfo.totalMem);
    int totaLram = Integer.parseInt(TotalRam);
    String freeRam = String.valueOf(memInfo.availMem);
    return  Integer.parseInt(freeRam);

}

接下来为您的自定义 asyncTask 创建一个内部类。您可以在 doInBackground() 中使用 for 循环,然后定期调用 onProgressUpdate() 方法。

public class AsyncRamInfo extends AsyncTask<Void, Integer, Void>{


 @Override
    protected Void doInBackground(Void... voids) {

        try {
            for (; ; ) { //loop forever
                onProgressUpdate(getRam());
                Thread.sleep(5000);
            }
        } catch (InterruptedException e) {
             return null;    
        } 
    }

    @Override
    protected void onProgressUpdate(Integer... values) {

        Integer ram = values[0];
        //display the ram on the UI thread.
        textViewRam.setText(" RAM = "+ ram);
    }
}

【讨论】:

  • 感谢您的回复...应用程序在几秒钟后崩溃了。原因:android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸它的视图。
  • @andi,有两件事需要注意。 1) 这个 asyncTask 应该在 Fragment 类中执行,而不是从另一个线程执行;2) doInBackground() 方法不应该更新任何视图。您可以使用新代码更新您的问题,以便我们更好地理解问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多