Thread
第一种方式:
class MyThread extends Thread{ public void run(){ // 写耗时操作代码 // Only the original thread that created a view hierarchy can touch its views. // 如果子线程已经执行了耗时操作,那么就不能修改视图的属性了;视图的属性只能在UI线程去修改 } } MyThread myThead = new MyThread(); myThread.start();
第二种方式:
class MyRunnable implements Runnable { @Override public void run() { try { Thread.sleep(3000); String result = "runnable 345345"; Log.i("runnable", result); } catch (InterruptedException e) { e.printStackTrace(); } } } MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start();
第三种方式:(常见、推荐)
new Thread(new Runnable() { @Override public void run() { // 耗时任务 try { Thread.sleep(3000); String result = "匿名线程"; Log.i("匿名线程",result); } catch (InterruptedException e) { e.printStackTrace(); } } }).start();
3 Handler
handle是一套 Android 消息传递机制,主要用于线程间通信。
handle作用:是满足线程与线程之间通信的
主线程不能做耗时操作,子线程不能更新UI
/** * 从服务器接收到用户的昵称,并将昵称设置在textview对应的text属性上 * * 连接服务器的功能,是属于耗时任务,所以必须放在子线程 * * 子线程中是没有办法修改页面,借助Handler给主线程传递消息 *