I would like to ask about sockets in Android. I rummaged through half of the Internet and did not find what I needed.
The task is to write a client for Android in Java, which would send and receive messages. When I wrote to the computer, everything was wonderful, I immediately ran into the problem of multithreading (you cannot call network tasks from the main thread). I figured out more or less, forced me to send messages to the server, but I can’t get the TextView to accept and update the dialogue history.
Here the client code, the server even rewrote as a simple echo server, sends back what the client sent. Below client code, help with the implementation of receiving messages from the server.
import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; public class MainActivity extends AppCompatActivity { private Socket socket; private Button SendBut; private EditText editText; private TextView textView; private PrintWriter os; private BufferedReader is; networking net; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SendBut = (Button) findViewById(R.id.SendBut); editText = (EditText) findViewById(R.id.editText); textView = (TextView) findViewById(R.id.TxtFrSrv); net = new networking(); net.execute(); } public void onClck(View view) { String txt = null; txt = editText.getText().toString(); os.println(txt); } public class networking extends AsyncTask < String, Void, Void > { @Override protected Void doInBackground(String...params) { try { socket = new Socket("10.0.2.2", 4444); os = new PrintWriter(new PrintWriter(new OutputStreamWriter(socket.getOutputStream())), true); } catch (IOException e) { e.printStackTrace(); } return null; } } } I tried to portray something similar to this, but with zero value it is impossible to start ...
public class getMsg extends Thread{ public void run(){ try { is=new BufferedReader(new InputStreamReader(socket.getInputStream())); final String finc; finc=is.readLine(); while (!finc.equals("break")){ MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { textView.setText(finc); } }); } } catch (IOException e) { e.printStackTrace(); } } }