OneSignal Push Notification Click to open activity

Krunal Prajapati picture Krunal Prajapati · Mar 25, 2017 · Viewed 7.4k times · Source

I have integrated one signal library for push notification. I want to open a particular activity from click of push notification while app is not running I am receiving push notification but while I am clicking on notification the app crashes. Here is my code for notification receiver

public class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler 
{

Context context;
@Override
public void notificationOpened(OSNotificationOpenResult result) {
    OSNotificationAction.ActionType actionType = result.action.type;
    JSONObject data = result.notification.payload.additionalData;
    String customKey;

    if (data != null) {
        customKey = data.optString("customkey", null);
        if (customKey != null)
            Log.e("OneSignalExample", "customkey set with value: " + customKey);
    }

    if (actionType == OSNotificationAction.ActionType.ActionTaken)
        Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);

     Intent intent = new Intent(context, User_Detail.class);
     intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
     context.startActivity(intent);
}

here is my error msg

Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

Answer

Krunal Prajapati picture Krunal Prajapati · Mar 25, 2017

I just missed to build constructor in class before onReceivedMethod

Context context2;

ExampleNotificationOpenedHandler(Context context) {
    context2 = context;
}

@Override
public void notificationOpened(OSNotificationOpenResult result) {
    OSNotificationAction.ActionType actionType = result.action.type;
    JSONObject data = result.notification.payload.additionalData;
    String customKey;

    Intent intent = new Intent(context2,User_Detail.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
    context2.startActivity(intent);


   if (data != null) {
        customKey = data.optString("customkey", null);
        if (customKey != null)
            Log.e("OneSignalExample", "customkey set with value: " + customKey);
    }

    if (actionType == OSNotificationAction.ActionType.ActionTaken)
    {
        Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);


    }

and also pass context in Application class

  @Override
public void onCreate() {
    super.onCreate();
    mInstance = this;


    OneSignal.startInit(this)
            .setNotificationOpenedHandler(new ExampleNotificationOpenedHandler(this))
            .init();

}