reda youssoufi reda youssoufi - 25 days ago 11
Android Question

Android: Where can I implement socket.on(...) in a Service? I receive the same message several Times

I want to use a socket in a service with AsyncTask. I put the listener socket in the onCreate and I receive the same message several times. I don't know where I can implement my socket listener in order to receive the message only once. Thank you for your help. This is my code:

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


}

Answer

you do Ok with your code when init and add callback to socket at the onCreate() and close it in onDestroy(). However, your should add callback (socket.on) in the same thread with your socket initializing (now you are separating them in 2 different AsyncTask).

If you got any error, you should: - Check if your onCreate() is called many times or not. If it's called more than one --> your other codes have issues. Otherwise, the issue comes from your server code.

Comments