2016-06-26 3 views
0

サービスから最初のメッセージを送信すると、1つのメッセージが受信されます。 2番目のメッセージを送信すると、2つのメッセージなどが表示されます。理由はわかりません。私は1回の送信ごとに1つのメッセージしか受信しません。なぜ私は複数を取得するのですか?私はあなたがいないonStartCommand内のonCreateメソッドで受信定義する必要はありだと思いサービスから1つのソケットを使用している間に複数の受信メッセージ

import android.app.IntentService; 
import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.AsyncTask; 
import android.os.Binder; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.support.v4.content.LocalBroadcastManager; 
import android.util.Base64; 
import android.util.Log; 
import android.widget.Toast; 

import com.github.nkzawa.emitter.Emitter; 
import com.github.nkzawa.socketio.client.IO; 
import com.github.nkzawa.socketio.client.Socket; 

import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.net.URISyntaxException; 

public class SocketService extends Service { 

    final String TAG = "SocketService"; 
    JSONObject sendMessage; 
    private Socket socket; 



    private final IBinder mBinder = new MyBinder(); 
    public class MyBinder extends Binder { 

     SocketService getService() { 
      return SocketService.this; 
     } 
    } 

    @Override 
    public void onCreate(){ 
     super.onCreate(); 


     //  Receive receive = new Receive(); 

     // receive.execute(); 
     Connection connection = new Connection(); 
     connection.execute(); 

    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 

     Receive receive = new Receive(); 

     receive.execute(); 

     Bundle extras = intent.getExtras(); 

     if(extras!= null) { 
      String msg = extras.getString("message"); 
      String encPth = extras.getString("encodeImagePath"); 

      Send send = new Send(); 
      send.execute(msg, encPth); 
     } 

     return Service.START_NOT_STICKY; 
    } 


    private String encodeImage(String path) { // Bitmap bm 

     File imagefile = new File(path); 
     FileInputStream fis = null; 
     try { 
      fis = new FileInputStream(imagefile); 
     } catch (FileNotFoundException e) { 

      e.printStackTrace(); 
     } 

     Bitmap bm = BitmapFactory.decodeStream(fis); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
     byte[] b = baos.toByteArray(); 
     String encImage = Base64.encodeToString(b, Base64.DEFAULT); 

     return encImage; 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO: Return the communication channel to the service. 
     throw new UnsupportedOperationException("Not yet implemented"); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     //socket.disconnect(); 
     Disconnection disconnection = new Disconnection(); 
     disconnection.execute(); 
    } 

    class Connection extends AsyncTask<Void, Void, Void>{ 
     @Override 
     protected Void doInBackground(Void... voids) { 
      try { 
       socket = IO.socket("http://ec2-74-52-49-87.eu-west-1.compute.amazonaws.com"); 
      } catch (URISyntaxException e) { 
       throw new RuntimeException(e); 
      } 


      socket.connect(); 
      return null; 
     } 
    } 

    class Disconnection extends AsyncTask<Void, Void, Void>{ 
     @Override 
     protected Void doInBackground(Void... voids) { 

      socket.disconnect(); 

     return null; 
     } 
    } 

    class Receive extends AsyncTask<Void, Void, Void>{ 

     @Override 
     protected Void doInBackground(Void... voids) { 


      Log.d(TAG, "onCreate"); 
      socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() { 

       @Override 
       public void call(Object... args) { 
        Log.d(getClass().getCanonicalName(), "Connected to server"); 
       } 

      }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() { 

       @Override 
       public void call(Object... arg0) { 
        Log.d(getClass().getCanonicalName(), "Disconnected from server"); 
       } 

      }); 
      socket.on("message", new Emitter.Listener() { 
       @Override 
       public void call(Object... args) { 


          JSONObject data = (JSONObject) args[0]; 
          Log.d(TAG, "Handling friendcall"); 
          String message = null; 
          String imageText = null; 

          try { 
           if (data.getString("image") != null) { 

            message = data.getString("text").toString(); 
            imageText = data.getString("image"); 

            Intent in = new Intent(); 
            Bundle extras = new Bundle(); 
            extras.putString("MsgWithImag", message); 
            extras.putString("Imag", imageText); 
            in.putExtras(extras); 
            in.setAction("NOW"); 

            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(in); 
            Log.d(TAG, "Call from : " + message + imageText); 
           } 

          } catch (JSONException e) { 
           // Log.d(TAG, "friend call object cannot be parsed"); 
           e.printStackTrace(); 
          } 

          try { 
           if (data.getString("sansPhoto") != null) { 
            message = data.getString("text").toString(); 

            Intent in = new Intent(); 
            in.putExtra("Msg", message); 
            in.setAction("NOW"); 

            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(in); 

           } 
          } catch (JSONException e) { 
           // Log.d(TAG, "friend call object cannot be parsed"); 
           e.printStackTrace(); 
          } 
         } 
        }); 


      Log.d(TAG, "onStartCommand. Socket should be up"); 


      return null; 
     } 
    } 

    class Send extends AsyncTask<Object, Void, Void>{ 

     String msg, encPth, sansPhoto; 


     @Override 
     protected Void doInBackground(Object... params) { 



       msg = (String)params[0]; 
       encPth = (String)params[1]; 
       sansPhoto = "g"; 


       sendMessage = new JSONObject(); 
       try { 

        if(msg != null) { 

         sendMessage.put("text", msg); 

        } 

        if(encPth != null){ //ImageBmp 

         sendMessage.put("image",encodeImage(encPth)); 
         // sendMessage.put("image", encodeImage(ImageBmp)); 

        }else{ 
         sendMessage.put("sansPhoto", sansPhoto); 
        } 


        socket.emit("message", sendMessage); 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 


      return null; 
     } 
    } 
} 
+0

メッセージを3回送信するとどうなりますか?あなたは3つのメッセージを受け取りますか?あなたはバッファをクリアする必要がありますか? –

+0

ありがとうございました@AdamH。彼らはlogiqueていません。初めて他のスマートフォンを使用した後、1から1、1後に1を受信し、16のメッセージを受信し、再び変更し、2つを受信します。私はバッファを使用しません。 –

+0

M. @アダムHあなたは解決策を持っていますか? –

答えて

0

は、これは私のコードです。新しい受信を呼び出すたびにサービスが開始されるためです。

Android onCreate or onStartCommand for starting service

+0

@mehd aziziありがとうございました!私はonCreateメソッドでReceiveを定義しますが、動作しません(同じ問題があります)。その後、私はrunOnUiThreadを追加しますが、動作しません。私はいつも同じ問題を抱えています。 –

+0

の新しいスレッド(新しいRunnableを(){ ます。public void実行(){ runOnUiThread(新しいRunnableを(){ @Override ます。public void実行(){ は=新しい受信()を受け取る受信、 receive.execute ();}});}})。 ' –

+0

M. mehd azizi解決策はありますか?私はいつもこの問題を抱えています。私は解決策を見つけることができません。助けてください。 –

関連する問題