Android笔记【1】--Handler

鸡汤:世界上最可怕的事情是比你优秀的人更加努力。


Handler的学习

       

1.        什么是handler?

A Handler allows you to send and process {@link Message} and Runnable objects associated with a thread's ,Each Handler
 instance is associated with a single thread and that thread's message queue.  

Handler主要用于异步消息的处理:当发出一个消息之后,首先进入一个消息队列,发送消息的函数即刻返回,而另外一个部分在消息队列中逐一将消息取出,然后对消息进行处理,也就是发送消息和接收消息不是同步的处理。 这种机制通常用来处理相对耗时比较长的操作

2.        为什么要用handler?

更新view在主线程中进行即UI线程,android中的view线程不是安全的。更新UI一定要在主线程中。不然致命的错误。

3.        Handler怎么用?

post(Runnable r)

postAtTime(Runnable, long)

postDelayed(Runnable r, long delayMillis)

sendEmptyMessage(Message msg)

sendMessage(int what)

sendMessageAtTime(Message msg, long uptimeMillis)

4.        Android为什么要设计只能通过handler机制更新UI?

主线程是安全,更新还是UI线程

5.        Handler的原理?

一般情况下,在主线程中我们绑定了Handler,并在事件触发上面创建新的线程用于完成某些耗时的操作,当子线程中的工作完成之后,会对Handler发送一个完成的信号,而Handler接收到信号后,就进行主UI界面的更新操作


6.        使用handler遇到的问题?

Can't create handler inside thread that has not called Looper.prepare()

 if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");

Only the original thread that created a view hierarchy can touch its views

CheckThread()判断当前线程是不是主线程,不是在主线程(UI线程)就抛出异常

7.        如何实现一个线线程相关的handler?

private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case <span style="font-weight: bold;">state</span>:
				mButton.setText(currentDownloadBin + "%");
				mBar.setProgress((int) currentDownloadBin);
				break;
			case 22:
				mTextView.setText(" 固件文件不存在或不完整(bin和ini)");
				mButton.setEnabled(false);

			default:
				break;
			}
		}

	};



8.        HandlerThread又是什么?

处理handler的子线程

		子线程handler
		HandlerThread thread = new HandlerThread("handlerThread");
		thread.start();
		threadHandler = new Handler(thread.getLooper()){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
			}
			
		};


9.        如何在主线程中给子线程发送消息?

// 更新UI进度条
			mHandler.sendEmptyMessage(state); 主线程
<span style="font-weight: bold;">HandlerThread </span>创建子线程handler 


10.    Android中更新UI的几种方式?

runOnUiThread 

handler post

handler sendMessage

View.post

A.如果只是单纯的想要更新UI而不涉及到多线程的话,使用View.post()就可以了;

B.需要另开线程处理数据以免阻塞UI线程,像是IO操作或者是循环,可以使用Activity.runOnUiThread();

C.如果需要传递状态值等信息,像是蓝牙编程中的socket连接,就需要利用状态值来提示连接状态以及做相应的处理,就需要使用Handler + Thread的方式;

D.如果是后台任务,像是下载任务等,就需要使用AsyncTask。


11.    非UI线程真的不能更新UI吗?

new Thread (  ).start   在不休眠情况下run方法里面可以更新

体会:人不能太贪,贪多,想一下理解更多的东西,需要时间去实践并且体会。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值