文章目录
什么是通知
通知是 Android 中 Service 与用户交互的一种方式(主要是 Service )
如何发送一个简单通知?
1、获取 NotificationManager 通知管理器
2、构建 Notification 对象:
使用 Notification.Builder 构建器构建对象
Builder builder = new Builder();
builder.setXXX().setXXX().build();
3、调用 manager.notify() 方法发送该通知
一个发送通知的栗子:
private static final int NOTIFICATION_ID = 1001;
private void sendNotification() {
//1、NotificationManager
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
/** 2、Builder->Notification
* 必要属性有三项
* 小图标,通过 setSmallIcon() 方法设置
* 标题,通过 setContentTitle() 方法设置
* 内容,通过 setContentText() 方法设置*/
Notification.Builder builder = new Notification.Builder(this);
builder.setContentInfo("Content info")
.setContentText("Content text")//设置通知内容
.setContentTitle("Content title")//设置通知标题
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher_round)//不能缺少的一个属性
.setSubText("Subtext")
.setTicker("滚动消息......")
.setWhen(System.currentTimeMillis());//设置通知时间,默认为系统发出通知的时间,通常不用设置
Notification n = builder.build();
//3、manager.notify()
manager.notify(NOTIFICATION_ID,n);
}
运行在API22的手机上效果:
Android 8.0不能弹出通知
运行在API26的手机上怎么样呢…原来根本就不能弹出通知,填坑请戳下文:
Notification Android8.0中无法发送通知,提示:No Channel found for pkg
一个兼容8.0的栗子
private static final int NOTIFICATION_ID = 1001;
private void sendNotification() {
//1、NotificationManager
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
/** 2、Builder->Notification
* 必要属性有三项
* 小图标,通过 setSmallIcon() 方法设置
* 标题,通过 setContentTitle() 方法设置
* 内容,通过 setContentText() 方法设置*/
Notification.Builder builder = new Notification.Builder(this);
builder.setContentInfo("Content info")
.setContentText("Content text")//设置通知内容
.setContentTitle("Content title")//设置通知标题
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher_round)//不能缺少的一个属性
.setSubText("Subtext")
.setTicker("滚动消息......")
.setWhen(System.currentTimeMillis());//设置通知时间,默认为系统发出通知的时间,通常不用设置
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("001","my_channel",NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true); //是否在桌面icon右上角展示小红点
channel.setLightColor(Color.GREEN); //小红点颜色
channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
manager.createNotificationChannel(channel);
builder.setChannelId("001");
}
Notification n = builder.build();
//3、manager.notify()
manager.notify(NOTIFICATION_ID,n);
}
让通知常驻通知栏
如何让通知常驻通知栏?(用户无法删除)
第一种方式:
//让通知常驻通知栏
builder.setOngoing(true);
第二种方式:
Notification n = builder.build();
n.flags = Notification.FLAG_NO_CLEAR;
如何清除通知
private void clearNotification() {
//单利的系统服务
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(NOTIFICATION_ID);
}
如何更新通知界面内容
如何更新通知的界面内容?
更新界面中的内容原理就是使用相同的 ID 再次发送一个内容不同的通知即可
private static final int NOTIFICATION_ID2 = 1002;
private int progress = 0;
private void sendNotification2() {
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("音乐下载")
.setContentText("下载进度:"+progress+"%")
.setSmallIcon(R.mipmap.ic_launcher) ;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("002","download_channel",NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
builder.setChannelId("002");
}
Notification n = builder.build();
manager.notify(NOTIFICATION_ID2,n);
progress+=10;
}
点击通知执行意图
如何实现点击了通知后,执行具体意图?
builder.setOntentIntent(PendingIntent);
PendingIntent 是一个包装意图,该对象中包含了具体的意图, PendingIntent 可以传递给另外的应用程序,让对让在某个时刻执行该 PendingIntent
如何获取 PendingIntent?
PendingIntent pi = PendingIntent.getActivity(...);
PendingIntent pi = PendingIntent.getService(...);
PendingIntent pi = PendingIntent.getBroadcast(...);
sendNotification2方法修改如下:
Intent intent = new Intent(this,Main2Activity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
//给通知添加点击意图
builder.setContentIntent(pi);
如何实现进度条的通知
如何实现进度条的通知?
builder.setProgress(max,progress,indetermination);
setProgress(0,0,false);去掉进度条
setProgress(100,20,false);带有进度条
setProgress(10,20,true);不确定进度条
private void sendProgressNotification() {
final NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
final Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("进度")
.setContentText("进度...")
.setProgress(100,10,true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("003","download_channel",NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
builder.setChannelId("003");
}
Notification n = builder.build();
manager.notify(NOTIFICATION_ID3,n);
//每隔1秒更新进度条进度
//启动工作线程
new Thread(){
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=1;i<=10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//发通知
builder.setProgress(100,i*10,false);
Notification n = builder.build();
manager.notify(NOTIFICATION_ID3,n);
}
//更新通知内容
manager.cancel(NOTIFICATION_ID3);
builder.setProgress(0,0,false);
builder.setContentText("音乐下载完毕");
Notification n = builder.build();
manager.notify(NOTIFICATION_ID3,n);
}
}.start();
}
如何自定义通知的UI界面
如何自定义通知的 UI 界面?
RemoteViews views = new RemoteViews(...,...);
builder.setContent(RemoteViews view);
如何给自定义的通知上的按钮添加点击意图?
RemoteViews views = new RemoteViews(...,...);
views.setOnclickPendingIntent(id,PendingIntent);
public class NotificationActivity extends Activity implements View.OnClickListener{
private static final int NOTIFICATION_ID3 = 1003;
private static final int NOTIFICATION_ID4 = 1004;
Button button;
Button button2;
private MyReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_notification);
button = findViewById(R.id.button);
button.setOnClickListener(this);
button2 = findViewById(R.id.button2);
button2.setOnClickListener(this);
//动态注册广播接收器
receiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("ACTION_BUTTON_PAUSE_CLICKED");
this.registerReceiver(receiver,intentFilter);
}
class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.i("info","接收到了广播"+intent.getAction());
}
}
@Override
protected void onDestroy() {
this.unregisterReceiver(receiver);
super.onDestroy();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
sendProgressNotification();
break;
case R.id.button2:
sendCustomeNotification();
break;
}
}
public void sendCustomeNotification() {
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
RemoteViews views = new RemoteViews(getPackageName(),R.layout.layout_notification);
//给views中的按钮添加点击意图
Intent intent = new Intent(this,NewsContentActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.btn_pre,pendingIntent);
//给中间按钮添加点击意图
Intent intent1 = new Intent("ACTION_BUTTON_PAUSE_CLICKED");
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this,0,intent1,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.btn_pause,pendingIntent1);
builder.setContent(views);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("004","download_channel",NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
builder.setChannelId("004");
}
Notification n = builder.build();
manager.notify(NOTIFICATION_ID4,n);
}
private void sendProgressNotification() {
final NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
final Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("进度")
.setContentText("进度...")
.setProgress(100,10,true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("003","download_channel",NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
builder.setChannelId("003");
}
Notification n = builder.build();
manager.notify(NOTIFICATION_ID3,n);
//每隔1秒更新进度条进度
//启动工作线程
new Thread(){
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=1;i<=10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//发通知
builder.setProgress(100,i*10,false);
Notification n = builder.build();
manager.notify(NOTIFICATION_ID3,n);
}
//更新通知内容
manager.cancel(NOTIFICATION_ID3);
builder.setProgress(0,0,false);
builder.setContentText("音乐下载完毕");
Notification n = builder.build();
manager.notify(NOTIFICATION_ID3,n);
}
}.start();
}
}