Android之通知的使用-Notification

通知

基本概念

Notification是一种Android中的通知状态栏,其设置在屏幕的顶部,当我们往下手动滑的时候,可以看到具体的通知内容.当有通知来的时候,如果不往下拉的时候,通知会是一个小图标呈现在手机顶部的状态栏.

通知的使用

涉及到的类:NotificationNotificationManager

Notification:用于设置通知中内容的类

NotificationManager:用于管理通知的类

用法:

  • 获得NotificationManager对象
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  • 获得Notification对象,先通过NotificationCompat的构造类Builder构造一个对象,并通过该对象设置通知的具体细节信息内容,比如图标,布局等等,再通过Builder类提供的build方法得到Notification对象.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,channelId);
                    .setSmallIcon(R.drawable.small)
                    .setCustomContentView(views)
                    .setContent(views)
                    .setContentIntent(pi)
                    .setWhen(System.currentTimeMillis());
Notifacation notification = builder.build();

通知的基本方法

下面介绍一些在通知中的Builder类中提供的方法,这些方法用于设置通知中的细节信息

  • setContentTitle:用于设置标题
  • setContentText:设置内容
  • setWhen:设置通知时间
  • setCustomContentView:用于设置通知中的布局
  • setDefault:使用默认设置,声音,闪灯,震动均设置
  • setContentIntent:用于设置点击通知进行跳转
Intent intent = new Intent(this,MainActivity);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
builder.setContentIntent(pi);
  • setTicker:收到通知后状态栏顶部显示的信息

案例

/*对象*/
publilc RemoteViews views;
public Notification notification;
public NotificationManager notificationManager;

/*方法*/
Intent clickIntent =new Intent(this,MainActivity.class);
PendingIntent pi =PendingIntent.getActivity(this,0,clickIntent,0);

views = new RemoteViews(this.getPackageName(),R.layout.notification);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
	String channelId ="MusicId";
	String channelName = "Music";

	NotificationChannel notificationChannel =new 				      NotificationChannel(channelId,channelName,NotificationManager.IMPORTANCE_LOW);
	notificationManager.createNotificationChannel(notificationChannel);
 
	notification = new NotificationCompat.Builder(this,channelId)
                    .setSmallIcon(R.drawable.small)
                    .setCustomContentView(views)
                    .setContent(views)
                    .setContentIntent(pi)
                    .setWhen(System.currentTimeMillis())
                    .setDefaults(Notification.DEFAULT_ALL)
                    .build();
     } else {
	notification = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.small)
                    .setCustomBigContentView(views)
                    .setContent(views)
                    .setContentIntent(pi)
                    .setWhen(System.currentTimeMillis())
                    .build();
        }
startForeground(123,notification);

参考

https://www.cnblogs.com/nylcy/p/6536790.html

https://blog.csdn.net/wangz666/article/details/90181561

你可能感兴趣的:(Android)