繁体   English   中英

如何使用 NotificationCompat.Builder 创建通知?

[英]How to create a notification with NotificationCompat.Builder?

我需要创建一个简单的通知,如果可能的话,它将与声音和图标一起显示在通知栏中? 我还需要它与 Android 2.2 兼容,所以我发现 NotificationCompat.Builder 可以与 4 以上的所有 API 一起使用。如果有更好的解决方案,请随时提及。

NotificationCompat.Builder是在所有Android版本上创建Notifications的最简单方法。 您甚至可以使用Android 4.1提供的功能。 如果您的应用在Android> = 4.1的设备上运行,则会使用新功能,如果在Android <4.1上运行,则通知将是一个简单的旧通知。

要创建一个简单的通知,请执行此操作(请参阅Android API通知指南 ):

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!")
    .setContentIntent(pendingIntent); //Required on Gingerbread and below

您必须至少设置smallIconcontentTitlecontentText 如果您错过了一个通知将不会显示。

注意:在Gingerbread和下面你必须设置内容意图,否则将抛出IllegalArgumentException

要创建无效的intent,请使用:

final Intent emptyIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, NOT_USED, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

您可以通过构建器添加声音,即来自RingtoneManager的声音:

mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))

通知通过NotificationManager添加到栏中:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mId, mBuilder.build());

工作范例:

    Intent intent = new Intent(ctx, HomeActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder b = new NotificationCompat.Builder(ctx);

    b.setAutoCancel(true)
     .setDefaults(Notification.DEFAULT_ALL)
     .setWhen(System.currentTimeMillis())         
     .setSmallIcon(R.drawable.ic_launcher)
     .setTicker("Hearty365")            
     .setContentTitle("Default notification")
     .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
     .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
     .setContentIntent(contentIntent)
     .setContentInfo("Info");


    NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, b.build());

我制作这个方法并且工作正常。 (在android 6.0.1中测试过)

public void notifyThis(String title, String message) {
    NotificationCompat.Builder b = new NotificationCompat.Builder(this.context);
    b.setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.favicon32)
            .setTicker("{your tiny message}")
            .setContentTitle(title)
            .setContentText(message)
            .setContentInfo("INFO");

    NotificationManager nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(1, b.build());
}

在Android 8.0中显示Notificaton

@TargetApi(Build.VERSION_CODES.O)
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)

  public void show_Notification(){

    Intent intent=new Intent(getApplicationContext(),MainActivity.class);
    String CHANNEL_ID="MYCHANNEL";
    NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"name",NotificationManager.IMPORTANCE_LOW);
    PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
    Notification notification=new Notification.Builder(getApplicationContext(),CHANNEL_ID)
            .setContentText("Heading")
            .setContentTitle("subheading")
            .setContentIntent(pendingIntent)
            .addAction(android.R.drawable.sym_action_chat,"Title",pendingIntent)
            .setChannelId(CHANNEL_ID)
            .setSmallIcon(android.R.drawable.sym_action_chat)
            .build();

    NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
    notificationManager.notify(1,notification);


}

深入通知

Intent intent = new Intent(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.your_notification_icon)
                        .setContentTitle("Notification Title")
                        .setContentText("Notification ")
                        .setContentIntent(pendingIntent );

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());

深度知识

可以使用通知构建通知。 Builder或NotificationCompat.Builder类。
但是如果你想要向后兼容,你应该使用NotificationCompat.Builder类,因为它是v4支持库的一部分,因为它负责为API 4及更高版本的Notification提供一致的外观和功能。

核心通知属性

通知有4个核心属性(3个基本显示属性+ 1个单击操作属性)

  • 小图标
  • 标题
  • 文本
  • 按钮单击事件(点击通知时单击事件)

Android 3.0及更高版本上的按钮点击事件是可选的。 这意味着,如果您的minSdk定位到Android 3.0或更高版本,则只能使用显示属性来构建通知。 但是,如果您希望您的通知在比Android 3.0更旧的设备上运行,那么您必须提供Click事件,否则您将看到IllegalArgumentException。

通知显示

通过调用NotificationManger类的notify()方法显示通知

notify()参数

通知方法有两种变体

notify(String tag, int id, Notification notification)

要么

notify(int id, Notification notification)

notify方法采用整数id来唯一标识您的通知。 但是,您还可以提供可选的String标记,以便在发生冲突时进一步识别通知。

这种类型的冲突很少见,但是,您创建了一些库,其他开发人员正在使用您的库。 现在他们创建了自己的通知,不知怎的,您的通知和其他开发人员的通知ID是相同的,那么您将面临冲突。

API 11之后的通知(更多控制)

API 11提供了对通知行为的额外控制

  • 通知解雇
    默认情况下,如果用户点击通知,则它会执行指定的点击事件,但不会清除通知。 如果您希望在此时清除通知,则应添加此通知

    mBuilder.setAutoClear(真);

  • 防止用户解除通知
    用户也可以通过滑动来解除通知。 您可以在构建通知时添加此行为来禁用此默认行为

    mBuilder.setOngoing(真);

  • 通知的定位
    您可以通过设置通知的相对优先级

    mBuilder.setOngoing(int pri);

如果您的应用运行API低于11,那么您的通知将在没有上述附加功能的情况下运行。 这是通过Notification.Builder选择NotificationCompat.Builder的优势

API 16之后的通知(更多信息)

随着API 16的引入,通知被赋予了许多新功能
通知可以提供更多信息。
您可以在徽标中添加bigPicture。 假设您现在使用mBuilder.setLargeIcon(位图位图)从某人那里收到消息,您可以显示该人的照片。 因此,在状态栏中,您将在滚动时看到图标,您将看到人物照片代替图标。 还有其他功能

  • 在通知中添加一个计数器
  • 第一次看到通知时的Ticker消息
  • 可扩展的通知
  • 多行通知等

您可以尝试使用此代码,这对我来说很好:

    NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this);

    Intent i = new Intent(noti.this, Xyz_activtiy.class);
    PendingIntent pendingIntent= PendingIntent.getActivity(this,0,i,0);

    mBuilder.setAutoCancel(true);
    mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
    mBuilder.setWhen(20000);
    mBuilder.setTicker("Ticker");
    mBuilder.setContentInfo("Info");
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setSmallIcon(R.drawable.home);
    mBuilder.setContentTitle("New notification title");
    mBuilder.setContentText("Notification text");
    mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

    NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(2,mBuilder.build());

简单的通知方式

 NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher) //icon
            .setContentTitle("Test") //tittle
            .setAutoCancel(true)//swipe for delete
            .setContentText("Hello Hello"); //content
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(1, builder.build()
    );

使用此代码

            Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
            PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                    (int) System.currentTimeMillis(), intent, 0);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.drawable.your_notification_icon)
                            .setContentTitle("Notification title")
                            .setContentText("Notification message!")
                            .setContentIntent(pIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, mBuilder.build());

此处应用 Class 代码在下面

public class App extends Application {
public static final String CHANNEL_1="CHANNEL1";
@Override
public void onCreate() {
    super.onCreate();
    createNotificationChannel();
}

private void createNotificationChannel() {
    NotificationChannel channel=new NotificationChannel(CHANNEL_1,"Channel 1", NotificationManager.IMPORTANCE_HIGH);
    channel.setDescription("This is Channel 1");

    NotificationManager  notificationManager=getSystemService(NotificationManager.class);
    notificationManager.createNotificationChannel(channel);
}

}

在代码下方创建活动显示通知

 NotificationManagerCompat notificationManagerCompat;

    notificationManagerCompat = NotificationManagerCompat.from(this);

    binding.btnNotification.setOnClickListener(v -> {
        Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_1)
                .setSmallIcon(R.drawable.ic_black_24)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText("Message")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .build();
        notificationManagerCompat.notify(1, notification);
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM