我可以为同时执行的1个以上线程中的按钮创建onClickListener()
吗?
是否会在每个线程中单独调用该侦听器?
答案 0 :(得分:0)
不,按钮只有一个onClickListener。设置第二个会覆盖先前设置的任何侦听器。并且该功能仅在UI线程上调用。您可以通过该函数将消息传递给多个线程。
答案 1 :(得分:0)
线程之间有很多通信方式。由于您想知道如何将某些内容传递给线程,这里有一个简单的例子:
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
...
//Start a thread you need to
anotherThread = new AnotherThread();
anotherThread.start();
}
protected void onResume() {
...
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
anotherThread.sendData(message);
}
});
}
}
public class AnotherThread extends Thread {
//Instantiate handler to associate it with the current thread.
//Handler enqueues all tasks in the MessageQueue using Looper
//and execute them upon coming out of queue;
private Handler handler;
@Override
public void run() {
try {
//Here we create a unique Looper for this thread.
//The main purpose of which to keep thread alive looping through
//MessageQueue and send task to corresponding handler.
Looper.prepare();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
//manage incoming messages here
String value = msg.getData().getString("key");
}
};
Looper.loop();
} catch (Throwable e) {
e.printStackTrace();
}
}
public synchronized void sendData(Message message) {
handler.post(new Runnable() {
@Override
public void run() {
handler.sendMessage(message);
}
});
}
}