我有一段代码,我想在循环中运行,以便我可以从中获取实时数据到我的 fragment 中。
如何使用 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);
最佳答案
首先将您的 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);
}
}
关于java - 如何使用 AsyncTask 实时检索 RAM 消耗情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51016855/