我想玩進度條。當我調用Progress(N)時,我有這個(下面)簡單的活動,一個接一個地運行一個進度條N次。它工作的很好,但是我面臨的問題是,如果我按回按鈕。我進入mainActivity,但進度條(線程)仍然依次在後臺運行。只要他們完成了N個循環,意圖就會被調用,我所做的任何事情都會被這個LOOP_OVER活動中斷。殺死所有線程後退出活動android
我試着自己解決這個問題。我嘗試使用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!
}
}
我對我感覺很糟糕。我想不出這種方法。其實我並沒有試圖在這方面認真思考。偉大的思想btw。有效。 :) PS:我編輯了答案,接受編輯,以便我可以接受答案。 – impossible