我为某个进程创建了一个线程,并且我同时使用Progress Dialog运行此线程。当进程完成时,进度对话框将被解雇。直到这个没有问题但是当用户按下电话按钮两次时,活动将会破坏,我的过程应该停止。所以我在onDestroy()中停止了线程。但是应用程序崩溃在mt.stop()
我的代码,错误日志如下所示。请给我任何解决方案,如果可能的话,我想要理由。
使用flag,process将仅在每次迭代开始时检查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();
}
log cat中的错误;
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)
答案 0 :(得分:0)
请参考我的解决方案: android kill specific thread on action bar event
使用TimerTask而不是线程的解决方案可以更好地为您的应用程序提供服务并进行更优化。
即使取消也可以。)
P.S:它还提供了为什么stop
不适合你的信息。