我的问题是我在线程中运行一个方法,30秒后我将显示alertdialog并单击alertdialog的确定按钮我将停止当前线程但问题是线程没有停止,以下是我的代码并抱歉英语不良通信
public class CountDownTimerActivity extends Activity implements Runnable {
Thread t;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Thread(this);
t.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
myTimer.start();
mDeclaration();
myTimer.cancel();
}
private CountDownTimer myTimer = new CountDownTimer(30000, 1000) {
// This will give you 30 sec timer with each tick at 1 second
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
t.interrupt();
//t.stop();
AlertDialog.Builder alert = new AlertDialog.Builder(
CountDownTimerActivity.this);
alert.setMessage("Loading...");
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
};
public void mDeclaration() {
for (int i = 0; i < 100000; i++) {
System.out.println("Printing OK" + i);
}
}
}
答案 0 :(得分:0)
请参阅此question ...而是可以在run方法中放置一个标志..并检查是否运行以在线程中运行代码。
答案 1 :(得分:0)
试试这个: -
public class CountDownTimerActivity extends Activity implements Runnable {
Thread t;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Thread(this);
t.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
myTimer.start();
mDeclaration();
myTimer.cancel();
}
private CountDownTimer myTimer = new CountDownTimer(30000, 1000) {
// This will give you 30 sec timer with each tick at 1 second
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
AlertDialog.Builder alert = new AlertDialog.Builder(
CountDownTimerActivity.this);
alert.setMessage("Loading...");
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// t.interrupt();
t.stop();
}
});
alert.show();
}
};
public void mDeclaration() {
for (int i = 0; i < 100000; i++) {
System.out.println("Printing OK" + i);
}
}
}