Notification的功能与用法

Notification是显示在手机状态栏的的通知—手机状态栏位于手机手机屏幕的最上方,哪里一般显示手机当前的网络状态、电池状态、时间等。Notification所代表的是一种具有全局效果的通知,程序一般通过NotificationManager服务发送Notification。
Android为NotiFication增加Notification.Builder类,通过该类允许开发者更轻松地创建Notification对象。Notification.Builder提供了如下常用方法。

  • setDefaults():设置通知LED灯,音乐,振动等。
  • setAutoCancel():设置点击通知后,状态栏自动删除通知。
  • setContentTitle():设置通知标题。
  • setContentText():设置通知内容。
  • setSmallIcon():为通知设置图标。
  • setLargeIcon():为通知设置大图标。
  • setTick():设置通知栏在状态栏的提示文本。
  • setContentIntent():设置点击通知后将要启动的程序组件对应的PendingInten。

发送Notification很简单,按如下步骤进行即可。

  1. 调用getSystemService(NOTIFICATION_SERVICE)方法获取系统的NotificationManager服务。
  2. 通过构造器创建一个Notification对象。
  3. 为Notification设置各种属性。
  4. 通过NotificationManager的notify()方法发送Notification.

版本号如果大于或者等于8.0

要创建一个通知,有以下几个步骤:

  1. 构造NotificationChannel对象,构造方法有三个参数:渠道id、渠道名称、渠道重要性级别。
  2. 调用NotificationChannel.setDescription方法可以设置渠道描述。这个描述在系统设置中可以看到。
  3. 调用NotificationManager.createNotificationChannel方法创建通知渠道
  4. 为Notification设置各种属性。
  5. 通过NotificationManager的notify()方法发送Notification.

以下是注册通知渠道的代码

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    //创建通知渠道
    CharSequence name = "渠道名称1";
    String description = "渠道描述1";
    String channelId="channelId1";//渠道id     
    int importance = NotificationManager.IMPORTANCE_DEFAULT;//重要性级别
    NotificationChannel mChannel = new NotificationChannel(channelId, name, importance);
    mChannel.setDescription(description);//渠道描述
    mChannel.enableLights(true);//是否显示通知指示灯
    mChannel.enableVibration(true);//是否振动

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            NOTIFICATION_SERVICE);
    notificationManager.createNotificationChannel(mChannel);//创建通知渠道
}
实例:加薪通知

java代码

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

public class Main2Activity extends Activity {
    static final int NOTIFICATION_ID = 0X123;
    NotificationManager nm;
    String id = "jia";
    String title = "一条薪通知";
    Notification notification;
    NotificationCompat.Builder builder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        //获取系统的NotificationManager服务
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    }
    //为发送通知的按钮的点击事件定义事件处理方法
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void send(View view) {
        //创建一个启动其他Activity的Intent
        Intent intent = new Intent(Main2Activity.this,MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = nm.getNotificationChannel(id);
            if (mChannel == null) {
                mChannel = new NotificationChannel(id, title, importance);
                mChannel.enableVibration(true);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});//振动模式
                nm.createNotificationChannel(mChannel);
            }
            builder = new NotificationCompat.Builder(this,id);
            builder.setAutoCancel(true)
                    .setContentTitle("一个薪通知")
                    .setSmallIcon(R.drawable.before_nh)
                    .setContentText("增薪10%")
                    .setContentIntent(pi)
                    .setWhen(System.currentTimeMillis())
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.after_nh));
        }else{
            builder = new NotificationCompat.Builder(this);
            builder.setAutoCancel(true)
                    .setContentTitle("一个薪通知")
                    .setSmallIcon(R.drawable.before_nh)
                    .setContentText("增薪10%")
                    .setContentIntent(pi)
                    .setWhen(System.currentTimeMillis())
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.after_nh));
        }
        notification = builder.build();
        nm.notify(NOTIFICATION_ID,notification);

    }

    public void del(View view) {
    	nm.cancel(NOTIFICATION_ID);
    }
}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main2Activity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送通知"
        android:onClick="send"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/guideline"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="取消通知"
        android:onClick="del"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
NotificationChanne

Android开发者文档介绍
构造方法:
NotificationChannel(String id, CharSequence name, int importance)

构造方法中的参数

参数名说明
idString:频道的ID。每个包装必须唯一。如果该值太长,则可能会被截断
nameCharSequence:通道的用户可见名。当系统区域设置更改时,您可以通过监听 Intent#ACTION_LOCALE_CHANGED广播来重命名该频道。建议的最大长度为40个字符;如果值太长,则可能被截断。
importanceint:渠道的重要性。这控制如何将中断通知发送到此通道。值是NotificationManager.IMPORTANCE_UNSPECIFIED
NotificationManager.IMPORTANCE_NONE
NotificationManager.IMPORTANCE_MIN
NotificationManager.IMPORTANCE_LOW
NotificationManager.IMPORTANCE_DEFAULT
或NotificationManager.IMPORTANCE_HIGH

公共方法:
boolean canBubble()
返回发布到此频道的通知是否可以在其他应用顶部的浮动窗口中的通知阴影之外显示。

boolean canBypassDnd()
发布到此频道的通知是否可以绕过“请勿打扰” NotificationManager#INTERRUPTION_FILTER_PRIORITY模式。

boolean canShowBadge()
返回发布到此频道的通知是否可以在启动器应用程序中显示为徽章。

int describeContents()
描述此Parcelable实例的编组表示中包含的特殊对象的种类。

void enableLights(boolean lights)
设置发布到此频道的通知是否应在支持该功能的设备上显示通知灯。

void enableVibration(boolean vibration)
设置发布到此频道的通知是否应该振动。

boolean equals(Object o)
指示其他某个对象是否与此对象“相等”。

AudioAttributes getAudioAttributes()
返回由发布到此频道的通知播放的声音的音频属性。

String getDescription()
返回此通道的用户可见描述。

String getGroup()
返回此通道所属的组。

String getId()
返回此通道的ID。

int getImportance()
返回用户指定的重要性,例如

int getLightColor()
返回发布到此频道的通知的通知灯颜色。

int getLockscreenVisibility()
返回发布到此频道的通知是否以完整或已编辑形式显示在锁定屏幕上。

CharSequence getName()
返回此通道的用户可见名称。

Uri getSound()
返回此频道的通知声音。

long[] getVibrationPattern()
返回发布到此通道的通知的振动模式。

boolean hasUserSetImportance()
返回用户是选择该渠道的重要性,还是从应用程序中确认初始选择,还是将其更改为更高或更低。

int hashCode()
返回对象的哈希码值。

void setAllowBubbles(boolean allowBubbles)
设置发布到此频道的通知是否可以显示在通知栏的外面,以气泡的形式浮动在其他应用程序的内容上。

void setBypassDnd(boolean bypassDnd)
设置发布到此频道的通知是否可以在NotificationManager.INTERRUPTION_FILTER_PRIORITY模式下打断用户 。

void setDescription(String description)
设置此通道的用户可见描述。

void setGroup(String groupId)
设置此通道所属的组。

void setImportance(int importance)
设置此通知通道的中断级别。

void setLightColor(int argb)
如果此通道上有指示灯enabled并且设备支持该功能,则设置发布到该通道的通知的通知灯颜色 。

void setLockscreenVisibility(int lockscreenVisibility)
设置发布到此频道的通知是否显示在锁定屏幕上,如果显示,则是否以删节形式显示。

void setName(CharSequence name)
设置此通道的用户可见名称。

void setShowBadge(boolean showBadge)
设置发布到此频道的通知是否可以在启动器中显示为应用程序图标标志。

void setSound(Uri sound, AudioAttributes audioAttributes)
设置发布到此频道的通知应播放的声音及其音频属性。

void setVibrationPattern(long[] vibrationPattern)
设置发布到此频道的通知的振动模式。

boolean shouldShowLights()
返回发布到此频道的通知是否触发通知灯。

boolean shouldVibrate()
返回发布到此频道的通知是否始终振动。

String toString()
返回对象的字符串表示形式。

void writeToParcel(Parcel dest, int flags)
将此对象展平到包裹中。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值