1 回答
TA贡献1856条经验 获得超5个赞
好吧,我可以给你一个如何实现这一点的例子,但你确实需要研究我将使用的东西。
创建线程来发送和接收数据
public class myReceiveThread extends Thread{
public gotNewData listener;
//Create an interface to pass data to Activity
public interface gotNewData(){
void gotNewDataToDisplay(String data); //or int or data or what ever.
}
//CTor
public myThread(gotNewData listener){
this.listener = listener;
}
@Override
public void run(){
while(myAppisRunnung == true){
//Receive Data
listener.gotNewDataToDisplay("New Data");
}
}
}
在主要活动中:
//In Main activity
public class MainActivity extends AppCompactActiity implements gotNewData{
//what ever
public void startThread(){
myReceiveThread thread = new myReceiveThread(this);
thread.start();
}
@Override
public void gotNewDataToDisplay(String data){
someTextView.setText(data);
}
}
创建发送线程
public class mySendingThread extends Thread{
private BlockingQueue<String> toSendMessages= new BlockingQueue<>();
Public mySendingThread (BlockingQueue<String> toSendMessages){
this.toSendMessages = toSendMessages;
}
@Override
public void run(){
while(myAppisRunnung == true){
String message= toSendMessages.take();
//Send message
}
}
}
在主要活动中
public void startSendThread(){
mySendingThread threadSend = new mySendingThread(MessageQueue);
thread.start();
}
在 mainActivity 中,您需要一个BlockingQueue<String> MessageQueue 并且可以添加您想要的每条消息。
添加回答
举报