There is an activit that launches AsyncTask:
public class MainActivity extends ActionBarActivity implements View.OnClickListener { SocketAsync SocketAsync = new SocketAsync(); ConfigSocket config = new ConfigSocket(); Button btnEnter; Button btnFight; //выводит все элементы этого активити @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //убираю ActionBar getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //убираю заголовок приложения ActionBar actionBar = getSupportActionBar(); actionBar.hide(); setContentView(R.layout.activity_main); //подключаем лауер-файл с элементами //находим эти элементы по ID btnEnter = (Button) findViewById(R.id.btnEnter); btnFight = (Button) findViewById(R.id.btnFight); // присваиваем обработчик кнопкам btnEnter.setOnClickListener(this); btnFight.setOnClickListener(this); SocketAsync.execute(); } //обработчик нажатий на кнопки @Override public void onClick(View v) { // по id определеяем кнопку, вызвавшую этот обработчик switch (v.getId()) { case R.id.btnEnter: config.setSOCKET_MESSAGE("12345"); break; case R.id.btnFight: config.setSOCKET_MESSAGE("12345"); break; } } AsyncTask code:
public class SocketAsync extends AsyncTask <Void, Integer, Void> { public Socket socket; public String message; ConfigSocket config = new ConfigSocket(); @Override protected Void doInBackground(Void... params) { //конект с сервером try { if (config.getSOCKET_CONNECTED() == false) { InetAddress serverAddr = InetAddress.getByName(config.SERVER_ADDR); socket = new Socket(serverAddr, config.SERVER_PORT); config.setSOCKET_CONNECTED(true); } } catch (Exception e) { e.printStackTrace(); } //создает новый поток для отправки сообщений Thread threadWrite = new Thread(new Runnable() { @Override public void run() { send(socket); } }); threadWrite.start(); // запускаем на отправку //пока есть конект с сервером, цикл ждет приема сообщений while (socket != null && socket.isConnected()) { //Message m = new Message(); //m.what = 2; try { //переменная для получение данных BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream())); String st = null; st = input.readLine(); } catch (IOException e) { e.printStackTrace(); } } threadWrite.stop(); return null; } protected void send(Socket socket) { PrintWriter out = null; //пока есть конект с сервером, цикл ждет сообщение на отправку while (socket != null && socket.isConnected()) { if (config.getSOCKET_MESSAGE() = null) { //Log.d("Send Message", config.SOCKET_MESSAGE); try { out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println(config.getSOCKET_MESSAGE()); } catch (Exception e) { return; } config.setSOCKET_MESSAGE(null); } } } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); //если связь разорвалась.... if (socket == null || !socket.isConnected()) { config.setSOCKET_CONNECTED(false); } } and there is such a class:
public class ConfigSocket { boolean SOCKET_CONNECTED = false; String SERVER_ADDR = "192.168.1.23"; int SERVER_PORT = 8888; String SOCKET_MESSAGE = null; public String getSOCKET_MESSAGE() { //геттер SOCKET_MESSAGE return this.SOCKET_MESSAGE; } public void setSOCKET_MESSAGE(String SOCKET_MESSAGE) { //сеттер SOCKET_MESSAGE this.SOCKET_MESSAGE = SOCKET_MESSAGE; } public boolean getSOCKET_CONNECTED() { //геттер SOCKET_CONNECTED return this.SOCKET_CONNECTED; } public void setSOCKET_CONNECTED(boolean SOCKET_CONNECTED) { //сеттер SOCKET_CONNECTED this.SOCKET_CONNECTED = SOCKET_CONNECTED; } } Help me to understand. This is how I think. AsyncTask launches a new stream, where it connects to the server (which the server informs me that the new client has successfully connected) and until the connection is broken through the loop, it must wait for incoming information. And another stream is started, which should send a message to the server. Its loop should scan the SOCKET_MESSAGE variable from the ConfigSocket class, if it is not null , then send a message to the server. By activating the button, I set the variable value, but the message is not sent. And if before launching the application in ConfigSocket prescribe the value SOCKET_MESSAGE , then it will be sent.
Please tell me what I'm doing wrong and how to implement it all correctly? Because I'm already the third day trying to figure it out. Thank you very much in advance.