Android:我在哪里可以在服务中实现 socket.on(...)?我多次收到相同的消息
Posted
技术标签:
【中文标题】Android:我在哪里可以在服务中实现 socket.on(...)?我多次收到相同的消息【英文标题】:Android: Where can I implement socket.on(...) in a Service? I receive the same message several Times 【发布时间】:2017-03-22 19:09:01 【问题描述】:我想通过 AsyncTask 在服务中使用套接字。我将侦听器套接字放在 onCreate 中,并且多次收到相同的消息。我不知道在哪里可以实现我的套接字侦听器以便只接收一次消息。谢谢您的帮助。这是我的代码:
public class SocketService extends Service
final String TAG = "SocketService";
JSONObject sendMessage;
JSONObject sendUserPhone;
protected Socket socket;
String msg;
SessionManager session;
Handler handler;
private final IBinder mBinder = new MyBinder();
public class MyBinder extends Binder
SocketService getService()
return SocketService.this;
@Override
public void onCreate()
handler = new Handler();
super.onCreate();
Connection connection = new Connection();
connection.execute();
Identification identification = new Identification();
identification.execute();
Receive receive = new Receive();
receive.execute();
@Override
public int onStartCommand(Intent intent, int flags, int startId)
session = new SessionManager(getApplicationContext());
Bundle extras = intent.getExtras();
if(extras!= null)
String emtr_phone = session.getPhoneSession();
String msg = extras.getString("message");
String encPth = extras.getString("encodeImagePath");
String dest1_phone = extras.getString("dest1 phone");
String dest2_phone = extras.getString("dest2 phone");
String dest3_phone = extras.getString("dest3 phone");
String dest4_phone = extras.getString("dest4 phone");
String dest5_phone = extras.getString("dest5 phone");
String dest6_phone = extras.getString("dest6 phone");
String dest7_phone = extras.getString("dest7 phone");
String dest8_phone = extras.getString("dest8 phone");
String dest9_phone = extras.getString("dest9 phone");
String dest10_phone = extras.getString("dest10 phone");
String dest11_phone = extras.getString("dest11 phone");
String dest12_phone = extras.getString("dest12 phone");
String dest13_phone = extras.getString("dest13 phone");
String dest14_phone = extras.getString("dest14 phone");
String dest15_phone = extras.getString("dest15 phone");
Send send = new Send();
send.execute(emtr_phone, msg, encPth, dest1_phone,dest2_phone,dest3_phone, dest4_phone, dest5_phone, dest6_phone,dest7_phone,dest8_phone, dest9_phone, dest10_phone, dest11_phone,dest12_phone, dest13_phone, dest14_phone, dest15_phone);
return Service.START_STICKY;
// return Service.START_NOT_STICKY;
// return Service.START_REDELIVER_INTENT;
private String encodeImage(String path)
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.
// return mBinder;
//throw new UnsupportedOperationException("Not yet implemented");
return null;
@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-53-17-78-94.eu-west-1.compute.amazonaws.com:8080");
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 Identification extends AsyncTask<Void, Void, Void>
@Override
protected Void doInBackground(Void... voids)
// Session class instance
SessionManager session = new SessionManager(getApplicationContext());
String phone_session = session.getPhoneSession();
sendUserPhone = new JSONObject();
try
sendUserPhone.put("nbrphone", phone_session);
socket.emit("adduser", sendUserPhone);
catch (JSONException e)
e.printStackTrace();
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 msg;
// String imageText = null;
try
if (data.getString("image") != null)
String message = data.getString("text").toString();
String 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)
String 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 emetr_phone, msg, encPth, sansPhoto, dest1_phone, dest2_phone, dest3_phone, dest4_phone, dest5_phone, dest6_phone, dest7_phone, dest8_phone, dest9_phone, dest10_phone, dest11_phone, dest12_phone, dest13_phone, dest14_phone, dest15_phone;
@Override
protected Void doInBackground(Object... params)
emetr_phone = (String) params[0];
msg = (String) params[1];
encPth = (String) params[2];
sansPhoto = "g";
dest1_phone = SupprCaractDest((String) params[3]);
dest2_phone = SupprCaractDest((String) params[4]);
dest3_phone = SupprCaractDest((String) params[5]);
dest4_phone = SupprCaractDest((String) params[6]);
dest5_phone = SupprCaractDest((String) params[7]);
dest6_phone = SupprCaractDest((String) params[8]);
dest7_phone = SupprCaractDest((String) params[9]);
dest8_phone = SupprCaractDest((String) params[10]);
dest9_phone = SupprCaractDest((String) params[11]);
dest10_phone = SupprCaractDest((String) params[12]);
dest11_phone = SupprCaractDest((String) params[13]);
dest12_phone = SupprCaractDest((String) params[14]);
dest13_phone = SupprCaractDest((String) params[15]);
dest14_phone = SupprCaractDest((String) params[16]);
dest15_phone = SupprCaractDest((String) params[17]);
sendMessage = new JSONObject();
// String phone_emmet = SupprCaractEmmet(emetr_phone);
try
sendMessage.put("emetr_phone", emetr_phone);
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);
sendMessage.put("dest1_phone", dest1_phone);
sendMessage.put("dest2_phone", dest2_phone);
sendMessage.put("dest3_phone", dest3_phone);
sendMessage.put("dest4_phone", dest4_phone);
sendMessage.put("dest5_phone", dest5_phone);
sendMessage.put("dest6_phone", dest6_phone);
sendMessage.put("dest7_phone", dest7_phone);
sendMessage.put("dest8_phone", dest8_phone);
sendMessage.put("dest9_phone", dest9_phone);
sendMessage.put("dest10_phone", dest10_phone);
sendMessage.put("dest11_phone", dest11_phone);
sendMessage.put("dest12_phone", dest12_phone);
sendMessage.put("dest13_phone", dest13_phone);
sendMessage.put("dest14_phone", dest14_phone);
sendMessage.put("dest15_phone", dest15_phone);
socket.emit("message", sendMessage);
catch (JSONException e)
e.printStackTrace();
return null;
public String SupprCaractDest(String dest_phone)
String carAsup = "+";
dest_phone = dest_phone.replace(carAsup, "");
return dest_phone;
【问题讨论】:
【参考方案1】:你在初始化时对你的代码做 OK,并在 onCreate()
和 close
添加回调到 socket
onDestroy()
。但是,您应该在套接字初始化的同一线程中添加回调 (socket.on
)(现在您将它们分隔为 2 个不同的 AsyncTask
)。
如果您遇到任何错误,您应该:
- 检查您的onCreate()
是否被多次调用。如果它被称为多个 - >您的其他代码有问题。否则,问题来自您的服务器代码。
【讨论】:
谢谢 M.@Kingfisher Phuoc。我在同一个线程中添加了回调(socket.on),并且只调用了一次 onCreate,但我总是遇到同样的问题。以上是关于Android:我在哪里可以在服务中实现 socket.on(...)?我多次收到相同的消息的主要内容,如果未能解决你的问题,请参考以下文章