gpt4 book ai didi

java - Android HandlerThread 在没有 UiHandler 的情况下更新 UI

转载 作者:太空宇宙 更新时间:2023-11-04 10:52:22 25 4
gpt4 key购买 nike

此代码工作正常并更新我的“TextView”并显示“Toast”这就是我的头痛,因为我试图传递一个可运行的对象,而不包含我的 UiHandler,因为它应该是更新我的 UI 线程的桥梁,但我的 Activity 已更新,没有任何错误??????这不应该是 CustomHandlerThread 应该是一个不同的线程

为什么会发生这种情况?

My Activity

公共(public)类 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();
}

my 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作为引用

是我的线程运行在MainThread上还是getLooper()初始化我的 HandlerThread 和 MainThread Looper ,那些日志消息是真的

请照亮我

最佳答案

After fill day of debugging i Found out That if i post A Runnable to my mWorkerThread with sleep() as here i got " Only the original thread that created a view hierarchy can touch its views." as should be.. but until I know why it not works without it I wish it would help some one.

   try {
TimeUnit.SECONDS.sleep(2);
send_test_message.setText("Change--->");
} catch (Exception e) {
e.printStackTrace();
}

关于java - Android HandlerThread 在没有 UiHandler 的情况下更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47660631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com