Android开发之ProgressDialog在独立Thread线程中更新进度
简单的需求:在一个工作Thread中更新进度对话框ProgressDialog
遇到的问题:
1,创建需要Context,这个需要传进来
2,Thread中不能创建ProgressDialog,否则需要创建Looper
3,直接在Thread中更新ProgressDialog不行,扔例外,不是创建Thread的View不允许更新
4,Thread外创建Handler,然后现成里Post,更本不会更新。
解决方案:
1,创建ProgressDialog,同时创建Handler,用Callback handleMessage更新对话框
2,Thread中调用sendMessage之后,还需要调用Thread.yield()或Thread.sleep(),否则同样不更新。
示例代码:
final ProgressDialog pgDlg=new ProgressDialog(mContext); pgDlg.setTitle("Testing ...");pgDlg.setMessage(" "); pgDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pgDlg.setIndeterminate(false); pgDlg.setMax(100);pgDlg.setProgress(0); pgDlg.setIcon(android.R.drawable.ic_menu_search); final Handler dlgHandler=new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { String s = (String)msg.obj; pgDlg.setMessage(s); if(msg.what>=100){ pgDlg.setProgress(100); new Handler().postDelayed(new Runnable() { @Override public void run() { pgDlg.dismiss(); } },1000); }else{ pgDlg.setProgress(msg.what); } return true; } }); pgDlg.show(); new Thread(new Runnable() { @Override public void run() { BluetoothGattCharacteristic ctc=bleHelper.getCharacteristic(SampleGattAttributes.SERVICE_KeyService,SampleGattAttributes.CHARACTERISTIC_KeyCharacteristic); for (int i=0;i<cmdsToTest.length;i++){ String cmd = cmdsToTest[i]; final String msg=String.format("command>:%s", cmd); AppUtils.logD(msg); ObdCommand oc = new ObdCommand(cmd, cmd); final ObdCommandJob job = new ObdCommandJob(oc); CommandExecutor executor = new BleCommandExecutor(bleHelper,ctc, job) .setLocker(mJobLock, mJobCondition); try { mJobLock.lock(); new Thread(executor).start(); mJobCondition.await(5, TimeUnit.SECONDS); } catch (InterruptedException ex) { Log.e("", ex.getMessage()); job.setState(ObdCommandJobState.EXECUTION_ERROR); } finally { mJobLock.unlock(); bleHelper.resumeIO(); } if (job.getState() != ObdCommandJobState.FINISHED) { errorMsg = String.format("test command %s failed!", job.getCommand().getCommand()); if (resultListener != null) { resultListener.onTestDone(false, errorMsg); Message.obtain(dlgHandler,100,errorMsg).sendToTarget(); Thread.yield();
break; } } final int progress = i*100/cmdsToTest.length; Message.obtain(dlgHandler,progress,msg+"\nresult>:"+job.getCommand().getRawData()).sendToTarget(); //pgDlg.setMessage(msg); throw exception when access direct here //pgDlg.incrementProgressBy(progress ); Thread.yield();//must yield to let message processed } if (resultListener != null) { resultListener.onTestDone(true, ""); Message.obtain(dlgHandler,100,"done").sendToTarget(); Thread.yield(); } bleHelper.close(); } }).start();