我已经为某个进程创建了一个线程,并且我正在使用 Progress Dialog 同时运行这个线程。进程完成后,进度对话框将关闭。直到这没有问题,但是当用户按下手机的后退按钮两次时,活动将被破坏,我的进程应该停止。所以我已经停止了 onDestroy() 中的线程。但是应用程序在我的代码中崩溃mt.stop()
并且错误日志如下所示。请给我任何解决方案,如果可能的话,我想要这背后的原因。使用标志,进程将仅在每次迭代开始时检查是否停止。我想显着地停止进程。
代码
Button b;
ProgressDialog pd = null;
MyThread mt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.btn_start);
b.setOnClickListener(this);
}
public void onClick(View v) {
pd = ProgressDialog.show(this, "one", "two", true, true);
mt = new MyThread();
mt.start();
}
class MyThread extends Thread {
@Override
public void run() {
// assume this loop is my process.
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("log_tag", "" + i);
}
Log.v("log_tag", "process COmplited");
pd.dismiss();
super.run();
}
}
@Override
protected void onDestroy() {
Log.v("log_tag", "OnDestroy");
pd.dismiss();
mt.stop();
super.onDestroy();
}
日志猫错误;
11-09 17:26:45.313: E/global(594): Deprecated Thread methods are not supported.
11-09 17:26:45.313: E/global(594): java.lang.UnsupportedOperationException
11-09 17:26:45.313: E/global(594): at java.lang.VMThread.stop(VMThread.java:85)
11-09 17:26:45.313: E/global(594): at java.lang.Thread.stop(Thread.java:1379)
11-09 17:26:45.313: E/global(594): at java.lang.Thread.stop(Thread.java:1344)
11-09 17:26:45.313: E/global(594): at com.example.threaddemo.MainActivity.onDestroy(MainActivity.java:53)
11-09 17:26:45.313: E/global(594): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3642)
11-09 17:26:45.313: E/global(594): at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3673)
11-09 17:26:45.313: E/global(594): at android.app.ActivityThread.access$2900(ActivityThread.java:125)
11-09 17:26:45.313: E/global(594): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
11-09 17:26:45.313: E/global(594): at android.os.Handler.dispatchMessage(Handler.java:99)
11-09 17:26:45.313: E/global(594): at android.os.Looper.loop(Looper.java:123)
11-09 17:26:45.313: E/global(594): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-09 17:26:45.313: E/global(594): at java.lang.reflect.Method.invokeNative(Native Method)
11-09 17:26:45.313: E/global(594): at java.lang.reflect.Method.invoke(Method.java:521)
11-09 17:26:45.313: E/global(594): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-09 17:26:45.313: E/global(594): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-09 17:26:45.313: E/global(594): at dalvik.system.NativeStart.main(Native Method)