1、Notification
与NotificationManager
创建一个NotificationManager
NotificationManager
类是一个通知管理器类,这个对象是由系统维护的服务,是以单例模式的方式获得,所以一般并不直接实例化这个对象。在Activity中,可以使用Activity.getSystemService(String)
方法获取NotificationManager
对象,Activity.getSystemService(String)
方法可以通过Android系统级服务的句柄,返回对应的对象。在这里需要返回NotificationManager
,所以直接传递Context.NOTIFICATION_SERVICE
即可。
使用Builder
构造器来创建Notification
使用NotificationCompat
类的Builder
构造器来创建Notification
对象,可以保证程序在所有的版本上都能正常工作。Android8.0新增了通知渠道这个概念,如果没有设置,则通知无法在Android8.0的机器上显示
2、NotificationChannel
通知渠道∶Android 8.0引入了通知渠道,其允许您为要显示的每种通知类型创建用户可自定义的渠道。
通知重要程度设置,NotificationManager
类中
-
IMPORTANCE_NONE 关闭通知
-
IMPORTANCE_MIN 开启通知,不会弹出,但没有提示音,状态栏中无显示
-
IMPORTANCE_LOW 开启通知,不会弹出,不发出提示音,状态栏中显示
-
IMPORTANCE_DEFAULT 开启通知,不会弹出,发出提示音,状态栏中显示
-
IMPORTANCE_HIGH 开启通知,会弹出,发出提示音,状态栏中显示
3、常见方法说明
-
1.setContentTitle(String string)设置标题 2.setContentText(String string)设置文本内容 3.setSmallcon(int icon)设置小图标 4.setLargelcon(Bitmap icon) 设置通知的大图标 5.setColor(int argb)设置小图标的颜色 6.setContentIntent(Pendinglntent intent)设置点击通知后的跳转意图 7.setAutoCancel(boolean boolean)设置点击通知后自动清除通知 8. setWhen(long when)设置通知被创建的时间
4、创建一个项目
创建两个Button
分别用于发送通知和取消通知
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendNotification"
android:text="发送通知"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="cacelNotification"
android:text="取消通知"/>
创建一个NotificationManager
,通过getSystemService
方法获取NotificationManager
对象,直接传递NOTIFICATION_SERVICE
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
使用NotificationChannel
自定义通知
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel("leo","啦啦啦啦啦",NotificationManager.IMPORTANCE_HIGH);//传入`IMPORTANCE_HIGH`开启通知,会弹出,发出提示音,状态栏中显示
manager.createNotificationChannel(channel);
}
创建Notification
使用NotificationCompat
类的Builder
构造器来创建Notification
对象,并对通知进行设置
Notification notification= new NotificationCompat.Builder(this,"leo")
.setContentTitle("官方通知")
.setContentText("go!go!go!")
.setSmallIcon(R.drawable.test)//从Android5.0开始,图片必须只使用alpha图层
.build();
创建点击按钮的触发条件sendNotification
和cacelNotification
在sendNotification()
里实现发送通知的行为
public void sendNotification(View view){
manager.notify(1,notification);
}
在cacelNotification()
里实现取消通知的行为
public void cacelNotification(View view){
manager.cancel(1);
}
通过.setContentIntent
实现点击通知完成页面跳转
创建NotificationActivity
(注:别忘记在AndroidManifest
注册)
Intent intent = new Intent(this,NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification= new NotificationCompat.Builder(this,"leo")
.setContentTitle("官方通知")
.setContentText("go!go!go!")
.setSmallIcon(R.drawable.test)
.setContentIntent(pendingIntent)
.setAutoCancel(true)//可以实现点击完通知,通知自动消失
.build();
lIcon(R.drawable.test)
.setContentIntent(pendingIntent)
.setAutoCancel(true)//可以实现点击完通知,通知自动消失
.build();