Socket Io With Android Service











up vote
3
down vote

favorite
1












Good day. I have a very specific issue considering the Socket IO library for android and it's service.



Important to mention that my device is huawei p8 lite which i am testing on.



Here it goes :



• I have a socket Io library which is being initialized inside the service i have created



• I set the listener to the socket io for new messages



• Everything works like a char if the application is not killed within the process trey by the user.



• The purpose of service was to keep the socket IO connection alive even if the application is killed so the user will be notified about new messages.



• As soon as the application is being killed,the Socket IO connection has been disconnected



No matter what i try,and i try all of possible ways : Isolating the process of Service,giving another process for the service,Starting it sticky,starting it not sticky recreating as soon as the service destroys and etc.



The only thing which has worked is the startForeground() method,but i do not want to use it as it will go under the design principles and plus i do not want to show any notification about the running service.



My question is the next : Can anyone help me out and tell me how can i keep the Socket IO connection alive even if the application is killed?



Here is the code of the service.



package com.github.nkzawa.socketio.androidchat;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import java.net.URISyntaxException;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class SocketService extends Service {
private Socket mSocket;
public static final String TAG = SocketService.class.getSimpleName();

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw null;
}

@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "on created", Toast.LENGTH_SHORT).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "start command", Toast.LENGTH_SHORT).show();
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
mSocket.on("newMessageReceived", onNewMessage);
mSocket.connect();
return START_STICKY;
}

private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(Object... args) {
String message = args[0].toString();
Log.d(TAG, "call: new message ");
sendGeneralNotification(getApplicationContext(), "1", "new message", message, null);
}
};

private void sendGeneralNotification(Context context, String uniqueId,
String title, String contentText,
@Nullable Class<?> resultClass) {

NotificationManager notificationManagerCompat = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(context);
builder.setAutoCancel(true);


builder.setContentTitle(title);
builder.setContentText(contentText);
builder.setGroup("faskfjasfa");
builder.setDefaults(android.app.Notification.DEFAULT_ALL);
builder.setStyle(new NotificationCompat.BigTextStyle()
.setSummaryText(title)
.setBigContentTitle(title)
.bigText(contentText)
);

Intent requestsViewIntent = new Intent(context, MainActivity.class);
requestsViewIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
requestsViewIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent requestsViewPending = PendingIntent.getActivity(context, Integer.valueOf(uniqueId), requestsViewIntent, 0);
builder.setContentIntent(requestsViewPending);
builder.setSmallIcon(R.drawable.ic_launcher);

builder.setShowWhen(true);
android.app.Notification notification = builder.build();
notificationManagerCompat.notify(Integer.valueOf(uniqueId), notification);
}

private Notification getNotification() {
Notification notification;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setColor(getResources()
.getColor(R.color.material_deep_teal_500))
.setAutoCancel(true);

notification = builder.build();
notification.flags = Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_AUTO_CANCEL;

return notification;
}
}


And NO,i do not want to use neither firebase nor any 3rd party made ones as i am using one now and i suffer from delays,from non-received notifications and etc,and i will make my own small one ways better. Thanks everyone for you'r time and patience.










share|improve this question




















  • 2




    hmm i guess i have asked really horrible question huh? No one even closer tried to asnwer or give a smallest hint at all
    – Volo Apps
    Feb 13 '17 at 21:32










  • Hi Volo, I too facing exactly same issue did you found any way to achieve it,if so can you share it as your own answer,Thank you in advance.
    – Shylendra Madda
    Jun 15 '17 at 3:23










  • Find complete server and client side solution here stackoverflow.com/a/45099689/5063805
    – JosephM
    Jul 14 '17 at 9:49















up vote
3
down vote

favorite
1












Good day. I have a very specific issue considering the Socket IO library for android and it's service.



Important to mention that my device is huawei p8 lite which i am testing on.



Here it goes :



• I have a socket Io library which is being initialized inside the service i have created



• I set the listener to the socket io for new messages



• Everything works like a char if the application is not killed within the process trey by the user.



• The purpose of service was to keep the socket IO connection alive even if the application is killed so the user will be notified about new messages.



• As soon as the application is being killed,the Socket IO connection has been disconnected



No matter what i try,and i try all of possible ways : Isolating the process of Service,giving another process for the service,Starting it sticky,starting it not sticky recreating as soon as the service destroys and etc.



The only thing which has worked is the startForeground() method,but i do not want to use it as it will go under the design principles and plus i do not want to show any notification about the running service.



My question is the next : Can anyone help me out and tell me how can i keep the Socket IO connection alive even if the application is killed?



Here is the code of the service.



package com.github.nkzawa.socketio.androidchat;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import java.net.URISyntaxException;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class SocketService extends Service {
private Socket mSocket;
public static final String TAG = SocketService.class.getSimpleName();

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw null;
}

@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "on created", Toast.LENGTH_SHORT).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "start command", Toast.LENGTH_SHORT).show();
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
mSocket.on("newMessageReceived", onNewMessage);
mSocket.connect();
return START_STICKY;
}

private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(Object... args) {
String message = args[0].toString();
Log.d(TAG, "call: new message ");
sendGeneralNotification(getApplicationContext(), "1", "new message", message, null);
}
};

private void sendGeneralNotification(Context context, String uniqueId,
String title, String contentText,
@Nullable Class<?> resultClass) {

NotificationManager notificationManagerCompat = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(context);
builder.setAutoCancel(true);


builder.setContentTitle(title);
builder.setContentText(contentText);
builder.setGroup("faskfjasfa");
builder.setDefaults(android.app.Notification.DEFAULT_ALL);
builder.setStyle(new NotificationCompat.BigTextStyle()
.setSummaryText(title)
.setBigContentTitle(title)
.bigText(contentText)
);

Intent requestsViewIntent = new Intent(context, MainActivity.class);
requestsViewIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
requestsViewIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent requestsViewPending = PendingIntent.getActivity(context, Integer.valueOf(uniqueId), requestsViewIntent, 0);
builder.setContentIntent(requestsViewPending);
builder.setSmallIcon(R.drawable.ic_launcher);

builder.setShowWhen(true);
android.app.Notification notification = builder.build();
notificationManagerCompat.notify(Integer.valueOf(uniqueId), notification);
}

private Notification getNotification() {
Notification notification;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setColor(getResources()
.getColor(R.color.material_deep_teal_500))
.setAutoCancel(true);

notification = builder.build();
notification.flags = Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_AUTO_CANCEL;

return notification;
}
}


And NO,i do not want to use neither firebase nor any 3rd party made ones as i am using one now and i suffer from delays,from non-received notifications and etc,and i will make my own small one ways better. Thanks everyone for you'r time and patience.










share|improve this question




















  • 2




    hmm i guess i have asked really horrible question huh? No one even closer tried to asnwer or give a smallest hint at all
    – Volo Apps
    Feb 13 '17 at 21:32










  • Hi Volo, I too facing exactly same issue did you found any way to achieve it,if so can you share it as your own answer,Thank you in advance.
    – Shylendra Madda
    Jun 15 '17 at 3:23










  • Find complete server and client side solution here stackoverflow.com/a/45099689/5063805
    – JosephM
    Jul 14 '17 at 9:49













up vote
3
down vote

favorite
1









up vote
3
down vote

favorite
1






1





Good day. I have a very specific issue considering the Socket IO library for android and it's service.



Important to mention that my device is huawei p8 lite which i am testing on.



Here it goes :



• I have a socket Io library which is being initialized inside the service i have created



• I set the listener to the socket io for new messages



• Everything works like a char if the application is not killed within the process trey by the user.



• The purpose of service was to keep the socket IO connection alive even if the application is killed so the user will be notified about new messages.



• As soon as the application is being killed,the Socket IO connection has been disconnected



No matter what i try,and i try all of possible ways : Isolating the process of Service,giving another process for the service,Starting it sticky,starting it not sticky recreating as soon as the service destroys and etc.



The only thing which has worked is the startForeground() method,but i do not want to use it as it will go under the design principles and plus i do not want to show any notification about the running service.



My question is the next : Can anyone help me out and tell me how can i keep the Socket IO connection alive even if the application is killed?



Here is the code of the service.



package com.github.nkzawa.socketio.androidchat;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import java.net.URISyntaxException;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class SocketService extends Service {
private Socket mSocket;
public static final String TAG = SocketService.class.getSimpleName();

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw null;
}

@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "on created", Toast.LENGTH_SHORT).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "start command", Toast.LENGTH_SHORT).show();
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
mSocket.on("newMessageReceived", onNewMessage);
mSocket.connect();
return START_STICKY;
}

private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(Object... args) {
String message = args[0].toString();
Log.d(TAG, "call: new message ");
sendGeneralNotification(getApplicationContext(), "1", "new message", message, null);
}
};

private void sendGeneralNotification(Context context, String uniqueId,
String title, String contentText,
@Nullable Class<?> resultClass) {

NotificationManager notificationManagerCompat = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(context);
builder.setAutoCancel(true);


builder.setContentTitle(title);
builder.setContentText(contentText);
builder.setGroup("faskfjasfa");
builder.setDefaults(android.app.Notification.DEFAULT_ALL);
builder.setStyle(new NotificationCompat.BigTextStyle()
.setSummaryText(title)
.setBigContentTitle(title)
.bigText(contentText)
);

Intent requestsViewIntent = new Intent(context, MainActivity.class);
requestsViewIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
requestsViewIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent requestsViewPending = PendingIntent.getActivity(context, Integer.valueOf(uniqueId), requestsViewIntent, 0);
builder.setContentIntent(requestsViewPending);
builder.setSmallIcon(R.drawable.ic_launcher);

builder.setShowWhen(true);
android.app.Notification notification = builder.build();
notificationManagerCompat.notify(Integer.valueOf(uniqueId), notification);
}

private Notification getNotification() {
Notification notification;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setColor(getResources()
.getColor(R.color.material_deep_teal_500))
.setAutoCancel(true);

notification = builder.build();
notification.flags = Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_AUTO_CANCEL;

return notification;
}
}


And NO,i do not want to use neither firebase nor any 3rd party made ones as i am using one now and i suffer from delays,from non-received notifications and etc,and i will make my own small one ways better. Thanks everyone for you'r time and patience.










share|improve this question















Good day. I have a very specific issue considering the Socket IO library for android and it's service.



Important to mention that my device is huawei p8 lite which i am testing on.



Here it goes :



• I have a socket Io library which is being initialized inside the service i have created



• I set the listener to the socket io for new messages



• Everything works like a char if the application is not killed within the process trey by the user.



• The purpose of service was to keep the socket IO connection alive even if the application is killed so the user will be notified about new messages.



• As soon as the application is being killed,the Socket IO connection has been disconnected



No matter what i try,and i try all of possible ways : Isolating the process of Service,giving another process for the service,Starting it sticky,starting it not sticky recreating as soon as the service destroys and etc.



The only thing which has worked is the startForeground() method,but i do not want to use it as it will go under the design principles and plus i do not want to show any notification about the running service.



My question is the next : Can anyone help me out and tell me how can i keep the Socket IO connection alive even if the application is killed?



Here is the code of the service.



package com.github.nkzawa.socketio.androidchat;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import java.net.URISyntaxException;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class SocketService extends Service {
private Socket mSocket;
public static final String TAG = SocketService.class.getSimpleName();

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw null;
}

@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "on created", Toast.LENGTH_SHORT).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "start command", Toast.LENGTH_SHORT).show();
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
mSocket.on("newMessageReceived", onNewMessage);
mSocket.connect();
return START_STICKY;
}

private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(Object... args) {
String message = args[0].toString();
Log.d(TAG, "call: new message ");
sendGeneralNotification(getApplicationContext(), "1", "new message", message, null);
}
};

private void sendGeneralNotification(Context context, String uniqueId,
String title, String contentText,
@Nullable Class<?> resultClass) {

NotificationManager notificationManagerCompat = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(context);
builder.setAutoCancel(true);


builder.setContentTitle(title);
builder.setContentText(contentText);
builder.setGroup("faskfjasfa");
builder.setDefaults(android.app.Notification.DEFAULT_ALL);
builder.setStyle(new NotificationCompat.BigTextStyle()
.setSummaryText(title)
.setBigContentTitle(title)
.bigText(contentText)
);

Intent requestsViewIntent = new Intent(context, MainActivity.class);
requestsViewIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
requestsViewIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent requestsViewPending = PendingIntent.getActivity(context, Integer.valueOf(uniqueId), requestsViewIntent, 0);
builder.setContentIntent(requestsViewPending);
builder.setSmallIcon(R.drawable.ic_launcher);

builder.setShowWhen(true);
android.app.Notification notification = builder.build();
notificationManagerCompat.notify(Integer.valueOf(uniqueId), notification);
}

private Notification getNotification() {
Notification notification;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setColor(getResources()
.getColor(R.color.material_deep_teal_500))
.setAutoCancel(true);

notification = builder.build();
notification.flags = Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_AUTO_CANCEL;

return notification;
}
}


And NO,i do not want to use neither firebase nor any 3rd party made ones as i am using one now and i suffer from delays,from non-received notifications and etc,and i will make my own small one ways better. Thanks everyone for you'r time and patience.







android sockets service threadpool background-task






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 13 '17 at 20:06

























asked Feb 13 '17 at 19:58









Volo Apps

658




658








  • 2




    hmm i guess i have asked really horrible question huh? No one even closer tried to asnwer or give a smallest hint at all
    – Volo Apps
    Feb 13 '17 at 21:32










  • Hi Volo, I too facing exactly same issue did you found any way to achieve it,if so can you share it as your own answer,Thank you in advance.
    – Shylendra Madda
    Jun 15 '17 at 3:23










  • Find complete server and client side solution here stackoverflow.com/a/45099689/5063805
    – JosephM
    Jul 14 '17 at 9:49














  • 2




    hmm i guess i have asked really horrible question huh? No one even closer tried to asnwer or give a smallest hint at all
    – Volo Apps
    Feb 13 '17 at 21:32










  • Hi Volo, I too facing exactly same issue did you found any way to achieve it,if so can you share it as your own answer,Thank you in advance.
    – Shylendra Madda
    Jun 15 '17 at 3:23










  • Find complete server and client side solution here stackoverflow.com/a/45099689/5063805
    – JosephM
    Jul 14 '17 at 9:49








2




2




hmm i guess i have asked really horrible question huh? No one even closer tried to asnwer or give a smallest hint at all
– Volo Apps
Feb 13 '17 at 21:32




hmm i guess i have asked really horrible question huh? No one even closer tried to asnwer or give a smallest hint at all
– Volo Apps
Feb 13 '17 at 21:32












Hi Volo, I too facing exactly same issue did you found any way to achieve it,if so can you share it as your own answer,Thank you in advance.
– Shylendra Madda
Jun 15 '17 at 3:23




Hi Volo, I too facing exactly same issue did you found any way to achieve it,if so can you share it as your own answer,Thank you in advance.
– Shylendra Madda
Jun 15 '17 at 3:23












Find complete server and client side solution here stackoverflow.com/a/45099689/5063805
– JosephM
Jul 14 '17 at 9:49




Find complete server and client side solution here stackoverflow.com/a/45099689/5063805
– JosephM
Jul 14 '17 at 9:49












3 Answers
3






active

oldest

votes

















up vote
0
down vote













Sorry that no one quickly replied to your question. I hope valentines 2018 will not be spent in suffering for others.



Implementing Socket.io in the background IS NOT the best of ideas. Socket.io has an active ping to your server. Using it for a short period is okay, but in the background it is a NO.



The best way to solve your problem is to combine Socket.io and FCM/GCM topics to emit a broadcast. On the users device, detect if there is an active Socket.io connection, if one exits ignore the FCM else execute the FCM.






share|improve this answer




























    up vote
    0
    down vote













    Implement this method in your service class and try with this.



    @Override
    public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);


    Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());

    restartServiceIntent.setPackage(getPackageName());
    restartServiceIntent.putExtra("NODE CONNECTED", true);
    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().
    getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
    AlarmManager.ELAPSED_REALTIME,
    SystemClock.elapsedRealtime() + 1000,
    restartServicePendingIntent);
    }


    this method will call when you kill the app and again restart your background service.






    share|improve this answer




























      up vote
      0
      down vote













      try this in the service:



      @Override
      public void onCreate() {
      super.onCreate();
      PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
      mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "systemService");
      mWakeLock.acquire();
      }


      and do not forget permission:



      <uses-permission android:name="android.permission.WAKE_LOCK" />





      share|improve this answer










      New contributor




      mazen Imara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.


















      • try this in the service , and do not forget permission : <uses-permission android:name="android.permission.WAKE_LOCK" />
        – mazen Imara
        Nov 10 at 15:40








      • 3




        Please add the explanation to your answer using the edit link
        – Nick
        Nov 11 at 2:20











      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42212484%2fsocket-io-with-android-service%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote













      Sorry that no one quickly replied to your question. I hope valentines 2018 will not be spent in suffering for others.



      Implementing Socket.io in the background IS NOT the best of ideas. Socket.io has an active ping to your server. Using it for a short period is okay, but in the background it is a NO.



      The best way to solve your problem is to combine Socket.io and FCM/GCM topics to emit a broadcast. On the users device, detect if there is an active Socket.io connection, if one exits ignore the FCM else execute the FCM.






      share|improve this answer

























        up vote
        0
        down vote













        Sorry that no one quickly replied to your question. I hope valentines 2018 will not be spent in suffering for others.



        Implementing Socket.io in the background IS NOT the best of ideas. Socket.io has an active ping to your server. Using it for a short period is okay, but in the background it is a NO.



        The best way to solve your problem is to combine Socket.io and FCM/GCM topics to emit a broadcast. On the users device, detect if there is an active Socket.io connection, if one exits ignore the FCM else execute the FCM.






        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          Sorry that no one quickly replied to your question. I hope valentines 2018 will not be spent in suffering for others.



          Implementing Socket.io in the background IS NOT the best of ideas. Socket.io has an active ping to your server. Using it for a short period is okay, but in the background it is a NO.



          The best way to solve your problem is to combine Socket.io and FCM/GCM topics to emit a broadcast. On the users device, detect if there is an active Socket.io connection, if one exits ignore the FCM else execute the FCM.






          share|improve this answer












          Sorry that no one quickly replied to your question. I hope valentines 2018 will not be spent in suffering for others.



          Implementing Socket.io in the background IS NOT the best of ideas. Socket.io has an active ping to your server. Using it for a short period is okay, but in the background it is a NO.



          The best way to solve your problem is to combine Socket.io and FCM/GCM topics to emit a broadcast. On the users device, detect if there is an active Socket.io connection, if one exits ignore the FCM else execute the FCM.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Feb 5 at 7:02









          Kennedy Nyaga

          2,55611719




          2,55611719
























              up vote
              0
              down vote













              Implement this method in your service class and try with this.



              @Override
              public void onTaskRemoved(Intent rootIntent) {
              super.onTaskRemoved(rootIntent);


              Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());

              restartServiceIntent.setPackage(getPackageName());
              restartServiceIntent.putExtra("NODE CONNECTED", true);
              PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
              AlarmManager alarmService = (AlarmManager) getApplicationContext().
              getSystemService(Context.ALARM_SERVICE);
              alarmService.set(
              AlarmManager.ELAPSED_REALTIME,
              SystemClock.elapsedRealtime() + 1000,
              restartServicePendingIntent);
              }


              this method will call when you kill the app and again restart your background service.






              share|improve this answer

























                up vote
                0
                down vote













                Implement this method in your service class and try with this.



                @Override
                public void onTaskRemoved(Intent rootIntent) {
                super.onTaskRemoved(rootIntent);


                Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());

                restartServiceIntent.setPackage(getPackageName());
                restartServiceIntent.putExtra("NODE CONNECTED", true);
                PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
                AlarmManager alarmService = (AlarmManager) getApplicationContext().
                getSystemService(Context.ALARM_SERVICE);
                alarmService.set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 1000,
                restartServicePendingIntent);
                }


                this method will call when you kill the app and again restart your background service.






                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Implement this method in your service class and try with this.



                  @Override
                  public void onTaskRemoved(Intent rootIntent) {
                  super.onTaskRemoved(rootIntent);


                  Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());

                  restartServiceIntent.setPackage(getPackageName());
                  restartServiceIntent.putExtra("NODE CONNECTED", true);
                  PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
                  AlarmManager alarmService = (AlarmManager) getApplicationContext().
                  getSystemService(Context.ALARM_SERVICE);
                  alarmService.set(
                  AlarmManager.ELAPSED_REALTIME,
                  SystemClock.elapsedRealtime() + 1000,
                  restartServicePendingIntent);
                  }


                  this method will call when you kill the app and again restart your background service.






                  share|improve this answer












                  Implement this method in your service class and try with this.



                  @Override
                  public void onTaskRemoved(Intent rootIntent) {
                  super.onTaskRemoved(rootIntent);


                  Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());

                  restartServiceIntent.setPackage(getPackageName());
                  restartServiceIntent.putExtra("NODE CONNECTED", true);
                  PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
                  AlarmManager alarmService = (AlarmManager) getApplicationContext().
                  getSystemService(Context.ALARM_SERVICE);
                  alarmService.set(
                  AlarmManager.ELAPSED_REALTIME,
                  SystemClock.elapsedRealtime() + 1000,
                  restartServicePendingIntent);
                  }


                  this method will call when you kill the app and again restart your background service.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 1 at 10:27









                  aj0822ArpitJoshi

                  661218




                  661218






















                      up vote
                      0
                      down vote













                      try this in the service:



                      @Override
                      public void onCreate() {
                      super.onCreate();
                      PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
                      mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "systemService");
                      mWakeLock.acquire();
                      }


                      and do not forget permission:



                      <uses-permission android:name="android.permission.WAKE_LOCK" />





                      share|improve this answer










                      New contributor




                      mazen Imara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.


















                      • try this in the service , and do not forget permission : <uses-permission android:name="android.permission.WAKE_LOCK" />
                        – mazen Imara
                        Nov 10 at 15:40








                      • 3




                        Please add the explanation to your answer using the edit link
                        – Nick
                        Nov 11 at 2:20















                      up vote
                      0
                      down vote













                      try this in the service:



                      @Override
                      public void onCreate() {
                      super.onCreate();
                      PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
                      mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "systemService");
                      mWakeLock.acquire();
                      }


                      and do not forget permission:



                      <uses-permission android:name="android.permission.WAKE_LOCK" />





                      share|improve this answer










                      New contributor




                      mazen Imara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.


















                      • try this in the service , and do not forget permission : <uses-permission android:name="android.permission.WAKE_LOCK" />
                        – mazen Imara
                        Nov 10 at 15:40








                      • 3




                        Please add the explanation to your answer using the edit link
                        – Nick
                        Nov 11 at 2:20













                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      try this in the service:



                      @Override
                      public void onCreate() {
                      super.onCreate();
                      PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
                      mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "systemService");
                      mWakeLock.acquire();
                      }


                      and do not forget permission:



                      <uses-permission android:name="android.permission.WAKE_LOCK" />





                      share|improve this answer










                      New contributor




                      mazen Imara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.









                      try this in the service:



                      @Override
                      public void onCreate() {
                      super.onCreate();
                      PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
                      mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "systemService");
                      mWakeLock.acquire();
                      }


                      and do not forget permission:



                      <uses-permission android:name="android.permission.WAKE_LOCK" />






                      share|improve this answer










                      New contributor




                      mazen Imara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.









                      share|improve this answer



                      share|improve this answer








                      edited Nov 11 at 20:08









                      jcubic

                      33k28116220




                      33k28116220






                      New contributor




                      mazen Imara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.









                      answered Nov 10 at 15:36









                      mazen Imara

                      11




                      11




                      New contributor




                      mazen Imara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.





                      New contributor





                      mazen Imara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.






                      mazen Imara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.












                      • try this in the service , and do not forget permission : <uses-permission android:name="android.permission.WAKE_LOCK" />
                        – mazen Imara
                        Nov 10 at 15:40








                      • 3




                        Please add the explanation to your answer using the edit link
                        – Nick
                        Nov 11 at 2:20


















                      • try this in the service , and do not forget permission : <uses-permission android:name="android.permission.WAKE_LOCK" />
                        – mazen Imara
                        Nov 10 at 15:40








                      • 3




                        Please add the explanation to your answer using the edit link
                        – Nick
                        Nov 11 at 2:20
















                      try this in the service , and do not forget permission : <uses-permission android:name="android.permission.WAKE_LOCK" />
                      – mazen Imara
                      Nov 10 at 15:40






                      try this in the service , and do not forget permission : <uses-permission android:name="android.permission.WAKE_LOCK" />
                      – mazen Imara
                      Nov 10 at 15:40






                      3




                      3




                      Please add the explanation to your answer using the edit link
                      – Nick
                      Nov 11 at 2:20




                      Please add the explanation to your answer using the edit link
                      – Nick
                      Nov 11 at 2:20


















                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42212484%2fsocket-io-with-android-service%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Full-time equivalent

                      さくらももこ

                      13 indicted, 8 arrested in Calif. drug cartel investigation