我在下面的代码中使用HandlerThread和Handler,实际上我尝试将数据从 runnable 更新为 Handler 回调。
在每个循环中,调用了sendMessage()函数,但我在回调中没有收到任何内容。我错过了什么?
public class MainActivity extends AppCompatActivity {
private TextView result;
HandlerThread handlerThread = new HandlerThread("bThread");
Callback callBack = new Callback(){
@Override
public boolean handleMessage(Message message) {
Bundle bundle = message.getData();
String val = bundle.getString("output");
result.setText(val);
return false;
}
};
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = findViewById(R.id.result);
handlerThread.start();
handler = new Handler(handlerThread.getLooper(),callBack);
handler.post(runnable);
}
Runnable runnable= new Runnable() {
@Override
public void run() {
for (int i = 0; i <200 ; i++) {
try {
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("output",i+"");
message.setData(bundle);
handler.sendMessage(message);
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
}