Android8之前,使用Notification的步骤
1、调用getSystemService()方法获取系统的Notification服务
2、创建一个Notification对象,并为其设置各种属性
3、为Notification对象设置事件信息
4、通过NotificationManager类的notify()方法发送Notification通知
Android8之后,使用Notification的步骤
1、调用getSystemService()方法获取系统的NotificationManager服务
2、创建通知构造器NotificationCompatible.Builder对象
3、调用NotificationCompat.Builder对象的方法设置通知相关的内容
4、通过notify()方法发送Notification通知
public class NotificaionActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notificaion);
//Android 8.0+
NotificationChannel channel=new NotificationChannel("shouzhi"//唯一id
,"收支"//渠道名
, NotificationManager.IMPORTANCE_DEFAULT);//重要性
//设置渠道属性
channel.enableLights(true);//呼吸灯
channel.setShowBadge(true);//是否要显示到桌面应用图标上
//getSystemService
NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
//创建
Notification.Builder builder=new Notification.Builder(this);
Intent intent=new Intent(this,ButtonActivity.class);//跳转的界面
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,0);
Notification notification=builder.setSmallIcon(R.drawable.ic_launcher_background)//应用图标
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.bi04))//消息配套图片
.setContentTitle("好消息")
.setContentText("这是一个大厂")
.setAutoCancel(true)//点击后是否删除
.setProgress(100,30,true)//进度条最大现在是否变化
.setChannelId(channel.getId())
//Intent 意向意图 启动Activity,Service
//PendingIntent 对Intent的封装,将来要干什么,延迟的意向
.setContentIntent(pendingIntent)//点击通知将要做什么
.build();//创建一个通知
notificationManager.notify(1,notification);
}
}