andrew
andrew

Reputation: 183

How to stop while loop after back button is hit

I have tried so many ways of solving my problem, but still no success.I have a method, which returns me a string value and I am using it to update TextView on my screen like this: outCPU.setText(getCpuInfo());

Which would be fine, but I need to update this TextView until back button was pressed.

I guess i have need a while loop which starts after activity has been created and stops after back button was pressed. This loop should be in a new thread, because:- I have to load the activity first and execute the loop in another thread so the executing won't affect main thread and loading of the activity.

As I've already said, I don't know how to do this properly even though i have spent few hours on it.

Could someone show me an example how to get this done? Thanks...!!

EDITED - WORKING:

private Handler mHandler;
private int i;


@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_systeminfo);

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

    i = 0;
    mHandler = new Handler();
    mHandler.post(mUpdate);

}


private Runnable mUpdate = new Runnable() {
    @Override
    public void run() {
        outCPU.setText(getCpuInfo());
        outMEM.setText(getMemInfo());
        outTASKS.setText(getTasksInfo());
        i++;
        mHandler.postDelayed(this, 1000);
    }
};

@Override
public void onBackPressed() {

    mHandler.removeCallbacks(mUpdate);
    super.onBackPressed();
    Log.i("MSG", "Going back");

    finish();

}

Upvotes: 2

Views: 814

Answers (2)

Sharp Edge
Sharp Edge

Reputation: 4192

You can use AsyncTask to perform operations on UI Thread while being in a Thread. Or you can use 'my favorite' , the combination of Thread and Handler. To make sure the thread is stopped when back is pressed, you can use handler.removeCallBacks(Runnable) The following example could solve your problem:

//Global
Handler h = new Handler();

private static boolean flag = true;

public void updateTextView(){

 // call thread here
 h.post(thread);
}


  // take this thread out side so that it can be stopped with handler
 Thread thread = new Thread(){

 public void run(){

      while(flag)
      outCPU.setText(getCpuInfo());

    }

 }

public void onBackPressed(){

    flag = false;
    h.removeCallBacks(thread);
    super.onBackPressed();

}

Upvotes: 3

Alex Salauyou
Alex Salauyou

Reputation: 14348

Use a shared flag somewhere in your app:

private volatile boolean wasPressed = false;

In while loop, check this flag:

while (!wasPressed) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            outCPU.setText(getCpuInfo()); 
        }
    });
    // sleep for a while
}

On button click listener, switch wasPressed to true.

Upvotes: 0

Related Questions