android线程间通信和主线程更新ui

今天做了一个demo,需要更新下载进度,搜集信息发现两种方案

1,使用Hanlder机制

在Activity中 重新 Handler的handleMessage方法

 private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int i = msg.arg1;
            builder.setProgress(100, i, false);
            //发送通知
            notificationManager.notify(notificationFlag, builder.build());
            if (i == 100) {
                notificationManager.cancel(notificationFlag);
                installApp(filePath);
            }
        }
    };
在子线程中 获取Message对象,并发送

 
new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i <= 100; i++) {
                      Message msg = handler.obtainMessage();
                      msg.arg1 = i;
                      handler.sendMessage(msg);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

2,在子线程中 使用Activity的 runOnUiThread()方法

new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i <= 100; i++) {
                    MainActivity act= (MainActivity) context;
                    final int finalI = i;
                    act.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            builder.setProgress(100, finalI, false);
                            //发送通知
                            notificationManager.notify(notificationFlag, builder.build());
                            if (finalI == 100) {
                                notificationManager.cancel(notificationFlag);
                                installApp(filePath);
                            }
                        }
                    });
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();




你可能感兴趣的:(android,线程间通信)