【问题标题】:using NotificationManager into an android service在 Android 服务中使用 NotificationManager
【发布时间】:2012-07-22 10:15:17
【问题描述】:

我有一个在后台运行的服务,如果有新数据,我想通知用户,我使用了一个通知管理器,通知出现了,但是当点击它时它什么也没做(它是应该显示一个活动 我是 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);

您的帮助将不胜感激。

【问题讨论】:

    标签: android service notificationmanager


    【解决方案1】:

    您可以使用此代码。将 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.");
    

    【讨论】:

    • 也不起作用,感谢您的帮助,但您确定此代码甚至可以用于服务吗?
    • 是的,这行得通,因为我从我的服务中复制了它。让我给你完整的代码,你可以随心所欲地使用它。编辑我的答案
    • 如何发送带有消息编号的通知,即徽章计数?
    【解决方案2】:

    下面一行:

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

    应该是这样的:

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

    因为您尝试启动Activity,而不是Service。希望这会有所帮助。

    【讨论】:

    • 谢谢你的帮助,但它也不起作用,通知文本不显示(在正常状态下,当我点击时,我的通知栏有我的通知,但这里通知栏为空)
    • @Yasmine GreenApple,确保代码确实被执行。顺便说一句,您使用的通知初始化模式已被弃用,请查看 Notification.Builder 类,因为它是现在构建通知的首选方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    相关资源
    最近更新 更多