Reputation: 21
I am getting notification using this through OneSignal
, but I want to open the application when I click on notification
private static class ExampleNotificationOpenedHandler implements OneSignal.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();
}
Upvotes: 2
Views: 6746
Reputation: 672
In your OneSignalPushApplication class, initialize:
OneSignal.startInit(this)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.autoPromptLocation(true)
.init();
and declare ExampleNotificationOpenedHandler as:
private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
@Override
public void notificationOpened(OSNotificationOpenResult result) {
String title=result.notification.payload.title;
String desc=result.notification.payload.body;
Log.d("xiomi", "Received Title "+title);
Log.d("xiomi", "Received Desc "+desc);
Intent intent = new Intent(getApplicationContext(), YourMainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("push_title", title);
intent.putExtra("push_message", desc);
startActivity(intent);
}
}
Upvotes: 1
Reputation: 10309
Add a constructor in ExampleNotificationOpenedHandler
that takes context as a parameter
private Context mContext;
public ExampleNotificationOpenedHandler(Context context) {
mContext = context;
}
Init OneSignal
with ExampleNotificationOpenedHandler
constructor with context inside application class
public void onCreate() {
super.onCreate();
OneSignal.startInit(this)
.setNotificationOpenedHandler((OneSignal.NotificationOpenedHandler)
new ExampleNotificationOpenedHandler(this))
.init();
}
Prepare intent and start your activity using context
@Override
public void notificationOpened(OSNotificationOpenResult result) {
try {
if (additionalData != null) {
Intent intent = new Intent(mContext, DetailsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("key", <additionalData to be sent>);
mContext.startActivity(intent);
}
} catch (Throwable t) {
t.printStackTrace();
}
Upvotes: 7