2017-06-18 14 views
1

NotificationListenerServiceを使用していて、onNotificationPosted()が呼び出されたときにリモートソケットにデータを送信したいとします。 しかし、ソケットが接続されているという問題がありますが、BufferedWriterまたはその他の出力クラスを使用して何かを書くと、アプリケーションとAndroidスタジオでサービスをシャットダウンするまで、決してリモートソケットに送信されません。 これは、データを送信するための私のコードです:私は完全にアンドロイドスタジオに停止ボタンを使用して、アプリケーションを停止した後にのみサービスからリモートソケットにデータを送信する際の問題

  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(); 

、サーバはクライアントからのメッセージを取得します。 このコードは主なアプリケーションから私のために働いたのでメッセージを送信するためには問題ありませんが、バックグラウンドサービスがそれを使用する場合にのみ問題を引き起こします。

これは私のサーバーコード(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); 

      } 
     } 

答えて

0

はsepareteサービスクラスを作成し、そこにデータを送信しよう。デバイスのウェイクアップを忘れないでください。

私は意味は、新しいものにstartService()代わりに使用new Thread...

new Thread...のを使用しています。

+0

コードの最初のチャンクは、NotificationListenerService内のメソッドです。つまり、サーバーとの通信のためだけに新しいサービスを作成する必要がありますか? –

+0

@ EldarAzulay、yes – Vyacheslav

+0

新しいサービスで同じ問題が再び発生します。上記のコードと全く同じコードを使用していますが、私は 'onStart()'メソッドでそれを書きました。 –

関連する問題