Handler 在子线程工作
public class MainActivity extends AppCompatActivity {
private Button mButton;
private TextView textView;
DownLoad mLoad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initview();
initDownLoad();
}
private void initview() {
mButton = (Button) findViewById(R.id.test_btn);
textView = (TextView) findViewById(R.id.textview);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Message message = new Message();
message.obj = "sql work";
mLoad.mHandler.sendMessage(message);
}
});
}
private void initDownLoad() {
mLoad = new DownLoad();
new Thread(mLoad).start();
}
class DownLoad implements Runnable {
private Handler mHandler;
@Override
public void run() {
Log.d("123", Thread.currentThread().getName());
try {
Thread.sleep(5000);
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d("123", msg.obj.toString());
//获得主线程发来的消息,进行耗时处理,比如sql操作
}
};
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
在这里又报错了:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
无法在未调用Looper.prepare()的线程中创建handler.
通过看源码例子 实现以下代码
public void run() {
Looper.prepare();
Log.d("123", Thread.currentThread().getName());
try {
Thread.sleep(5000);
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d("123", msg.obj.toString());
}
};
} catch (InterruptedException e) {
e.printStackTrace();
}
Looper.loop();
}
}
这样就能正常使用了,到这里基础的用法就已经理解了,想要理解Handler还是需要看源码的,下篇再让我们从源码分析下Handler的使用
网友评论