Handler使用实例

实例1:

post(Runnable r)和post(Runnable r, long delayMillis),将指定Runnable(包装成PostMessage)加入到MessageQueue中,然后Looper不断从MessageQueue中读取Message进行处理。该用例只是new了Runable,但无Thread.start()的调用,因此并没有开启子线程

Handler使用实例_第1张图片

其中activity的代码如下:
public class MainActivity extends AppCompatActivity {

    private TextView text_view = null;
    private Button start = null;
    private Button end = null;
    Handler handler = new Handler();
    Runnable send_msg_runable = new Runnable()
    {
        public void run()
        {
            text_view.append("\nreceive msg.");
            handler.postDelayed(send_msg_runable, 2000);
        }
    };

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

        text_view = (TextView)findViewById(R.id.text_view);
        start = (Button)findViewById(R.id.send);
        end = (Button)findViewById(R.id.end);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将线程接口立刻送到线程队列中
                handler.post(send_msg_runable);
            }
        });

        end.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.removeCallbacks(send_msg_runable);
            }
        });

    }

布局文件如下:




    

 

实例2:

public class MainActivity extends AppCompatActivity {

    private ProgressBar progress_bar = null;
    private Button start = null;

    Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            progress_bar.setProgress(msg.arg1);
            mHandler.post(mRunable);
        }
    };

    Runnable mRunable = new Runnable()
    {
        int m = 0;
        public void run() {
            // TODO Auto-generated method stub
            m += 10;
            Message msg = mHandler.obtainMessage();
            msg.arg1 = m;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            //发送消息
            mHandler.sendMessage(msg);
            if(m == 100)
                //从线程队列中移除线程
                mHandler.removeCallbacks(mRunable);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progress_bar = (ProgressBar)findViewById(R.id.progress_bar);
        start = (Button)findViewById(R.id.send_msg);

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //让进度条显示出来
                progress_bar.setVisibility(View.VISIBLE);
                //将线程加入到handler的线程队列中
                mHandler.post(mRunable);
            }
        });
    }
}

布局如下:



    
    

说明:该实例也没有开启子线程

实例3:

主线程和子线程各自拥有一个handler,双向通信,

通过Looper.myLooper()获取当前线程Looper,子线程需要调用Looper.prepare和Looper.loop初始化looper

UI线程通过getMainLooper获取主线程looper

Activity代码如下:

public class MainActivity extends AppCompatActivity {

    public static final String TAG = "MainActivity";
    private TextView mTextView;
    private Handler1 mSubThreadHandler;
    private Handler2 mMainThreadHandler;
    private int counter=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        mTextView = (TextView) findViewById(R.id.text);


        new Thread() {
            public void run() {
                Looper.prepare();
                //Looper.myLooper()获取当前线程的looper
                mSubThreadHandler=new Handler1(Looper.myLooper());
                Message message = new Message();
                message.obj = "子线程发送的消息";
                //子线程给自己发消息
                mSubThreadHandler.sendMessage(message);
                Looper.loop();
            };
        }.start();

    }

    private class Handler1 extends Handler {

        private Handler1(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //子线程解析消息
           Log.d(TAG,"子线程收到:" + msg.obj);

            //子线程发消息到主线程
            mMainThreadHandler = new Handler2(getMainLooper());
            Message message = new Message();
            message.obj = "abc";
            mMainThreadHandler.sendMessage(message);
        }
    }

    private class Handler2 extends Handler {

        private Handler2(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //主线程解析消息
            mTextView.setText("主线程收到子线程消息:" + msg.obj);

            //主线程发消息到子线程
            if (counter==0) {
                Message message = new Message();
                message.obj = "主线程发送的消息mmm";
                mSubThreadHandler.sendMessage(message);
                counter++;
            }

        }
    }

}

布局文件如下:



    
    

运行结果如下:

Handler使用实例_第2张图片

 

 

 

 

 

 

你可能感兴趣的:(android/linux)