自服务以来我使用一个套接字时多次接收消息

时间:2016-06-26 04:40:40

标签: android sockets android-asynctask android-service

当我从服务发送第一条消息后,我收到一条消息。当我发送第二条消息时,我会收到两条消息,等等。我不知道为什么。我希望每次发送只收到一条消息。为什么我会获得多个?

这是我的代码:

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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你必须在onCreate方法中定义不在onStartCommand中的Receive。因为每次调用新的接收服务都会启动。

Android onCreate or onStartCommand for starting service