1 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個(gè)贊
好吧,我可以給你一個(gè)如何實(shí)現(xiàn)這一點(diǎn)的例子,但你確實(shí)需要研究我將使用的東西。
創(chuàng)建線程來(lái)發(fā)送和接收數(shù)據(jù)
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");
}
}
}
在主要活動(dòng)中:
//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);
}
}
創(chuàng)建發(fā)送線程
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
}
}
}
在主要活動(dòng)中
public void startSendThread(){
mySendingThread threadSend = new mySendingThread(MessageQueue);
thread.start();
}
在 mainActivity 中,您需要一個(gè)BlockingQueue<String> MessageQueue 并且可以添加您想要的每條消息。
添加回答
舉報(bào)