如何通过点击推送通知来了解应用程序是否已启动

时间:2014-04-01 18:58:53

标签: android android-notifications

我想知道是否有标志和参数可以告诉我用户是否通过点击通知托盘中的推送通知启动了活动/应用。

我在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);

我尝试过设置

notificationIntent.putExtra("fromRemote", true);

但是当应用程序启动时,意图中没有额外内容。

我的主要活动的onCreate函数中的代码

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");
    }

我得到的输出是onCreate - bundle没有额外的东西。所以附加内容没有通过。

还有其他方法吗?它在iOS中非常容易

1 个答案:

答案 0 :(得分:2)

只需发布回答即可让访问此页面的人获得解决方案。

在创建启动应用程序的Intent时需要使用putExtra(ID_KEY,id),而在onCreate()方法中,您可以使用getIntent().getExtras().getInt(ID_KEY);来检索传递的id整数。

传递的额外内容可以是任何东西,布尔值,字符串等。

来源 - https://stackoverflow.com/a/7358692/3036759