How to receive a message when the app is in backgr

2019-05-11 22:03发布

I'm very experienced on Unity and iOS and I can deploy my Unity app to Android. But I don't know anything about native Android stuff.

My problem is about receiving a GCM message and showing a notification when the android app is in background. I implemented it and it works perfect when the app is in foreground but my GCM message listener isn't being triggered when the app is in background and I can't show the notification.

I use this plugin for receiving GCM messages : https://github.com/kskkbys/unity-gcm I use this for showing the notification : https://www.assetstore.unity3d.com/en/#!/content/9484

I tried to reach out the authors of these plugins but they didn't reply for a long time...

2条回答
地球回转人心会变
2楼-- · 2019-05-11 22:39

I solved my problem by using "Android Native" plugin from StansAssets in asset store. With his implementation, android device shows a notification when the cloud message arrives even if the app is in the background. Tapping on the notification opens up the app.

查看更多
干净又极端
3楼-- · 2019-05-11 22:49

You may find the concept of the event bus interesting. I'll try and show you an example, although I've never used it with notifications before. I'll use Toast messages as a substitute, since that's what I'm comfortable with.

The idea is fairly simple, in that any object (activity) can "ride the bus":

bus.register(this)

The you need subscriber methods to run when the bus "beeps"(emits an event):

public void onEvent(NotificationEvent event) {
Toast.makeText(this, 
    event.payload.getString("message"), 
    LENGTH_SHORT)
.show();
}

The, when an object needs to alight the bus:

bus.unregister(this);

Also, to actually make the bus "beep":

NotificationEvent event = new NotificationEvent(bundle);
bus.post(event);

This triggers the call to the onEvent(NotificationEvent event) method in every object that has a seat on the bus. You can add different subscriber methods (such as onEvent(LocationEvent event)) and these method will only be run when an event of the same type is emitted bus.post(new LocationEvent()) There is no limit to how many objects can register with the bus.

With a small amount of modification, I see no reason why you can't adapt this to a notification method, and trigger events based on your program.

查看更多
登录 后发表回答