1

I am using NotificationListenerService and I want to send data to remote socket when onNotificationPosted() is called. But I have a problem that the socket is connected, but when I write something using BufferedWriter or any other output class, it never sends it to the remote socket, until I shut down the app and the service with android studio. this is my code for sending the data:

            new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //     DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                    //    outputStream.writeUTF(send_counter + " $title: " + title + " $mes: " + mes);
                    Log.d(TAG, "started sending info");
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    bw.write(send_counter + " $title: " + title + " $mes: " + mes);
                    bw.newLine();
                    bw.flush();
                //    bw.close();
                    //  outputStream.writeInt(icon.length);
                    //      outputStream.write(icon);
                    Log.d(TAG, "info sent");
                    //    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

only after I completely stop the app using stop button on android studio, the server gets the message from the client. This code is fine for sending a message because this code worked for me from the main app, but it makes problems only when the background service uses it.

this is my server code (c#):

            TcpClient client = server.AcceptTcpClient();
            NetworkStream nwStream = client.GetStream();

            PostToConsole("Phone has connected from: " + ((IPEndPoint)client.Client.RemoteEndPoint).Address + ":" + ((IPEndPoint)client.Client.RemoteEndPoint).Port);

            byte[] buffer = new byte[client.ReceiveBufferSize];
            int res = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            while (res > 0)
            {
                string data = Encoding.UTF8.GetString(buffer, 0, res);
                PostToConsole(data + ((IPEndPoint)client.Client.RemoteEndPoint).Address);

                buffer = new byte[client.ReceiveBufferSize];
                res = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            }
        }
Eldar Azulay
  • 271
  • 1
  • 3
  • 17

1 Answers1

0

try to create a separete Service class and send the data into it. Do not forget to wakeup the device.

I mean, use startService() instead of new Thread...

use new Thread... into a new one.

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194