Stop Stream in Android App

I've searched for hours on Google and here. I could not find a solution to my problem. I want the thread to stop when the user clicks the back button. So, for example, the user clicks the back button and the cycle stops flipping coins. The text boxes will then be populated with the number of heads and tails that the loop completed before the user canceled the operation.

I know what I need to install

dialog.setCancelable(false);

      

to

dialog.setCancelable(true);

      

and what i need to implement

progressDialog.setOnCancelListener(new OnCancelListener(){

  public void onCancel(DialogInterface dialog) {

   background.setRunning(false);

  }});

      

But when I try to do it, it ends up killing all my application force closing it. You can help. I am still new to android programming and I really want to know more, if you notice any other things in the code that I can improve it would be appreciated.

package com.michaelpeerman.probability;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;

public class ProbabilityActivity extends Activity implements OnClickListener {

    private Button submit;
    ProgressDialog dialog;
    int increment;
    Thread background;
    int heads = 0;
    int tails = 0;

    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.main);
        submit = ((Button) findViewById(R.id.submit));
        submit.setOnClickListener(this);
    }

    public void onClick(View view) {
        increment = 1;
        dialog = new ProgressDialog(this);
        dialog.setCancelable(false);
        dialog.setMessage("Flipping Coin...");
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setProgress(0);
        EditText max = (EditText) findViewById(R.id.number);
        int maximum = Integer.parseInt(max.getText().toString());
        dialog.setMax(maximum);
        dialog.show();
        background = new Thread(new Runnable() {
            public void run() {
                for (int j = 0; j < dialog.getMax(); j++) {
                    int i = 1 + new Random().nextInt(2);
                    if (i == 1)
                        heads++;
                    if (i == 2)
                        tails++;
                progressHandler.sendMessage(progressHandler.obtainMessage());
            }
        }
    });
    background.start();
}

Handler progressHandler = new Handler() {
    public void handleMessage(Message msg) {

        dialog.incrementProgressBy(increment);
        if (dialog.getProgress() == dialog.getMax()) {
            dialog.dismiss();
            TextView result = (TextView) findViewById(R.id.result);
            result.setText("heads : " + heads + "\ntails : " + tails);

        }
    }

};

}

      

+2


source to share


3 answers


I am curious how your code compiles as setRunning(boolean)

it is not part of the api for Thread

.

Regardless, here's one way to get out of the stream cleanly. Change your background thread definition to this:

background = new Thread(new Runnable() {
    public void run() {
        for (int j = 0; !Thread.interrupted() && j < dialog.getMax(); j++) {
            int i = 1 + new Random().nextInt(2);
            if (i == 1)
                heads++;
            if (i == 2)
                tails++;
            progressHandler.sendMessage(progressHandler.obtainMessage());
        }
    }
}

      



Then cancel your stream:

background.interrupt();

      

+5


source


You shouldn't be forced to close threads in your application. This kind of flow control is usually a bad idea and generally completely unnecessary with the niceties that Android framework provides you. Instead, you should use AsyncTask, which will update the UI (this also precludes the use of this Messenger, which, although pretty simple in this example, can get a lot more annoying!). Using AsyncTask, you can do whatever work you need in the background and update the interface at the same time. You can read about all of this in a painless Android thread tutorial .



+1


source


To stop a thread, you have to use Thread.interrupt () method, it does not stop the thread right away, but it notifies the android system that this particular thread needs to be stopped, android os interrupts this thread when it comes up to stop the thread.

+1


source







All Articles