0

I have a question about GcmListenerService.

I have a service which receives GCM messages:

public class MyGcmListener extends GcmListenerService {  

    @Override
    public  void onMessageReceived(String from, Bundle data) {
    Log.i("mytag", "message received");
    ....
    }
}

Usually the main activity of my app startes it:

 context.startService(new Intent(context, MyGcmListener.class));

But it seems that sometimes two service objects are created and a receiceive doubled log messages:

01-07 17:15:02.090    3655-3668/package: message received
01-07 17:15:02.090    3655-3668/package: message received

So I want to try if the service is already active when I start it from main activity:

if (!MyGcmService.isActive())
   context.startService(new Intent(context, MyGcmListener.class));

One of the solutions could be to make a variable boolean active which could be set true in onStartCommand() method and false - in onDestroy() (like here). But GcmListenerService does not have onStartCommand() method.

So how can I implement it? Have already seen such a problem?

Community
  • 1
  • 1
user2957954
  • 1,221
  • 2
  • 18
  • 39
  • When you use `startService`, in case service already exists it is not created twice, so you don't need to check whether it exists before starting it. As reported in `startService` spec: "If this service is not already running, it will be instantiated and started (creating a process for it if needed); if it is running then it remains running." – andrea.petreri Jan 07 '16 at 17:36
  • Why don't you use a broadcast receiver and intent service so you don't have to start the service? – Keith Jan 07 '16 at 18:14
  • @thetonrifles, yes it should be so, i also have read the specification. But in fact it receives messages twice as you can see – user2957954 Jan 08 '16 at 07:44
  • @Keith, I use the service that Google has recently recommended – user2957954 Jan 08 '16 at 07:44
  • 1
    Maybe [this](http://stackoverflow.com/questions/32137660/android-gcm-duplicate-push-after-notification-dismiss) could help. – andrea.petreri Jan 08 '16 at 08:51
  • I know that it could help, but without it I have the [following problem](http://stackoverflow.com/questions/33627053/how-to-run-gcmlistenerservice-in-foreground) - the service does not receive anything in an hour – user2957954 Jan 08 '16 at 09:03
  • Solving a problem the wrong way - creating another problem, that's not the way to go. – Tim Jan 08 '16 at 09:06

0 Answers0