使用处理程序在UI线程和其他线程之间进行通信

8
如何在UI线程和后台线程之间进行线程间通信?我想在这里使用常见的handler概念来更新我的UI。我的概念如下:
new Thread(new Runnable() {
         public void run() {
             while (mProgressStatus < 100) {
                 mProgressStatus = doWork();

                 // Update the progress bar
                 mHandler.post(new Runnable() {
                     public void run() {
                         mProgress.setProgress(mProgressStatus);
                     }
                 });
             }
         }
     }).start();

我想使用两个类,一个类包含主线程,另一个类包含后台线程,并且它们使用同一个handler。我该如何实现这一点? 我知道这很常见,但我发现确切地实现它有些困难。

1个回答

9
如果您不想使用静态概念,可以从参数中传递任何内容。在下面的代码中,我实现了两个类。如您所要求的那样,在两个线程类中都使用了公共处理程序。我将处理程序h1作为Runnable对象的参数传递,并在那里使用start()方法触发另一个线程类的run()方法。包含run()方法的线程是UI(主)线程。我们必须使用UI线程来更新UI。工作者(后台)线程无法进行UI更新。工作者与UI之间的通信通过处理程序完成。因此,我在UI线程类中定义处理程序h2。当从后台线程类调用UI线程类构造函数时,我从构造函数中获取h1的值,并使用h2进行通信。实际上,h2和h1属于系统中的同一内存空间。
以下是我制作的两个类并进行线程通信供您参考。
第一个类:
 public class MainActivity extends AppCompatActivity {
    Handler h1;
    Thread t;
    EditText editText;
    private Bundle bb = new Bundle();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText);

        h1 = new Handler(Looper.getMainLooper()) {

            @Override
            public void handleMessage(Message msg) {
                bb = msg.getData();
                String str = bb.getString("udd");
                editText.setText(str);
                System.out.println(str);
            }
        };
        t = new Thread(new MyRunnable(h1)); //I pass Runnable object in thread so that the code inside the run() method
        //of Runnable object gets executed when I start my thread here. But the code executes in new thread
        t.start(); //thread started

        try {
            t.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

}

第二类

public class MyRunnable implements Runnable {
    private Handler h2;
    public MyRunnable(Handler h) {
        this.h2 = h;
    }

    @Override
    public void run() {

        //everything inside rum method executes in new thread
        for(int i=0;i<10;i++) {
            Message m = Message.obtain(); //get null message
            Bundle b = new Bundle();
            b.putString("udd", "daju");
            m.setData(b);
            //use the handler to send message
            h2.sendMessage(m);

        }
    }
}

注意: 当调用thread.start()时,会启动Runnable类的run方法,创建一个新的线程。因此,每次调用start()方法时,都会创建一个具有相同调用线程优先级的新线程。

希望这能对您有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接