【问题标题】:How exactly to use Notification.Builder究竟如何使用 Notification.Builder
【发布时间】:2011-09-17 12:35:45
【问题描述】:

我发现我正在使用已弃用的方法进行通知 (notification.setLatestEventInfo())

它说要使用 Notification.Builder。

  • 如何使用它?

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

Notification.Builder cannot be resolved to a type

【问题讨论】:

标签: android api notifications deprecated


【解决方案1】:

Notification.Builder API 11NotificationCompat.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);

【讨论】:

  • 我看到 v4 支持包中有一种技术可以做到这一点:NotificationCompat.Builder
  • 我认为应该有人告诉 Google,他们在 Notification.Builder 文档页面中有严重的拼写错误。我按照他们说的做,但没有任何意义。我来到这里,看到它是不同的。我非常感谢您的回答,因为它让我意识到文档上的错误。
  • 文档说builder.getNotification() 已弃用。它说你应该使用builder.build()
  • NotificationBuilder.build() 需要 API 级别 16 或更高。 API 级别 11 和 15 之间的任何内容都应该使用 NotificationBuilder.getNotification()。
  • @MrTristan:如文档中所述,setSmallIcon()setContentTitle()setContentText() 是最低要求。
【解决方案2】:

This 在 API 11 中,因此如果您正在为 3.0 之前的版本进行开发,您应该继续使用旧的 API。

更新:NotificationCompat.Builder 类已添加到支持包中,因此我们可以使用它来支持 API 级别 v4 及更高版本:

http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html

【讨论】:

  • 谢谢。我想知道为什么它没有在功能页面本身上提到这一点
  • 是的:在我看来,弃用警告有点为时过早,但我知道什么。
【解决方案3】:

除了这里选择的答案之外,还有来自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);  
}  

【讨论】:

  • 使用新的 Compat 构建器的第一个代码已经实际运行。干得好!
  • 对我也很有效。两个注意事项:1)您需要为“ic_launcher”制作一个 32x32 的图标。透明背景上的白色绘图 2)您需要为 int FM_NOTIFICATION_ID = [yourFavoriteRandom]; 定义一些随机数;
  • 非常感谢,我的问题是:当我第二次点击通知时,前一个片段是打开的,而这一行“PendingIntent.FLAG_UPDATE_CURRENT”解决了我的问题,让我度过了愉快的一天
【解决方案4】:

Notification Builder 仅适用于 Android API 级别 11 及更高版本(Android 3.0 及更高版本)。

因此,如果您的目标不是 Honeycomb 平板电脑,则不应使用通知生成器,而应遵循以下example 之类的旧通知创建方法。

【讨论】:

  • 您可以使用兼容性库,因此您可以在 API 4 或更高版本上使用它。
【解决方案5】:

更新 android-N(2016 年 3 月)

请访问Notifications Updates链接了解更多详情。

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

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

这是一个预先存在的示例,它显示了一个简单的服务,该服务发送 使用 NotificationCompat 的通知。每个未读对话来自 用户作为不同的通知发送。

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

sample code.

【讨论】:

  • 您好,当我们使用 downloader_library 时,您能告诉我们如何让此方法在 Android 6.0 上运行。我在 Eclipse SDK - 25.1.7 ||可悲的是 ADT 23.0.X || Google APK 扩展库和许可库均为 1.0
【解决方案6】:

我在构建通知时遇到问题(仅针对 Android 4.0+ 开发)。 This link 准确地向我展示了我做错了什么,并说以下内容:

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()

基本上我错过了其中之一。作为对此进行故障排除的基础,请确保您至少拥有所有这些。希望这可以避免其他人头疼。

【讨论】:

  • 因此,如果您认为:“我稍后会找到一个图标”,您将不会收到任何通知。感谢这个 ;)
【解决方案7】:

即使在 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);

或者我建议关注这个优秀的tutorial

【讨论】:

    【解决方案8】:

    我用过

    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());
    

    【讨论】:

      【解决方案9】:

      以防万一它对任何人都有帮助...在针对较新的较旧 API 进行测试时,我在使用支持包设置通知时遇到了很多麻烦。我能够让他们在较新的设备上工作,但会在旧设备上进行错误测试。 最终让它为我工作的是删除与通知功能相关的所有导入。特别是 NotificationCompat 和 TaskStackBuilder。似乎在开始时设置我的代码时,导入是从较新的版本而不是从支持包中添加的。然后当我想稍后在 eclipse 中实现这些项目时,我没有被提示再次导入它们。希望这是有道理的,并且它可以帮助其他人:)

      【讨论】:

        【解决方案10】:
                  // This is a working Notification
               private static final int NotificID=01;
           b= (Button) findViewById(R.id.btn);
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
        
                    Notification notification=new       Notification.Builder(MainActivity.this)
                            .setContentTitle("Notification Title")
                            .setContentText("Notification Description")
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .build();
                    NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                    notification.flags |=Notification.FLAG_AUTO_CANCEL;
                    notificationManager.notify(NotificID,notification);
        
        
                }
            });
        }
        

        【讨论】:

          【解决方案11】:

          独立示例

          this answer 中的技术相同,但是:

          • 自包含:复制粘贴即可编译运行
          • 带有一个按钮,您可以根据需要生成任意数量的通知,并使用意图和通知 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://stackoverflow.com/a/35278871/895245
                                  // `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 中测试。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-04-16
            • 2019-08-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多