Android中断线程的处理方法
本文实例讲述了Android中断线程的处理方法。分享给大家供大家参考。具体方法如下:
我现在对一个用户注册的功能
1.用ProgressDialog将当前页面设成不可操作(保留返回键退出ProgressDialog)
2.用一个线程clientThread执行数据的提交和返回
问题:考虑到ProgressDialog运行过程中,返回键的操作,应该终止clientThread的运行。
代码如下,感兴趣的朋友可以参考运行一下,以便得出更好的解决办法。
btn_register.setOnClickListener(newView.OnClickListener(){ @Override publicvoidonClick(Viewv){ //TODOAuto-generatedmethodstub if(doBeforeSubmit()){ try{ Log.v(TAG,"clientThreadprepare01。。。:"+Thread.interrupted()); clienThread=newThread(){ publicvoidrun(){ try{ Log.v(TAG,"clientThreadprepare02。。。:"+Thread.interrupted()); while(!Thread.interrupted()){ Log.v(TAG,"clientThreadstarting。。。"); MeApiCallmeApiCall=newMeApiCallImpl(); Meme=newMe(); me.setMeEmail(et_register_account.getText().toString().trim()); me.setMePwd(et_register_pwd.getText().toString().trim()); me.setMeName(et_register_nickName.getText().toString().trim()); Log.v(TAG,"clientThreaddataloaded。。。"); meApiCall.register(me); Log.v(TAG,"clientThreadcallback。。。"); handler.sendEmptyMessage(AppConfig.Register.SUCCESS_MSG); clienThread.interrupt(); //中断线程 } }catch(InterruptedExceptione){ //TODO:handleexception Log.v(TAG,"clientThreadisinterrupt"); }catch(Exceptione){ //TODOAuto-generatedcatchblock Log.v(TAG,"exception:"+e.getMessage()); handler.sendEmptyMessage(AppConfig.Register.FAIL_OTHER_MSG); e.printStackTrace(); } }; }; Log.v(TAG,"progressDialogprepare01。。。:"); progressDialog=ProgressDialog.show(Register.this, "", "正在获取....", true, true, newDialogInterface.OnCancelListener(){ @Override publicvoidonCancel(DialogInterfacedialog){ //TODOAuto-generatedmethodstub try{ clienThread.interrupt(); Log.v(TAG,"interruptissuccess!"); }catch(Exceptione){ //TODOAuto-generatedcatchblock Log.v(TAG,"interruptisfail!"); e.printStackTrace(); } } } ); Log.v(TAG,"clientThreadprepareing_end。。。"); clienThread.start(); //Log.v(TAG,"clientThreadprepareing_end。。。"); }catch(Exceptione){ //TODOAuto-generatedcatchblock Log.v(TAG,e.getMessage()+"00"); e.printStackTrace(); } } } });
希望本文所述对大家的Android程序设计有所帮助。