我已经在谷歌和这里搜索了几个小时。我一直找不到解决问题的方法。我希望线程在用户按下后退按钮时停止。因此,例如,用户将按下后退按钮,循环将停止抛硬币。然后, TextView 将填充在用户取消操作之前循环设法完成的正面和反面的数量。
我知道我必须设置
dialog.setCancelable(false);
到
dialog.setCancelable(true);
我需要实现
progressDialog.setOnCancelListener(new OnCancelListener(){
public void onCancel(DialogInterface dialog) {
background.setRunning(false);
}});
但是当我尝试这样做时,它最终会杀死我的整个应用程序并强制关闭它。 你能帮忙吗?我仍然是 Android 编程的新手,我渴望了解更多,所以如果您注意到代码中的任何其他内容我可以改进它,我们将不胜感激。
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);
}
}
};
}
最佳答案
我很好奇你的代码是如何编译的,因为 setRunning(boolean)
不是 Thread
的 api 的一部分。
无论如何,这里有一种方法可以干净地退出线程。将您的后台线程定义更改为:
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());
}
}
}
然后取消你的线程:
background.interrupt();
关于android - 在 Android 应用程序中停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9595603/