使用NotificationManager在Android服务中

3

我有一个在后台运行的服务,当有新数据时,我想通知用户。我已经使用了NotificationManager,通知出现了,但是当点击它时却没有任何反应(它应该显示一个活动)。我是Android方面的新手,以下是我的代码:

NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = newNotification(R.drawable.shoppingcarticon, "Nouvelle notification de ShopAlert", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.flags |= Notification.FLAG_AUTO_CANCEL;

Intent intent = new Intent(this,GooglemapActivity.class);
PendingIntent activity = PendingIntent.getService(this, 0, intent, 0);

notification.setLatestEventInfo(this, "This is the title", "This is the text", activity);
notification.number += 1;
notificationmanager.notify(0, notification);

your help will be appreciated.

2个回答

6
您可以使用此代码。将Main.Class更改为您的活动类,将标题和内容文本根据您的需要进行更改。
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);


int icon = R.drawable.ic_action_search;
CharSequence tickerText = "Pet Parrot";
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Context context = getApplicationContext();
CharSequence contentTitle = "Hungry!";
CharSequence contentText = "your parrot food meter is: ";
Intent notificationIntent = new Intent(context, Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

mNotificationManager.notify(1, notification); // Log.d("test", "Saving Data to File from Service.");

不起作用,谢谢你的帮助,但你确定这段代码在服务中也能正常工作吗? - Yasmine GreenApple
是的,这个可以运行,因为我从我的服务中复制了它。让我给你完整的代码,你可以随意使用。请勿编辑我的回答。 - Waqas
我该如何发送带有消息编号的通知,即徽章计数? - Karthick

3
以下是需要翻译的内容:

以下这一行:

PendingIntent activity = PendingIntent.getService(this, 0, intent, 0);

应该是这样的:

应该呈现为:

PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);

因为你试图启动一个 Activity,而不是一个 Service。希望这可以帮到你。


谢谢你的帮助,但它也不起作用,通知文本没有显示(在正常状态下,当我点击时,我有我的通知与通知栏,但这里的通知栏是空的)。 - Yasmine GreenApple
@Yasmine GreenApple,请确保代码确实被执行。顺便提一下,你正在使用的通知初始化模式已经过时了,请查看Notification.Builder类,因为它是构建通知的首选方式。 - Egor

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