通知在實(shí)際開(kāi)發(fā)中還是比較常見(jiàn)的肝箱,例如新聞,音樂(lè)播放器稀蟋,等煌张。
1,基本通知
//初始化通知管理器
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.reibang.com/p/890acf8e5080"));
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,mIntent,0);
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.ic_launcher_background);
builder.setContentTitle("標(biāo)題");
builder.setAutoCancel(true);
builder.setContentText("通知消息");
Notification notification = builder.build();
notificationManager.notify(0, notification);
2退客,基礎(chǔ)擴(kuò)展通知自定義布局
xml >> item_notification
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this is my View 骏融,http://www.reibang.com/u/6bbde9df8181http://www.reibang.com/u/6bbde9df8181http://www.reibang.com/u/6bbde9df8181http://www.reibang.com/u/6bbde9df8181http://www.reibang.com/u/6bbde9df8181http://www.reibang.com/u/6bbde9df8181"
/>
</LinearLayout>
JAVA類
首先要?jiǎng)?chuàng)建一個(gè)RemoteViews自定義視圖 詳情https://blog.csdn.net/baidu_26352053/article/details/54943759
RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.item_notification);
Notification notification1 = builder.build();
notification1.bigContentView= remoteViews;
notificationManager.notify(1, notification1);
注意链嘀,這里是在第一個(gè)通知的基礎(chǔ)上寫(xiě)的,和第一個(gè)的區(qū)別就是可展開(kāi)的自定義視圖档玻,
notification1.bigContentView= remoteViews;表示設(shè)置為普通視圖怀泊,但是可以展開(kāi),如果需要默認(rèn)展開(kāi)误趴,則設(shè)置notification1.contentView= remoteViews; 效果圖如下
可以看到在第二個(gè)通知中存在可以展開(kāi)的符號(hào)包个,也就是,layout >> item_notification這個(gè)布局。
3冤留,基礎(chǔ)再擴(kuò)展碧囊,懸浮通知,都是基于第一個(gè)例子
Intent flutterIntent =new Intent();
flutterIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
flutterIntent.setClass(NotificationActivity.this,RecycleViewActivity.class);
PendingIntent flutterPendingIntent = PendingIntent.getActivity(NotificationActivity.this,0,flutterIntent,PendingIntent.FLAG_CANCEL_CURRENT);
builder.setFullScreenIntent(flutterPendingIntent,true);
Notification notification2 = builder.build();
notificationManager.notify(2,notification2);
值得注意的是這種方式彈窗不會(huì)自動(dòng)消失
除了上述的用法纤怒,通知在5.0之后添加了通知等級(jí)糯而,分別有
builder.setVisibility(Notification.VISIBILITY_PUBLIC); 任何情況都都通知
builder.setVisibility(Notification.VISIBILITY_PRIVATE); 只有在沒(méi)有鎖屏情況下通知
builder.setVisibility(Notification.VISIBILITY_SECRET); 在pin,password等安全鎖和沒(méi)有鎖屏的情況下才能通知泊窘。