how to know if the app was launched by clicking on the push notification

南楼画角 提交于 2021-01-27 16:11:44

问题


I want to know if there is a flag and parameter that can tell me if the user launched the activity/app by clicking on the push notification in the notification tray.

My code in C2DMReceiver.java

Context context = getApplicationContext();

        PackageManager manager = context.getPackageManager();
        Intent notificationIntent = manager
                .getLaunchIntentForPackage(packageName);
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        **notificationIntent.putExtra("fromRemote", true);**

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, 0);

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification();
        notification.icon = R.drawable.icon;
        notification.tickerText = message;
        notification.number = badge;
        notification.when = System.currentTimeMillis();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.defaults = Notification.DEFAULT_ALL;
        notification.setLatestEventInfo(context, "Draw Something", message,
                pendingIntent);
        notification.contentIntent = pendingIntent;
        notificationManager.notify(0, notification);

I tried setting

notificationIntent.putExtra("fromRemote", true);

but when the app was launched there were no extras in the intent.

my code in the onCreate function of my mainactivity

Bundle extras = getIntent().getExtras();
    if (extras != null) {
        print("onCreate - bundle has extras");
        for (String key: extras.keySet())
        {
          Log.v ("mytag", "MainActivity onCreate key =" + key);
        }
    }
    else {
        Log.v ("mytag", "onCreate - bundle has NO extras");
    }

The output i get is onCreate - bundle has NO extras. So the extras are not getting passed through.

So is there any other way?? It is so easy in iOS


回答1:


Just posting an answer so that people who visit this page get the solution.

You need to use putExtra(ID_KEY,id) when you create your Intent for starting your application, and in your onCreate() method you can use getIntent().getExtras().getInt(ID_KEY); to retrieve your passed id integer.

The passed extra could be anything, a boolean, String etc.

Source - https://stackoverflow.com/a/7358692/3036759



来源:https://stackoverflow.com/questions/22794570/how-to-know-if-the-app-was-launched-by-clicking-on-the-push-notification

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