Notification 通用使用笔记

共 15620字,需浏览 32分钟

 ·

2024-05-21 08:12

和你一起终身学习,这里是程序员Android

经典好文推荐,通过阅读本文,您将收获以下知识点:

一、Notification 简介
二、创建Notification 的方法
三、通知的管理
四、简单的通知实现
五、可扩展通知实现
六、通知中含下载进度条
七、通知中含媒体播放控件
八、自定义通知内容

一、Notification 简介

Notification 通知是应用向用户显示的消息提示,当发送通知时,通知将先以图标的形式显示在通知区域中。用户可以打开下拉通知栏查看通知的详细信息。通知区域和下拉通知栏均是由系统控制的区域,用户可以随时查看。

通知在Android用户界面的一个重要部分,其使用方法请看以下内容:

通知区域中的通知

下拉通知栏中的通知

二、创建Notification 的方法

  • 1.通知创建的方法

调用NotificationCompat.Builder.build() 创建Notification对象,然后调用 NotificationManager.notify() 将Notification对象传递给系统。

  • 2.Notification 对象必须包含以下内容:

    • 小图标,由setSmallIcon()设置

    • 标题,由 setContentTitle() 设置

    • 详细文本,由 setContentText()设置

  • 3.通知可选内容

通知默认优先级为 PRIORITY_DEFAULT 0
Notification.Builder.setPriority()
5个级别可选(-2、-1、0、1、2)

通知优先级如下:

    PRIORITY_LOW=-1
PRIORITY_MIN=-2
PRIORITY_DEFAULT = 0
PRIORITY_HIGH=1
PRIORITY_MAX=2
  • 4.设置可以扩展样式

通过Notification.Builder.setStyle()可以设置通知的样式。

  • 5.点击通知启动Activity(PendingIntent)

通知中经常遇到,点击通知栏,打开 Activity



Notification.Builder mBuilder = new Notification.Builder(this);

mBuilder.setSmallIcon(R.drawable.gril)
.setDefaults(Notification.DEFAULT_SOUND).setColor(000)
.setContentTitle("简单通知Tittle").setContentText("点击可以打开Activity");

Intent resultIntent = new Intent(this, NotificationMethods.class);
// 新开一个Activity 栈

resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NotificationMethods.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());

三、通知的管理

  • 1.更新通知

调用 NotificationManager.notify(ID) 发出带有通知ID的通知,ID相同,即可更新以前ID发送的通知。

  • 2.删除通知

创建时 调用了 setAutoCancel(true)
删除时候调用删除指定ID

NotificationManager.cancel(notificationId)

删除自己应用发的所有通知

Utils.mNotificationManager.cancelAll();
  • 3.在通知中显示进度条

setProgress()

四、简单的通知实现

  • 1.实现效果

简单通知图片

  • 2.实现代码

    /**
* 简单通知
*/

public void SimpleNotification(View view) {

Notification.Builder mBuilder = new Notification.Builder(this);

mBuilder.setSmallIcon(R.drawable.gril)
.setDefaults(Notification.DEFAULT_SOUND).setColor(000)
.setContentTitle("简单通知Tittle").setContentText("点击可以打开Activity");

Intent resultIntent = new Intent(this, NotificationMethods.class);
// 新开一个Activity 栈

resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NotificationMethods.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}

五、可扩展通知实现

  • 1.实现效果

通知展开图

通知未展开图

  • 2.实现代码


/**
* 可扩展通知
* **/

public void NotificationStyle(View view) {

Notification.Builder mBuilder = new Notification.Builder(this);

mBuilder.setLargeIcon(
DrawableUtils.DrawableToBitmap(getResources().getDrawable(
R.drawable.ic_launcher)))
.setContentTitle("我是可扩展通知的Tittle ")
.setDefaults(Notification.DEFAULT_SOUND)

.setContentText("我是可扩展通知的内容")
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setStyle(
new Notification.InboxStyle().addLine("我是可扩展通知第一行")
.addLine("我是可扩展通知第二行")
.setBigContentTitle("我是可扩展的大 Tittle")
.setSummaryText("点击,展开获取更多内容"));

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 如果Id 一样可以更新通知
mNotificationManager.notify(1, mBuilder.build());
}

六、通知中含下载进度条

  • 1.实现效果

下载中通知

下载完成通知

  • 2.实现代码


/**
* 带有下载进度条的通知
* **/

public void NotificationProcess(View view) {

final NotificationManager mNotifyManagerProcess;
final Notification.Builder mBuilder;
mNotifyManagerProcess = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new Notification.Builder(this);
mBuilder.setContentTitle("Picture Downloading").setSmallIcon(
R.drawable.ic_launcher);
new Thread(new Runnable() {
@Override
public void run() {
for (MIncr = 0; MIncr <= 100; MIncr += 1 + 5 * Math.random()) {
mBuilder.setProgress(100, MIncr, false).setContentText(
MIncr + "%");
mNotifyManagerProcess.notify(2, mBuilder.build());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
/**
* setProgress true 则表示 进度条一直不停的从左至右滑动,类似于圆形进度条 false :进度条消失
* **/

mBuilder.setContentText("Download complete").setProgress(0, 0,
false);
mNotifyManagerProcess.notify(2, mBuilder.build());
}
}).start();
}

七、通知中含媒体播放控件

  • 1.实现效果

未展开图

展开图

  • 2.实现代码

    /**
* 音乐播放器样式
* **/

public void NotificationMediaStyle(View view) {
Notification.Builder mMediaBuilder = new Notification.Builder(this);
mMediaBuilder.setSmallIcon(R.drawable.ic_launcher);
mMediaBuilder.setContentTitle("如果有一天我变有钱");
mMediaBuilder.setContentText("毛不易");
mMediaBuilder.setLargeIcon(DrawableUtils
.DrawableToBitmap(getResources().getDrawable(
R.drawable.ic_launcher)));
Intent mIntent = new Intent();
ComponentName name = new ComponentName(this, NotificationMethods.class);
mIntent.setComponent(name);
PendingIntent mPendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, mIntent, 0);
mMediaBuilder.setContentIntent(mPendingIntent);
mMediaBuilder.setPriority(Notification.PRIORITY_MAX);
mMediaBuilder.addAction(new Notification.Action.Builder(Icon
.createWithResource(NotificationMethods.this,
R.drawable.music_pre), "1", null).build());
mMediaBuilder.addAction(new Notification.Action.Builder(Icon
.createWithResource(NotificationMethods.this,
R.drawable.music_play), "2", null).build());
mMediaBuilder.addAction(new Notification.Action.Builder(Icon
.createWithResource(NotificationMethods.this,
R.drawable.music_next), "3", null).build());

Notification.MediaStyle mMediaStyle = new Notification.MediaStyle();
mMediaStyle.setShowActionsInCompactView(0, 1, 2);
mMediaBuilder.setStyle(mMediaStyle);

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 如果Id 一样可以更新通知
mNotificationManager.notify(1, mMediaBuilder.build());
}

八、自定义通知内容

  • 1.实现效果

自定义通知效果图

  • 2.实现代码

    /**
* 自定义样式通知
* **/

public void NotificationCustomView(View view) {

/***
* 自定义Remoteview
* **/

RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.notification_view);
remoteViews.setTextViewText(R.id.tv_content_title, "十年");
remoteViews.setTextViewText(R.id.tv_content_text, "陈奕迅");
// 打开上一首
remoteViews.setOnClickPendingIntent(R.id.btn_pre,
SetClickPendingIntent(NOTIFICATION_PRE));
// 打开下一首
remoteViews.setOnClickPendingIntent(R.id.btn_next,
SetClickPendingIntent(NOTIFICATION_NEXT));
// 点击整体布局时,打开播放器
remoteViews.setOnClickPendingIntent(R.id.btn_play,
SetClickPendingIntent(NOTIFICATION_PLAY));
// 点击整体布局时,打开Activity
remoteViews.setOnClickPendingIntent(R.id.ll_root,
SetClickPendingIntent(NOTIFICATION_ACTIVITY));

remoteViews.setOnClickPendingIntent(R.id.img_clear,
SetClickPendingIntent(NOTIFICATION_CANCEL));

Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("当前正在播放..")
.setWhen(System.currentTimeMillis())
.setContentTitle("十年")
.setContentText("陈奕迅")
.setAutoCancel(true)
.setLargeIcon(
DrawableUtils.DrawableToBitmap(getResources()
.getDrawable(R.drawable.ic_launcher)))
.setContent(remoteViews);

Utils.mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 打开通知
Utils.mNotificationManager.notify(Utils.NOTIFICATION_CUSTOM_ID,
builder.build());
}

public PendingIntent SetClickPendingIntent(int what) {
switch (what) {

case NOTIFICATION_PRE:
Intent intentPre = new Intent(this, MainActivity.class);
intentPre.putExtra("cmd", what);
int flagPre = PendingIntent.FLAG_UPDATE_CURRENT;
PendingIntent clickPreIntent = PendingIntent.getActivity(this,
what, intentPre, flagPre);
return clickPreIntent;

case NOTIFICATION_PLAY:
Intent intentPlay = new Intent(this, NotificationMethods.class);
intentPlay.putExtra("cmd", what);
int flagPlay = PendingIntent.FLAG_UPDATE_CURRENT;
PendingIntent clickPlayIntent = PendingIntent.getActivity(this,
what, intentPlay, flagPlay);
return clickPlayIntent;
case NOTIFICATION_NEXT:
Intent intentNext = new Intent(this, ActivityMethods.class);
intentNext.putExtra("cmd", what);
int flagNext = PendingIntent.FLAG_UPDATE_CURRENT;
PendingIntent clickNextIntent = PendingIntent.getActivity(this,
what, intentNext, flagNext);
return clickNextIntent;
case NOTIFICATION_ACTIVITY:
Intent intentActivity = new Intent(this, ServiceMethod.class);
intentActivity.putExtra("cmd", what);
int flag = PendingIntent.FLAG_UPDATE_CURRENT;
PendingIntent clickIntent = PendingIntent.getActivity(this, what,
intentActivity, flag);
Toast.makeText(getApplicationContext(), "打开Activity", 0).show();
return clickIntent;
case NOTIFICATION_CANCEL:

Intent intentCancel = new Intent("Notification_cancel");
intentCancel.putExtra("cancel_notification_id",
Utils.NOTIFICATION_CUSTOM_ID);
int flagCancel = PendingIntent.FLAG_CANCEL_CURRENT;
PendingIntent clickCancelIntent = PendingIntent.getBroadcast(this,
0, intentCancel, flagCancel);
return clickCancelIntent;
default:
break;
}
return null;

}
  • 3.自定View布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#282828"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="8dp" >


<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="5dp"
android:src="@drawable/ic_launcher" />


<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:orientation="vertical" >


<TextView
android:id="@+id/tv_content_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="18sp"
android:text="十年"
android:textColor="@android:color/white" />


<TextView
android:id="@+id/tv_content_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:text="陈奕迅"
android:textSize="14sp"
android:textColor="@android:color/white" />

</LinearLayout>

<Button
android:id="@+id/btn_pre"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/music_pre" />


<Button
android:id="@+id/btn_play"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="8dp"
android:background="@drawable/music_play" />


<Button
android:id="@+id/btn_next"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="8dp"
android:background="@drawable/music_next" />


<ImageView
android:id="@+id/img_clear"
android:layout_width="30dp"
android:layout_height="match_parent"
android:layout_gravity="top|center_horizontal"
android:padding="6dp"
android:src="@drawable/clear_img" />


</LinearLayout>
  • 4.实现自定义通知删除按钮事件实现

        case NOTIFICATION_CANCEL:

Intent intentCancel = new Intent("Notification_cancel");
intentCancel.putExtra("cancel_notification_id",
Utils.NOTIFICATION_CUSTOM_ID);
int flagCancel = PendingIntent.FLAG_CANCEL_CURRENT;
PendingIntent clickCancelIntent = PendingIntent.getBroadcast(this,
0, intentCancel, flagCancel);
return clickCancelIntent;
  • 5.广播是四大组件之一,需要在AndroidManfest.xml中注册

注册方式如下:

        <receiver
android:name="com.programandroid.BroadcastReceiver.NotificationReceived"
android:enabled="true"
android:exported="true" >

<intent-filter>
<action android:name="Notification_cancel" />
<action android:name="Notification_music_pre" />
<action android:name="Notification_music_play" />
<action android:name="Notification_music_next" />
</intent-filter>
</receiver>

至此,本篇已结束。转载网络的文章,小编觉得很优秀,欢迎点击阅读原文,支持原创作者,如有侵权,恳请联系小编删除。同时感谢您的阅读,期待您的关注。

点个在看,方便您使用时快速查找!

浏览 39
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报