Android: 在服务类中使用intent.putExtra获取通知

5
这是我在 Service 类中的 showNotification 方法:
private void showNotification() {

Notification notification = new Notification(R.drawable.icon,
"New Notification", System.currentTimeMillis());

Intent i = new Intent(this, myActivity.class);
i.putExtra("notification", "MyNotif");
i.putExtra("notifiedby", "NotedBy");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
notification.setLatestEventInfo(this, "NotedBy", "MyNotif", contentIntent);
nm.notify(111, notification);
}

因此,在从状态栏中点击“通知”后,我会进入“myActivity”。

问题在于这些行在“myActivity”中始终返回false

this.getIntent().hasExtra("notification")
this.getIntent().hasExtra("notifiedby")

putExtra()在PendingIntent中无法使用吗?

1个回答

6

可以尝试使用以下代码:

String notification = getIntent().getStringExtra("notification");
String notifiedby = getIntent().getStringExtra("notifiedby");

是的,我也弄明白了。如果我移除“this”,它就可以正常工作。你有任何想法为什么会这样吗?谢谢。 - Archie.bpgc
1
我不知道你是如何处理你的代码的,但有时候 'this' 可能会引用错误的上下文。如果你没有提供任何东西,Android 将采用当前活动的默认上下文,这样你就可以得到正确的结果。 - Anup Cowkur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接