1

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! 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..

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.

I've seen this: How to use AsyncTask correctly in Android but it is still too difficult for me to do.

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;
}
}
Community
  • 1
  • 1
andrew
  • 183
  • 1
  • 2
  • 12
  • what issues are you having using asynctask ? This is the simpler way of handling async tasks because you could use services but in my opinion this is a bit more complicated. – Eddie Martinez May 05 '15 at 14:25
  • 5 mins you need to understand it http://developer.android.com/reference/android/os/AsyncTask.html – Andrew V. May 05 '15 at 14:33

2 Answers2

3

It's easy to use man.

just call in onCreate method next line new Async().execute();

but set Text and update UI in onPostExecute, you can return some params in doInBackground method and get them in 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);

   }

}
Andrew V.
  • 146
  • 1
  • 7
  • ok, but it has problem with type of doInBackground method... String would be nice, but it wants me to change it to void, is there any way how to solve this? – andrew May 05 '15 at 14:59
0

put the code that needs to be asynchronous in the AsyncTask class.

More information how to do this here

Basically what you will do is extend AsyncTask in your custom class.

 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.

Eddie Martinez
  • 13,582
  • 13
  • 81
  • 106
  • Yes, I got it, but I don't know, how the types of methods work in AsyncTask. I would like to have protected String doInBackground() but it doesn't want to let me do that.. Could you tell how should that method look like? – andrew May 05 '15 at 16:47
  • the thing is whatever you return in do in background is the type thatof hte paremeter in the post execute method. It's a bit confusing but you see in my example how you return totalSize a long, and that is the paremeter in the postexecute ? – Eddie Martinez May 05 '15 at 19:18