Android之通知的使用-Notification
16lz
2021-01-24
通知
基本概念
Notification是一种Android中的通知状态栏,其设置在屏幕的顶部,当我们往下手动滑的时候,可以看到具体的通知内容.当有通知来的时候,如果不往下拉的时候,通知会是一个小图标呈现在手机顶部的状态栏.
通知的使用
涉及到的类:Notification
和NotificationManager
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(安卓)Studio 快捷键
- Android开发经验总结——ListView的使用
- Android关于ViewPager+Fragment缓存问题
- Android清除所有应用的缓存(包括系统应用)的两种实现方法
- Android(安卓)led灯实现大致流程
- Android[高级教程] 设计模式之七 单例模式
- Android(安卓)开发中Parcel存储类型和数据容器
- Android(安卓)Jni代码示例讲解
- Android单元测试 - 验证函数参数、返回值的正确姿势