说说 Android 中的通知(Notification)

当应用程序不在前台运行,这时就可以借助通知( Notification )向用户发送一些提示消息。 发出通知后,手机最上方的状态栏中就会显示一个通知图标,下拉状态栏就会看到通知的详情。

1 基本用法

//获取系统通知服务
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

String contentTitle = "重庆现最苗条电梯"; //标题
String contentText = "宽度仅容纳一人爆红网络";//内容
Notification notification = new NotificationCompat.Builder(context).setContentTitle(contentTitle)
        .setContentText(contentText).setWhen(System.currentTimeMillis()).setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)).build();
manager.notify(1, notification);

*使用 NotificationCompat 可以保证通知功能能够在目前所有的 Android 版本中都适用。
*NotificationCompat 的 Builder 支持使用连缀的设置方法,这一点很像 jQuery。

Builder 设置方法:

方法名说明
setContentTitle(CharSequence title)设置标题。
setContentText(CharSequence text)设置内容。
setWhen(long when)设置创建通知的时间,单位是毫秒。
setSmallIcon(int icon)设置通知的小图标,会显示在手机的左上角。
setLargeIcon(Bitmap icon)设置通知的大图标,下拉系统的状态栏时,就可以看到它啦。

notify(int id, Notification notification) 方法用于显示通知,它有两个参数:id 是我们应用中为通知定义的唯一标识符;notification 即是我们建立的通知对象。

运行后:

通知小图标

下拉系统状态栏,即可看到我们新建的通知消息:

这时的通知消息还未实现点击效果,我们可以通过 PendingIntent 来实现。它与 Intent 的不同之处是:

  • Intent - 立即执行某个动作。
  • PendingIntent - 在某个合适的时机去执行某个动作。

我们新建一个活动,当用户点击通知消息后,会跳转到这个活动中。

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_notification"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="26sp"
        android:text="在重庆解放碑得意世界附近,有一部迷你电梯,因其异常狭窄引起了广泛的关注,对于这部魔性的电梯,有网友表示“这是对胖子的深深恶意······”"
        />

</RelativeLayout>

这个活动很简单,只是展示一些文本内容。

接着,修改之前的活动代码:

//获取系统通知服务
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

//创建 PendingIntent
int requestCode = 0;
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
Intent intent = new Intent(context, NotificationActivity.class);//启动 NotificationActivity 活动
PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode, intent, flags);

//创建通知
String contentTitle = "重庆现最苗条电梯"; //标题
String contentText = "宽度仅容纳一人爆红网络";//内容
Notification notification = new NotificationCompat.Builder(context).setContentTitle(contentTitle)
        .setContentText(contentText).setWhen(System.currentTimeMillis()).setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)).setContentIntent(pendingIntent).setAutoCancel(true).build();
manager.notify(1, notification);

这里创建 PendingIntent 对象,并把它放入 NotificationCompat.Builder 中。

PendingIntent.getActivity 定义如下:

 public static PendingIntent getActivity(Context context, int requestCode,
            Intent intent, @Flags int flags)
参数描述
Context上下文,在 Activity 类中就是本身(this)。
requestCode请求码。
intentIntent 对象。
flags行为方式。

flags 行为方式类型:

类型描述
FLAG_ONE_SHOTPendingIntent 对象只能被使用一次。
FLAG_NO_CREATE如果 PendingIntent 对象不存在,则返回 null。
FLAG_CANCEL_CURRENT即使之前的 PendingIntent 对象已经存在,也会创建一个新的 PendingIntent 对象。
FLAG_UPDATE_CURRENT如果之前的 PendingIntent 对象已经存在,那么会更新它的内容。(常用)

注意:我们构建 Build 的过程中加入了 setAutoCancel(true),则表示当用户点击了通知后,手机左上角的图标就不会再显示啦。也可以使用 NotificationManager 的 cancel 方法主动取消,这可以应用于某些特殊场景:

int notifyId = 1;//通知 ID
manager.notify(notifyId, notification);

//延迟 5 s,要不通知一下子就会被取消啦
try {
    Thread.sleep(5000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
manager.cancel(notifyId);

运行程序,再次点击系统通知栏中的通知,这时将会弹出通知活动页:

2 高级功能

2.1 自定义通知音

打开 Android Device Monitor,可以看到在 "/system/media/audio/notifications/ 下自带了很多通知音,我们可以选择甚至是自定义一个喜欢的通知音:

系统自带的通知音

//自定义通知音
Uri customSound = Uri.fromFile(new File("/system/media/audio/notifications/Altair.ogg"));

可以通过以下方式获得系统的通知音:

Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

最后使用 setSound 方法来设置通知音:

 public Builder setSound(Uri sound)

是不是很简单呀O(∩_∩)O哈哈~

2.2 通知振动

通过设置 vibrate 属性,可以让通知出现时让手机振动,它定义如下:

public Builder setVibrate(long[] pattern) 

pattern 是长整型数组,它被用来设置手机静止和振动的时长,以毫秒为单位。它是一种交替的设置模式,比如下标 0 表示静止的时长,下标 1 表示振动的时长,下标 2 又表示振动的时长,以此类推。

Notification notification = new NotificationCompat.Builder(context)
...
.setVibrate(new long[]{0,1000,1000,1000}).build();

接着,在 AndroidManifest.xml 中声明振动权限:

<uses-permission android:name="android.permission.VIBRATE"/>

这样,当用户收到通知时,手机就会振动啦 O(∩_∩)O哈哈~

2.3 呼吸灯

呼吸灯是指灯光在微电脑的控制之下完成由亮到暗的逐渐变化,感觉好像是人在呼吸,它起到一个通知提醒的作用。

通过设置 setLights ,可以控制呼吸灯的变化频率,它定义如下:

public Builder setLights(@ColorInt int argb, int onMs, int offMs) 
参数说明
argb灯的颜色,通过 Color 类来设置。
onMs灯亮的时长,单位:毫秒。
offMs灯灭的时长,单位:毫秒。
//自定义颜色-紫色
int color=Color.rgb(255,0,255);

Notification notification = new NotificationCompat.Builder(context).setContentTitle(contentTitle)
...
.setLights(color,1000,1000).build();

2.4 富文本

NotificationCompat.Builder 类中的 setStyle() 方法,可以让我们构建出富文本的通知内容, 这个方法接收一个 NotificationCompat.style 参数,通过它用来创建出具体的富文本信息,如长文字 、 图片等 。

2.4.1 长文本

如果 setContentText() 传入的内容过长,那么一行内显示不完的内容就会变为省略号:

//长文字
String longContentText = " 近日,重庆现最苗条电梯走红网络,到底是怎么样情况呢?在重庆解放碑得意世界附近,有一部显得十分“苗条”的迷你电梯,经测量,宽度约57.5厘米,只能容下一个人乘坐,一般而言,普通的电梯可以站两个人,但这部迷你电梯相对狭窄,因而有不少游客专程来打卡拍照。";//内容
android.support.v4.app.NotificationCompat.BigTextStyle bigTextStyle=new NotificationCompat.BigTextStyle().bigText(longContentText);


Notification notification = new NotificationCompat.Builder(context).setContentTitle(contentTitle)
        ...
        .setStyle(bigTextStyle).build();

长文本显示效果

2.4.2 图片

图片显示效果

2.5 优先级

NotificationCompat.Builder 类中的 setPriority() 方法可用于设置通知的重要程度,它接收一个整型参数,在 NotificationCompat 中定义了 5 级优先级常量值:

可用的优先级参数

 int priority=NotificationCompat.PRIORITY_MAX;

Notification notification = new NotificationCompat.Builder(context).setContentTitle(contentTitle)
...
                        .setPriority(priority)
                        .build();

如果设置为最高优先级,那么它会直接显示在屏幕顶部:

最高优先级效果

确保这个通知对于用户来说确实是至关重要的,否则如果用户产生了反感,那么有可能会卸载掉这个 APP 哦。

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android常驻通知(Notification)是指在用户状态栏一直显示的通知图标和文本内容,不会因为用户操作或应用进程被销毁而消失。常驻通知通常用于实时监测、后台服务、音乐播放等需要持续提醒用户的场景。 常驻通知的实现步骤如下: 1. 首先,需要创建一个Notification对象,包括通知图标、标题、内容等信息。 2. 然后,创建一个PendingIntent,用于定义用户点击通知后的操作,比如打开应用的某个Activity或执行某个Service。 3. 创建一个NotificationChannel(通知渠道),用于定义通知的重要程度,包括声音、震动等设置。 4. 将Notification对象与PendingIntent关联,并将其设置为常驻通知的优先级。 5. 最后,调用NotificationManager的notify方法,将通知显示在用户的状态栏上。 需要注意的是,常驻通知存在一些使用限制和最佳实践: 1. 用户可以通过设置通知管理来关闭或打开特定应用的常驻通知。 2. 常驻通知不适合用于广告或频繁推送的内容,以免打扰用户。 3. 为了避免误导用户,常驻通知的图标和文本内容应与应用的实际情况相符。 4. 如果需要更新通知的内容或操作,可以使用NotificationManager的notify方法进行更新,并保持通知的id不变。 总之,常驻通知Android提供的一个重要功能,可以实现持续提醒用户和后台监测的需求。但应用开发者需要注意使用场景和用户体验,遵循Android的最佳实践,以确保用户对常驻通知的接受和理解。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值