gpt4 book ai didi

java - 杀死所有线程后退出 Activity android

转载 作者:行者123 更新时间:2023-12-01 09:43:42 25 4
gpt4 key购买 nike

我正在尝试玩进度条。我有一个(如下)简单的 Activity ,当我调用 Progress(N) 时,它会一个接一个地运行进度条 N 次。它工作得很好,但我面临的问题是,如果我按后退按钮。我进入了 mainActivity,但进度条(线程)仍然在后台一个接一个地运行。一旦它们完成 N 个循环, Intent 就会被调用,而我要做的任何事情都会被这个 LOOP_OVER Activity 打断。

我尝试自己解决这个问题。我尝试使用 Thread 类的变量(在我直接这样做之前)。并尝试在 onDestroy() 甚至在调用 Intent 之前中断它,但它没有帮助。我该怎么办?

public class Loop extends Activity {

private ProgressBar progressBar;
private CircleProgress circleProgress;
private int progressStatus = 0;
private Handler handler = new Handler();

private TextView myView;
private int started = 0, doneLoop=0;
private Thread th;


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loop);

progressBar = (ProgressBar) findViewById(R.id.progressBar1);
circleProgress = (CircleProgress) findViewById(R.id.circle_progress);

myView = (TextView) findViewById(R.id.instruction);

progressBar.setScaleY(3f);
// Start long running operation in a background thread

Progress(3);

}

@Override
public void onDestroy() {
// Below, everything I am just
th.interrupt();
Loop.this.finish();
Thread.currentThread().interrupt();
super.onDestroy();
}

public void Progress(final int numberOfRuns){
// QueView.setText(Que);
if(numberOfRuns == 0){
th.interrupt();
Intent myIntent = new Intent(Loop.this, LOOP_OVER.class);
startActivity(myIntent);
super.onDestroy();
finish();
}
th = new Thread(new Runnable() {
public void run() {
genNextSet();
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
//current value in the text view
handler.post(new Runnable() {
public void run() {
circleProgress.setProgress(progressStatus);
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub

myView.setText(Que);
}
});
// Sleep for 200 milliseconds.
//Just to display the progress slowly
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
progressStatus = 0;

Progress(numberOfRuns - 1);
}
});

th.start();
}


private void genNextSet() {
// so some cool here!
}
}

最佳答案

您可以想象一个在所有线程之间共享的类变量。

尝试添加如下内容:

private Boolean LOOP = true;

然后

while (progressStatus < 100 && LOOP) {

@Override
public void onBackPressed() {
LOOP = false
}

还有

if(LOOP == true){
// call intent
}
finish();

关于java - 杀死所有线程后退出 Activity android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38243616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com