OneSignal Push Notification Click to open actiivty

我只是一个虾纸丫 提交于 2019-12-06 02:07:42
Krunal Prajapati

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();

}

This means that context variable is null.

If you look in source code of Intent with picked construcor

public Intent(Context packageContext, Class<?> cls) {
    mComponent = new ComponentName(packageContext, cls);
}

And ComponentName construcor

public ComponentName(Context pkg, String cls) {
     if (cls == null) throw new NullPointerException("class name is null");
     mPackage = pkg.getPackageName(); //here you get crash
     mClass = cls;
 }

You can use DI to provide context, for example Dagger2.

Or implement application class

public class DemoApp extends Application {

    private static DemoApp instance;

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

    public static DemoApp getInstance() {
        return instance;
    }

}

And in your manifest

<application
        android:name=".demo.DemoApp"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!