Thread 、Handler和IntentService的用法
重点
Thread(线程) 、Handler(句柄)、IntentService
内容
什么时候用到线程:需要在主线程中进行耗时任务时
什么时候用到句柄:将子线程中的消息传递给主线程。例如:更新UI
Android三种开启子线程的方式
一、继承Thread
创建子线程方法一 继承Thread类 class MyThread extends Thread{ @Override public void run() { //模拟耗时操作 try { sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } tv_text.setText("123456789"); 这里会报错,因为线程进行耗时操作后便不能对ui线程的界面进行更改 Only the original thread that created a view hierarchy can touch its views. } } MyThread myThread=new MyThread(); myThread.start(); //如果想要对tv_text设置值,就需要使用Handler句柄
二、继承Runnable
创建子线程方法二 继承Runnable类 class MyRunnable implements Runnable{ @Override public void run() { try { Runnable中没有sleep这个方法,所以要借用Thread中的方法 Thread.sleep(3000); String result="123456"; Log.i("Runnable:", result); } catch (InterruptedException e) { e.printStackTrace(); } } } MyRunnable myRunnable=new MyRunnable(); Thread thread=new Thread(myRunnable); thread.start();
三、同时使用Thread和Runnable
//创建子线程方法三 同时使用Thread和Runnable创建匿名内部类 new Thread(new Runnable() { @Override public void run() { try { //因为目前是在Runnable接口里所以还是要借用Thread的sleep方法 Thread.sleep(3000); String result="匿名线程"; tv_text.setText(result); } catch (InterruptedException e) { e.printStackTrace(); } } }).start();
首先如何定义Handler:
//这个方法已过时,一般会在加入Looper.getMainLooper()这个参数 //private Handler handler=new handler(){}; private Handler handler=new handler(Looper.getMainLooper){ }; //如何将子线程的消息传递给子线程? //在线程的run()中 Message msg=new Message(); msg.what=1; msg.obj="内容" //0x111是一个十六进制的数字 handler.sendEmptyMessage(0x111);
在主线程中接收消息
private Handler handler=new handler(Looper.getMainLooper){ handleMessage(Message msg){ if(msg.what==0x111){ String result=(Sring) msg.obj; tv1.setText(result); } };
IntentService
IntentService是Service的一个子类
他和Service的区别在于:Service不会自动开启线程,也不会自动关闭线程,但是IntentService会自动开启,也会自动关闭.