手记

℃江的程序员日记:Android中的主线程与子线程的交互方式

Android中的主线程与子线程的交互:

package com.example.handler;

import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.logging.Handler;

public class FourActivity extends AppCompatActivity {

    private Button btn_send, btn_stop;

    //创建的是主线程的Handler
    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {

            Message message = new Message();

            System.out.println("++++++++++++++++++++++主线程");

            //因为有Looper,在主线程收到消息后,向子线程发送消息
            threadHandler.sendMessageDelayed(message, 1000);
        }
    };

    private android.os.Handler threadHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_four);
        btn_send = (Button) findViewById(R.id.btn_send);
        btn_stop = (Button) findViewById(R.id.btn_stop);

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                handler.sendEmptyMessage(1);

            }
        });

        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handler.removeMessages(1);
            }
        });

        android.os.HandlerThread thread = new HandlerThread("handlerThread");
        thread.start();
        //创建子线程的Handler
        threadHandler = new android.os.Handler(thread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                Message message = new Message();
                System.out.println("=====================子线程");
                //向主线程去发送消息
                handler.sendMessageDelayed(message, 1000);

            }
        };

    }
}

打印的log是交互的:

3人推荐
随时随地看视频
慕课网APP