简体   繁体   English

通过AsyncTask在Android中执行循环方法 - Android?

[英]Executing a method in loop via AsyncTask - Android?

I am kinda noob in programming, but I am here to ask you for an advice. 我在编程方面有点像菜鸟,但我在这里向你征求意见。 I am making an app, which serves you an system informations like CPU load, RAM, etc.. I've got all I need, and it works! 我正在制作一个应用程序,为您提供系统信息,如CPU负载,RAM等。我已经得到了所有我需要的,它的工作原理! But there is a problem when I push button which starts new activity in which I can see the system info, also in that activity I run a method getSystemInfo() in onCreate() method which gets me all the information I need and this takes some time until it is done which means a black screen and the user has to wait.. 但是当我按下按钮开始我可以看到系统信息的新活动时会出现问题,同样在该活动中我在onCreate()方法中运行方法getSystemInfo() ,它获取了我需要的所有信息,这需要一些直到它完成的时间,这意味着黑屏,用户必须等待..

I'd like to start and load the activity before executing getSystemInfo() method which should be running in background in a loop until the user's pressed goBack button. 我想在执行getSystemInfo()方法之前启动并加载活动,该方法应该在循环中在后台运行,直到用户按下goBack按钮。

I've seen this: How to use AsyncTask correctly in Android but it is still too difficult for me to do. 我已经看到了这个: 如何在Android中正确使用AsyncTask,但对我来说仍然太难了。

Any help would be apreciated. 任何帮助都会被贬低。 Thank you a million times! 谢谢你一百万次!

My code here: 我的代码在这里:

public class SystemInfoActivity extends Activity{

TextView outCPU;
TextView outMEM;
TextView outTASKS;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_systeminfo);
    Log.d("MSG:", "running");

    outCPU = (TextView) findViewById(R.id.outCPU);
    outMEM = (TextView) findViewById(R.id.outMEM);
    outTASKS = (TextView) findViewById(R.id.outTASKS);

    getSystemInfo();

}

protected void getSystemInfo() {

    //**********CPU********
    RunCommandTOP top = new RunCommandTOP();
    int[] cpuUsage = top.CommandTOP();

    int user = cpuUsage[0];
    int system = cpuUsage[1];
    int total = (system + user);
    outCPU.setText("CPU usage: " + user + "% user, " + system + "% system, " + total + "% total");


    //**********RAM********
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(memoryInfo);
    long availibleMB = memoryInfo.availMem / 1048576L;
    long totalMB = memoryInfo.totalMem / 1048576L;
    long usedMB = totalMB - availibleMB;

    outMEM.setText("RAM usage: " + usedMB + "/" + totalMB + "MB");

    //**********TASKS********
    RunCommandPS ps = new RunCommandPS();
    String commandLines = ps.CommandPS();

    int NumberLines = countTasks(commandLines);
    int Tasks = NumberLines - 1;

    outTASKS.setText("Tasks: " + Tasks);

}

private static int countTasks(String str) {
    String[] lines = str.split("\r\n|\r|\n");
    return lines.length;
}

public void onBackPressed() {
    Log.i("MSG", "Going back");
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
    finish();
    //return true;
}
}

It's easy to use man. 这很容易使用男人。

just call in onCreate method next line new Async().execute(); 只需调用onCreate方法下一行新的Async()。execute();

but set Text and update UI in onPostExecute, you can return some params in doInBackground method and get them in onPostExecute 但是在onPostExecute中设置Text和update UI,你可以在doInBackground方法中返回一些params并在onPostExecute中获取它们

private class Async extends AsyncTask<Void, Void, String> {

   @Override
   protected String doInBackground(Void... params) {
       String myParamsForUi = getSystemInfo();
       return myParamsForUi;
   }

   @Override
   protected void onPostExecute(String result) {
       super.onPostExecute(result);

       outTASKS.setText("Tasks: " + result);

   }

}

put the code that needs to be asynchronous in the AsyncTask class. 将需要异步的代码放在AsyncTask类中。

More information how to do this here 更多信息如何在此处执行此操作

Basically what you will do is extend AsyncTask in your custom class. 基本上你要做的是在你的自定义类中扩展AsyncTask。

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

In the do in background method you will put the work you need to be done, and in postexecute you will have what happens after it finishes. 在do in background方法中,您将完成您需要完成的工作,而在postexecute中,您将完成它完成后会发生的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM