[英]Control Socket InputStream and OutputStream from Fragment (Android)
I have created a runnable class (Thread) witch connects to server, send and receives messages. 我创建了一个可运行类(线程),它连接到服务器,发送和接收消息。
public class ConnectAndReceiveData implements Runnable{
private BufferedReader inputBuffer;
private String incomeText;
private DataOutputStream outputStream;
@Override
public void run(){
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
if(socket.isConnected()){
outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeBytes("Hello");
}
inputBuffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (!Thread.currentThread().isInterrupted()) {
if (inputBuffer.ready()) {
incomeText = inputBuffer.readLine();
System.out.println(incomeText);
}
}
} catch (UnknownHostException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But all the previous code is inside the main activity. 但是所有先前的代码都在main活动中。
Is there any possibility to get the inputStream or the outputStream or the whole socket in a fragment?? 是否有可能在片段中获取inputStream或outputStream或整个套接字?
I tried to add the socket inside a parcable object and then to pass it to the fragment but i was not successful. 我试图将套接字添加到一个可解析的对象内,然后将其传递给片段,但是我没有成功。
I hope you can help me!!! 我希望你能帮帮我!!!
Created a getSocket method in main activity 在主要活动中创建了一个getSocket方法
public void Socket getSocket(){
return socket
}
To get the socket form fragment i just write the follow inside the onCreateView method 要获取套接字形式片段,我只需在onCreateView方法内编写以下代码
Socket socket = ((MainActivity)getActivity()).getSocket();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.