开发中如果涉及到了比较耗时的工作,之前做法是利用ProgressDialog做界面有好提示,新开现成做耗时操作,最后用Handler做UI线程的修改。界面如下:
oncreate方法: [li]public void onCreate(Bundle savedInstanceState) {[/li][li] super.onCreate(savedInstanceState);[/li][li] setContentView(R.layout.main);[/li][li][/li][li] progressDialog = new ProgressDialog(MainActivity.this);[/li][li] progressDialog.setMessage("Loading…");[/li][li] progressDialog.show();[/li][li][/li][li] new Thread(new Runnable() {[/li][li][/li][li] @Override[/li][li] public void run() {[/li][li] //这里作比较耗时的工作,暂时用线程休眠2秒作替代。[/li][li] try {[/li][li] Thread.sleep(4*1000);[/li][li] } catch (InterruptedException e) {[/li][li] // TODO Auto-generated catch block[/li][li] e.printStackTrace();[/li][li] }[/li][li] myHandler.sendMessage(myHandler.obtainMessage());[/li][li] }[/li][li] }).start();[/li][li] }
[/li]
复制代码
先show一个dialog,然后新开Thread做耗时操作,最后调用handler的sendMessage,唤醒Handler。handler写法如下:
[li]private Handler myHandler = new Handler(){[/li][li] @Override[/li][li] public void handleMessage(Message msg) {[/li][li] progressDialog.dismiss();[/li][li] super.handleMessage(msg);[/li][li] }[/li][li][/li][li] };
[/li]
复制代码
Android还有另一种方式实现就是利用AsyncTask,主要代码如下:
[li]private class DownloadFilesTask extends AsyncTask {[/li][li] @Override[/li][li] protected Void doInBackground(Void… params) {[/li][li] //耗时操作,[/li][li] try {[/li][li] Thread.sleep(4*1000);[/li][li] } catch (InterruptedException e) {[/li][li] // TODO Auto-generated catch block[/li][li] e.printStackTrace();[/li][li] }[/li][li] return null;[/li][li] }[/li][li] @Override[/li][li] protected void onPostExecute(Void result) {[/li][li] //作UI线程的修改。[/li][li] progressDialog.dismiss();[/li][li] super.onPostExecute(result);[/li][li] }[/li][li]}
[/li] |