如何准确地使用Notification.Builder

105

我发现我在使用通知(notification)时使用了一个已弃用的方法(notification.setLatestEventInfo())。

它建议使用Notification.Builder。

  • 我该如何使用它?

当我尝试创建一个新实例时,它告诉我:

Notification.Builder cannot be resolved to a type

我注意到这个链接从API Level 11(Android 3.0)开始可用。 - mobiledev Alex
请查看以下更新的答案:(链接) - Amit Vaghela
11个回答

152

Notification.Builder API 11 或者 NotificationCompat.Builder API 1

这是一个用法示例。

Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
        YOUR_PI_REQ_CODE, notificationIntent,
        PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) ctx
        .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);

builder.setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.some_img)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
            .setTicker(res.getString(R.string.your_ticker))
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle(res.getString(R.string.your_notif_title))
            .setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();

nm.notify(YOUR_NOTIF_ID, n);

13
我看到在v4支持包中有一种技术可以实现这一点:NotificationCompat.Builder。 - stanlick
6
我认为应该有人告诉谷歌他们在“Notification.Builder”文档页面中有严重的错别字。我照着文档操作,但是感觉讲解不太合理。后来我来到这里发现有所不同。非常感谢你的回答,它让我意识到了文档上的错误。 - Andy
5
文档显示 builder.getNotification() 已经被弃用,建议使用 builder.build() - mneri
26
NotificationBuilder.build() 需要 API Level 16 或更高版本。对于 API Level 11 至 15 之间的版本,应使用 NotificationBuilder.getNotification()。 - Camille Sévigny
4
如文档所述,setSmallIcon()setContentTitle()setContentText()是最低要求。 - caw
显示剩余7条评论

86

谢谢。我想知道为什么函数页面本身没有提到这一点。 - Saariko
15
是的,我认为这个弃用警告有点过早了,但我又能知道什么呢。 - Femi

70

除了所选答案之外,这里还提供了一些来自Source TricksNotificationCompat.Builder类示例代码:

// Add app running notification  

    private void addNotification() {



    NotificationCompat.Builder builder =  
            new NotificationCompat.Builder(this)  
            .setSmallIcon(R.drawable.ic_launcher)  
            .setContentTitle("Notifications Example")  
            .setContentText("This is a test notification");  

    Intent notificationIntent = new Intent(this, MainActivity.class);  
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
            PendingIntent.FLAG_UPDATE_CURRENT);  
    builder.setContentIntent(contentIntent);  

    // Add as notification  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.notify(FM_NOTIFICATION_ID, builder.build());  
}  

// Remove notification  
private void removeNotification() {  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.cancel(FM_NOTIFICATION_ID);  
}  

5
使用新的Compat构建器编写的第一个可以正常工作的代码。干得好! - James MV
1
对我也很有效。两个注意事项: 1)您需要为“ic_launcher”制作一个32x32的图标。白色绘画在透明背景上。 2)您需要为int FM_NOTIFICATION_ID = [yourFavoriteRandom]定义一些随机数。 - Anders8
1
非常感谢,我的问题是:当我第二次点击通知时,之前的片段仍然打开,而这行“PendingIntent.FLAG_UPDATE_CURRENT”解决了我的问题,让我的一天变得美好。 - Shruti

4

通知构建器仅适用于Android API Level 11及以上版本(Android 3.0及以上版本)。

因此,如果您不是针对蜂窝平板电脑进行开发,您就不应该使用通知构建器,而是遵循旧的通知创建方法,例如以下示例


4
你可以使用兼容性库,这样你就可以在 Android 4 或更高版本上使用它。 - Leandros

3

更新 Android-N (2016年3月)

请访问通知更新链接了解更多详情。

  • 直接回复
  • 捆绑通知
  • 自定义视图

Android N 还允许您将类似的通知捆绑在一起,以显示为单个通知。为了实现这一点,Android N 使用现有的 NotificationCompat.Builder.setGroup() 方法。用户可以展开每个通知,并从通知栏逐个执行操作,例如回复和忽略。

这是一个现有的示例,它显示一个简单的服务,使用 NotificationCompat 发送通知。来自用户的每个未读会话都作为不同的通知发送。

此示例已更新,以利用 Android N 中可用的新通知功能。

示例代码


你好,能否告诉我如何在使用downloader_library时使该方法在Android 6.0上工作。 我正在使用Eclipse SDK - 25.1.7 || ADT 23.0.X(遗憾的是)|| Google APK扩展库和许可证库都是1.0版本。 - mfaisalhyder

2
即使在API 8中也可以工作,您可以使用以下代码:

 Notification n = 
   new Notification(R.drawable.yourownpicturehere, getString(R.string.noticeMe), 
System.currentTimeMillis());

PendingIntent i=PendingIntent.getActivity(this, 0,
             new Intent(this, NotifyActivity.class),
                               0);
n.setLatestEventInfo(getApplicationContext(), getString(R.string.title), getString(R.string.message), i);
n.number=++count;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.flags |= Notification.DEFAULT_SOUND;
n.flags |= Notification.DEFAULT_VIBRATE;
n.ledARGB = 0xff0000ff;
n.flags |= Notification.FLAG_SHOW_LIGHTS;

// Now invoke the Notification Service
String notifService = Context.NOTIFICATION_SERVICE;
NotificationManager mgr = 
   (NotificationManager) getSystemService(notifService);
mgr.notify(NOTIFICATION_ID, n);

或者我建议您跟随一个关于此的优秀教程


2

我曾使用过

Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase Push Notification")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());

2

我在构建通知时遇到了问题(仅针对Android 4.0+进行开发)。 这个链接向我展示了我所做错误并表明如下:

Required notification contents

A Notification object must contain the following:

A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()

基本上我缺少其中之一。为了解决这个问题,请确保你至少拥有所有这些内容,这是故障排除的基础。希望这能帮助其他人避免头痛。


所以如果你认为:“我稍后再找图标”,那么你将不会收到任何通知和爱。谢谢这一个。 ;) - Nanne

1
如果有人需要帮助...我在测试新旧API时,使用支持包设置通知时遇到了很多问题。我能够让它们在较新的设备上工作,但在旧设备上测试时会出现错误。 最终让它对我起作用的是删除所有与通知函数相关的导入。特别是NotificationCompat和TaskStackBuilder。似乎在一开始设置我的代码时,导入来自较新版本而不是支持包。然后当我想在eclipse中稍后实现这些项目时,我没有被提示再次导入它们。希望这有意义,并且能帮助其他人 :)

0

自包含示例

此答案中相同的技术,但:

  • 自包含:复制粘贴即可编译和运行
  • 带有一个按钮,供您生成任意数量的通知并使用意图和通知ID进行操作

来源:

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main extends Activity {
    private int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Button button = new Button(this);
        button.setText("click me");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Notification notification = new Notification.Builder(Main.this)
                        /* Make app open when you click on the notification. */
                        .setContentIntent(PendingIntent.getActivity(
                                Main.this,
                                Main.this.i,
                                new Intent(Main.this, Main.class),
                                PendingIntent.FLAG_CANCEL_CURRENT))
                        .setContentTitle("title")
                        .setAutoCancel(true)
                        .setContentText(String.format("id = %d", Main.this.i))
                        // Starting on Android 5, only the alpha channel of the image matters.
                        // https://dev59.com/wl4c5IYBdhLWcg3wCGf2#35278871
                        // `android.R.drawable` resources all seem suitable.
                        .setSmallIcon(android.R.drawable.star_on)
                        // Color of the background on which the alpha image wil drawn white.
                        .setColor(Color.RED)
                        .build();
                final NotificationManager notificationManager =
                        (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(Main.this.i, notification);
                // If the same ID were used twice, the second notification would replace the first one. 
                //notificationManager.notify(0, notification);
                Main.this.i++;
            }
        });
        this.setContentView(button);
    }
}

已在Android 22上进行测试。


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