I am implementing push notifications in my Android application. We are using OneSignal to send push notification. We have an API that keeps track of all the devices and API decides which devices to send push notification.
API requests OneSignal and OneSignal send a notification to the device.
From Android I get the device token using the following code which is saved on the API and it uses it to send push notifications.
public String getGCMTokenForPushNotification(){
String token = "";
try {
InstanceID instanceID = InstanceID.getInstance(this);
token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(TAG, "GCM Registration Token: " + token);
return token;
}catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
}
return token;
}
R.string.gcm_defaultSenderId is the SENDER ID on the firebase consle when Android app is registered there.
As of now I have OneSignal set up on the Android application using
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OneSignal.startInit(this)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.init();
}
https://documentation.onesignal.com/docs/android-sdk-setup
If API is deciding and initializing the device on onesignal and sending push notification. I dont think I will require OneSignal setup on android app. Is that right? If I remove OneSignalfrom the android app. what should I be using to handle notification coming through.
Reason behind is, as of now we are using OneSignal and in the future if we change the provider we dont have to do anything on the app side.
is there any geniric way to handle notifications on android please.
Thank you for your help. R
Yes you dont need to use onesignal on client. you can remove that. Onesignal document says that - Implementing reliable interfaces to the GCM/FCM (Google), APNS (Apple)
So basically its uses GCM/FCM, ideally you can directly use GCM/FCM if you dont have complex scenarios.
Answering your question you can use below thing to receive Push notification, because it comes from Google cloud only ultimately
GCM docs to receive notification message read document carefully you will get it.
This below method will get you you message
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
// ...
}
and you can implement GCM/FCM also using below documentation, if you wish to go ahead directly GCM Docs
But you should use FCM now, because GCM is deprecated now. So here you go FCM docs