此代码工作正常并更新我的" TextView"并且还显示" Toast" 这是我的头痛,因为我试图通过A Runnable obj而不包括我的UiHandler,因为它认为是更新我的UI线程的桥梁,但我的活动更新没有单一的错误????? 这不应该是因为CustomHandlerThread应该是一个不同的线程
为什么会这样?
我的活动
公共类TestActivity扩展了BaseActivity {
Runnable task;
@BindView(R.id.send_test_message)
Button send_test_message;
private Handler mUiHandler = new Handler();
private MyWorkerThread mWorkerThread;
@Override
public void initViews() {
}
@Override
public void attachViewsListeners() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
ButterKnife.bind(this);
task = new Runnable() { ///this is normally work I have no problem with
///that
@Override
public void run() {
mUiHandler.post(new Runnable() {
@Override
public void run() {
send_test_message.setText("Change--->1");
}
});
}
};
}
@Override
protected void onStart() {
super.onStart();
mWorkerThread = new MyWorkerThread("myWorkerThread");
mWorkerThread.start();
mWorkerThread.prepareHandler();
mWorkerThread.postTask(task);
mWorkerThread.postTask(new Runnable() { /// why this task work with no
///error ?
@Override
public void run() {
send_test_message.setText("Change--->2");
}
});
}
@Override
protected void onDestroy() {
mWorkerThread.quit();
super.onDestroy();
}
我的HandlerThread
//MyWorkerThread.java
public class MyWorkerThread extends HandlerThread {
Handler mWorkerHandler;
public MyWorkerThread(String name) {
super(name);
}
public void postTask(Runnable task) {
mWorkerHandler.post(task);
}
public void prepareHandler() {
mWorkerHandler = new Handler(getLooper());
Log.e("MyWorkerThread--->",Looper.myLooper().getThread().getName()); //-->main
Log.e("MyWorkerThread--->",getLooper().getThread().getName());//-->//myWorkerThread
Log.e("MyWorkerThread--->",Thread.currentThread().getName()); //-->main
}
}
我按照link作为A Referance
是我在MainThread上运行的线程或getLooper()初始化我的 HandlerThread with MainThread Looper,是那些日志消息是真的
答案 0 :(得分:0)
在完成调试后的一天我发现如果我将A Runnable发布到我的 mWorkerThread与sleep()在这里我得到“只有创建视图层次结构的原始线程才能触及其视图。” 应该......但直到我知道为什么没有它它不起作用 我希望它会对某人有所帮助。
try {
TimeUnit.SECONDS.sleep(2);
send_test_message.setText("Change--->");
} catch (Exception e) {
e.printStackTrace();
}