Handling custom payloads in OneSignal notification - android

I have integrated OneSignal in to my android app to use for push notifications, all is working fine and the notifications come through. However what do i need to change in order to handle these notifications in a custom manner? The receiver needs to parse the JSON payload from the notification and send the user to the correct point in the app based on what is received.

You need to setup a NotificationOpenedHandler class to handle the opening of a notification. See the following example code to set it up.
import com.onesignal.OneSignal;
public class YourAppClass extends Application {
#Override
public void onCreate() {
super.onCreate();
OneSignal.startInit(this)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.init();
}
// This fires when a notification is opened by tapping on it or one is received while the app is running.
private class ExampleNotificationOpenedHandler implements NotificationOpenedHandler {
#Override
public void notificationOpened(String message, JSONObject additionalData, boolean isActive) {
try {
if (additionalData != null) {
if (additionalData.has("actionSelected"))
Log.d("OneSignalExample", "OneSignal notification button with id " + additionalData.getString("actionSelected") + " pressed");
Log.d("OneSignalExample", "Full additionalData:\n" + additionalData.toString());
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
If you need to change which Activity is started when your app is opened see the OneSignal Changing the open action of a notification instructions.

Related

How can I completely unsubscribe from getting push notifications?

In my application I have implemented Push Notification functionality.
I added a button for the user, which allows him to turn off the notification completely. However it doesn't work as I excpected. Here's the code snippet:
From MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseMessaging.getInstance().subscribeToTopic("test_topic");
((SwitchCompat)findViewById(R.id.notification_switch)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
Toast.makeText(MainActivity.this, "Switch activated ", Toast.LENGTH_LONG).show();
FirebaseMessaging.getInstance().subscribeToTopic("test_topic");
}else {
Toast.makeText(MainActivity.this, "Switch deactivated ", Toast.LENGTH_LONG).show();
FirebaseMessaging.getInstance().unsubscribeFromTopic("test_topic");
new Thread(new Runnable() {
#Override
public void run() {
try {
FirebaseInstanceId.getInstance().deleteInstanceId();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
});
}
FirebaseMessagingService class to handle the message:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static String TAG = MyFirebaseMessagingService.class.getName();
#Override
public void onMessageReceived(RemoteMessage remoteMessage){
super.onMessageReceived(remoteMessage);
Log.e(TAG, "onMessageReceived() --> " + remoteMessage.getNotification().getTitle());
}
// #Override
// public void onNewToken(String s) {
// super.onNewToken(s);
// Log.e(TAG, "onNewToken() --> " + s);
// }
}
When I try to send a notification using topic I don't get any notification. If I send the notification to all devices with the app, I still get the notification. How can I completely prevent my app from getting notifications?
Unregistration and Unsubscription
There are three methods a client app can use to stop receiving messages and/or topic subscriptions from the app server:
InstanceID deleteToken() with audience set to the app server's sender ID and scope set to GCM. This stops messages (including topic messages) from a specific app server
InstanceID deleteID(). This stops messages from all previous registrations and topic subscriptions for all app servers
GCMPubSub unsubscribe(). This stops topic messages from the specific topic of the app server
For FCM, it should be the FirebaseInstanceId.
Try to set setAutoInitEnabled(false) before FirebaseInstanceId.getInstance().deleteInstanceId().
When enabled, FCM generates a registration token on app startup if there is no valid one and generates a new token when it is deleted (which prevents deleteInstanceId() from stopping the periodic sending of data). This setting is persisted across app restarts and overrides the setting specified in your manifest.
By default, FCM auto-initialization is enabled.
For more information: FirebaseMessaging

FirebaseMessagingService Intercept notifications when app closed

can i intercept notifications when my app is closed?
I need for set badge with this library ShortcutBadger
Thanks.
There are 3 types of notifications:
notification: Can be send from the web console or any backend, it has predefines values. If the app is open the behaviour is customizable on onMessageRecieve if the app is closed triggers a default notification.
data: a key value pair, only Strings. Can be send from any backend. The behaviour is always defined in onMessageReceived method.
notification and data: Combination of previous it will have the behaviour of a notification, the data will be available as extras once the notification is clicked in the default launcher activity. Can be send from the web console or any backend.
A push is a json called Payload which contains those objects:
payload: {
data: {...}
}
Yes, you can send yourself a data type notification it will always do what you write in the onMessageReceived method inside the MessagingService.
This doc should help you
https://firebase.google.com/docs/cloud-messaging/concept-options?hl=es-419
If you dont have a server use Functions.
Since the default notification wont be shown, you will probably want to show your own.
If you want to also show a notification then the NotificationCompat class must be called from inside onMessageReceived. The visual notification is not related to the push message, in fact, a visual notification can be triggered by pressing a button.
For creating a visual notification, the best approach is to let Android Studio do it for you. Second click on the packages where your activities .java are, new, then selecet ui-component and there is the notification. It will create a basic template of a notification. Then use those methods inside onMessaReceived passing the info that has to be show to the user.
The docs about the class
https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html
And you will probably find this error
NotificationCompat.Builder deprecated in Android O
In case you never solved this, the problem is not how you are implementing it within your app, but how the JSON data payload is being sent. See this question and the respective answers for why you are not receiving the messages while they are in the background.
Very short summary is, if you are receiving the notification payload, it will never trigger in the background. If you receive the data payload without notification, you can parse and perform actions while the app is in the background.
do you mean it?
public class AppFcmMessagingsService extends FirebaseMessagingService {
private static final String TAG = "FirebaseMessageService";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
try {
if(remoteMessage.getData().size() > 0) {
final JSONObject jsonObject = new JSONObject(remoteMessage.getData().toString());
Log.d(TAG,"remoteMessage = " + jsonObject.toString());
int badgeCount = 1;
ShortcutBadger.applyCount(getApplicationContext(), badgeCount);
}
} catch (Exception e) {
Log.e(TAG, "onMessageReceived: ", e);
}
if(remoteMessage.getNotification() != null) {
int badgeCount = 1;
ShortcutBadger.applyCount(getApplicationContext(), badgeCount);
Log.d(TAG, "notification body : " + remoteMessage.getNotification().getBody());
}
}
}

How to show Parse Push Notification in notification bar while application is running?

I am using Parse to do push notifications and the issue I am running into is that while my application is running (either in the foreground or background) the phone's operating system does not show the push notification in the notification bar. What changes to my implementation do I need to make to see the push display on the notification bar?
My extended Application class has the following in onCreate()
// initialize Parse SDK
Parse.initialize(this, Constants.APPLICATION_ID_DEBUG, Constants.CLIENT_KEY_DEBUG);
ParsePush.subscribeInBackground(Constants.CHANNEL, new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Logger.i(TAG, "successfully subscribed to broadcast channel");
} else {
Logger.e(TAG, "failed to subscribe for push: " + e);
}
}
});
ParseInstallation.getCurrentInstallation().saveInBackground();
I have a sign in system for my app, so I am using the ID of the logged in user as the Channel to subscribe users to. So in the first Activity of my app I call the following code snippet in onCreate().
private void registerNotifications() {
List<String> arryChannel = new ArrayList<String>();
arryChannel.add(session.id);
ParseInstallation parseInstallation = ParseInstallation.getCurrentInstallation();
parseInstallation.put("channels", arryChannel);
parseInstallation.saveEventually();
}
I also have a custom receiver that is working. Each time a push is sent out, it is being received by the onPushReceive method, however, I want the push to display in the notification bar.
public class ParsePushReceiver extends ParsePushBroadcastReceiver {
private static final String TAG = ParsePushReceiver.class.getSimpleName();
#Override
public void onPushOpen(Context context, Intent intent) {
Log.i(TAG, "onPushOpen");
}
#Override
protected void onPushReceive(Context context, Intent intent) {
Log.i(TAG, "onPushReceive");
}
}
Thanks in advance!
Just remove the onPushReceive method and the default behaviour will remain (show the notification in the status bar.
You are getting this behaviour because if the application is running the Parse Push notification will call the method onPushReceive that does nothing.
I have figured this out. Although the answer provided by Sandra will make a push notification appear on the notification bar, it is not connected to Parse.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
This causes issues, because if you click on that notification the receiver you create extending ParsePushBroadcastReceiver will not register onPushOpen. My implementation for everything was correct, I only needed to add
super.onPushReceive(context, intent);
That will make the notification appear on the notification bar and also register clicks.
So make sure to make your receiver looks like this (at minimum)
public class ParsePushReceiver extends ParsePushBroadcastReceiver {
private static final String TAG = ParsePushReceiver.class.getSimpleName();
#Override
public void onPushOpen(Context context, Intent intent) {
Log.i(TAG, "onPushOpen");
}
#Override
protected void onPushReceive(Context context, Intent intent) {
Log.i(TAG, "onPushReceive");
**super.onPushReceive(context, intent);**
}
}

Parse Push Notifications Android to appear once the app is opened

I have done a lot of reading on Parse push notifications. I have push notifications working perfectly if the app is running or sitting in the background (user gets out of the app by pushing the home button or back button). I know I cannot get notifications to appear if the app has been force quit but if I close the app/force quit the app, is there a way to get the notifications to pop up the next time the app opens?
I have implemented MainApplication and made sure my manifest is correct but if the app is completely closed, then I do a push notification from Parse and then go to open the app it is as if it has not received it and never will display. Is that normal behavior?
Thanks,
Adam
Main Application
public class MainApplication extends Application {
private static MainApplication instance = new MainApplication();
public MainApplication()
{
instance=this;
}
public static Context getContext()
{
return instance;
}
#Override
public void onCreate() {
super.onCreate();
Parse.enableLocalDatastore(this);
//initialise whatson from parse.com
Parse.initialize(this, "xxxxx", "xxxxx");
PushService.setDefaultPushCallback(this, MainActivity.class);
//to register device to get push notifications and register the install
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
ParseInstallation.getCurrentInstallation().saveInBackground();
}
}

Notification received but not showing

I'm adding Urban Airship push notifications to my Android app. My custom BroadcastReceiver is receiving the notifications when I send a test push. Here's the onReceive() method.
public class IntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent == null)
return;
String action = intent.getAction();
if (action.equals(PushManager.ACTION_PUSH_RECEIVED)) {
int id = intent.getIntExtra(PushManager.EXTRA_NOTIFICATION_ID, 0); //Breakpoint here
Log.w("my app", "Received push notification. Alert: "
+ intent.getStringExtra(PushManager.EXTRA_ALERT)
+ " [NotificationID="+id+"]");
logPushExtras(intent);
} else if (action.equals(PushManager.ACTION_NOTIFICATION_OPENED)) {
//Other stuff here
}
Execution stops at the breakpoint (position shown in the comment) and the details are logged.
No notification is shown in the notification area though. In my other app with UA push notifications, I think this was all I did, but it doesn't seem to be working this time.
I suspect I've done something wrong in my manifest file or that I've forgotten to implement a class somewhere.
Any ideas?
Extra Info
Extended Application:
public class ExtendedApplication extends Application {
public void onCreate(){
AirshipConfigOptions options = AirshipConfigOptions.loadDefaultOptions(this);
UAirship.takeOff(this, options);
PushManager.enablePush();
PushPreferences prefs = PushManager.shared().getPreferences();
Log.e("my app", "My Application onCreate - App APID: " + prefs.getPushId());
PushManager.shared().setIntentReceiver(IntentReceiver.class);
}
}
Edit
I've tried adding
PushManager.shared().setNotificationBuilder(new BasicPushNotificationBuilder());
to my ExtendedApplication as suggested in this post.
I was sending a test push with a blank "Alert" field from the UA site. I tried with some text in there and now it works. I don't know why, but I don't think that's something that should fail silently.
Moral of the story: Don't leave your Alert field blank.

Categories

Resources