Skip to content Skip to sidebar Skip to footer

I Have A Service Gcm In The Background, How Do I Know If The App Is Open Or Not?

I have a class that extends GCMBaseIntentService, when I get a message from gcm function: @Override protected void onMessage (Context context, Intent intent) { String messag

Solution 1:

when a new message arrives the app recognize if the application is open and the user is using, or is a simple background service, and therefore I see a notification

To do that, you can use an in-process event bus. Have the service post an event to the bus. Have the UI subscribe to the bus for those events when the UI is in the foreground (e.g., register in onResume(), unregister in onPause()). Have the UI process the events when the UI gets them. If the UI does not respond to the event, the service can then raise a Notification.

I have sample apps that demonstrate this for three popular event bus implementations for Android:

Solution 2:

A pretty common approach to solving this problem is using an event bus to publish the message to the rest of your app to see if anyone is registered to handle it.

A good event bus for Android is the greenrobot EventBus https://github.com/greenrobot/EventBus

A code example of how to do it:

Create a class for your message

publicclassMessageEvent { 
    public message;

    publicMessageEvent(String message){
        this.message = message;
    }
}

Add the EventBus to your BroadcastReceiver

protectedvoidonMessage (Context context, Intent intent) {
    String message = intent.getExtras().getString("alien");

    MessageEvent event = new MessageEvent(message);

    EventBus.register(this);
    EventBus.getDefault().post(event)
}

publicvoidonEvent(NoSubscriberEvent event) {
    if (event.originalEvent instanceOf MessageEvent) {
        generateNotification(((MessageEvent) event.originalEvent).message));
    }
}

Then, in your Activity:

@OverridepublicvoidonStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@OverridepublicvoidonStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}

// This method will be called on the main thread when a MessageEvent is postedpublicvoidonEventMainThread(MessageEvent event){
    Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
}

This way, if your activity is active, it can process the MessageEvent, if it is not active, you can display the notification as usual.

Solution 3:

GCM runs completely at background and not in foreground.

<uses-permissionandroid:name="android.permission.WAKE_LOCK" /><uses-permissionandroid:name="com.google.android.c2dm.permission.RECEIVE" />

You will use these two permission's which is to receive the message at background.

Please read this.

https://developer.android.com/google/gcm/client.html

Post a Comment for "I Have A Service Gcm In The Background, How Do I Know If The App Is Open Or Not?"