通知剖析

通知的设计由系统模板决定,您的应用只需要定义模板中各个部分的内容即可。通知的部分详情仅在展开后的视图中显示。

android 推送图标 android 通知图标_android

图 7. 包含基本详情的通知

图 7 展示了通知最常见的部分,具体如下所示:

  1. 小图标:必须提供,通过 setSmallIcon() 进行设置。
  2. 应用名称:由系统提供。
  3. 时间戳:由系统提供,但您可以使用 setWhen() 替换它或者使用 setShowWhen(false) 隐藏它。
  4. 大图标:可选内容(通常仅用于联系人照片,请勿将其用于应用图标),通过 setLargeIcon() 进行设置。
  5. 标题:可选内容,通过 setContentTitle() 进行设置。
  6. 文本:可选内容,通过 setContentText() 进行设置。

 一、创建通知

1、创建一个可以点击的通知的基本步骤

第一步:设置意图

Intent intent = new Intent(this, MainActivity2.class);
                PendingIntent pi = PendingIntent.getActivities(this, 0, new Intent[]{intent}, 0);

API:

public static PendingIntent getActivities(Context context, int requestCode, @NonNull Intent[] intents, @Flags int flags) { return getActivities(context, requestCode, intents, flags, null); }

参数:

context

上下文

requestCode

发件人的私人请求代码(这个参数一般填0)

Intent[] intents

要启动的活动的意图数组。

flags

这里很少用,填0即可

返回值

返回与给定参数匹配的现有或新的 PendingIntent。可能返回空值

第二步:创建通知的管理对象。

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

第三步:使用Builder构造器来创建Notification对象和设置通知的相关属性

Notification.Builder notification = new Notification.Builder(this)
                        .setContentTitle("恭喜您,中奖了")
                        .setContentText("快点击!快点击!快点击!进去领奖!")
                        .setWhen(System.currentTimeMillis())  // 发送时间
                        .setSmallIcon(R.mipmap.ic_launcher)   // 小图标
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))  // 大图标
                        .setContentIntent(pi) // 将意图传进来,实现跳转
                        .setAutoCancel(true) // 点击后,取消通知
                        .setSound(Uri.fromFile(new File("/system/media/audio/notifications/Simple.ogg"))) // 通知铃声
                        .setVibrate(new long[] {0, 1000, 1000, 1000}) // 通知时震动
                        .setLights(Color.GREEN, 1000, 1000); // LED灯

注:setLargeIcon()方法中的API:

 @NonNull public Builder setLargeIcon(Bitmap b) { return setLargeIcon(b != null ? Icon.createWithBitmap(b) : null); }

public static Bitmap decodeResource(Resources res, int id) { return decodeResource(res, id, null); }

res

包含图像数据的资源对象

id

图像数据的资源 ID

return

已解码的位图,如果无法解码图像,则为 null。

第四步:设置通知频道

1、创建频道

2、通知注册频道

3、通知指定通知频道 ID

// 4、创建通知通道
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    // 第三个参数表示通知的重要程度,默认则只在通知栏闪烁一下
                    NotificationChannel notificationChannel = new NotificationChannel("AppTestNotificationId", "AppTestNotificationName", NotificationManager.IMPORTANCE_HIGH);
                    // 注册通道,注册后除非卸载再安装否则不改变
                    manager.createNotificationChannel(notificationChannel);
                    notification.setChannelId("AppTestNotificationId");
                }

注:通道构造器的API

public NotificationChannel(String id, CharSequence name, @Importance int importance) { this.mId = getTrimmedString(id); this.mName = name != null ? getTrimmedString(name.toString()) : null; this.mImportance = importance; }

参数:

id

频道的 ID。每个包裹必须是唯一的。如果值太长,则该值可能会被截断。

name

频道的用户可见名称

importance

频道的重要性等级

第五步:发通知

// 5、发出通知
                manager.notify(1, notification.build());

API:

public void notify(int id, Notification notification) { notify(null, id, notification); }

参数:

id

此通知的标识符在应用程序中是唯一的。

notification

一个通知对象,用于描述要向用户显示的内容。不得为空。

源码:

activity_main:

<?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">
<Button
    android:id="@+id/send_notice"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="点击有惊喜"/>

</LinearLayout>

MainActivity:

import androidx.appcompat.app.AppCompatActivity;
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.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.File;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button sendNotice = findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.send_notice:
                // 1、构建意图
                Intent intent = new Intent(this, MainActivity2.class);
                PendingIntent pi = PendingIntent.getActivities(this, 0, new Intent[]{intent}, 0);
                // 2、获取系统通知管理服务
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                // 3、构建 Notification和设置通知的相关属性
                Notification.Builder notification = new Notification.Builder(this)
                        .setContentTitle("恭喜您,中奖了")
                        .setContentText("快点击!快点击!快点击!进去领奖!")
                        .setWhen(System.currentTimeMillis())  // 发送时间
                        .setSmallIcon(R.mipmap.ic_launcher)   // 小biao't
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                        .setContentIntent(pi) // 跳转
                        .setAutoCancel(true) // 点击后取消通知
                        .setSound(Uri.fromFile(new File("/system/media/audio/notifications/Simple.ogg"))) // 通知铃声
                        .setVibrate(new long[] {0, 1000, 1000, 1000}) // 通知时震动
                        .setLights(Color.GREEN, 1000, 1000); // LED灯
                // 4、创建通知通道
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    // 第三个参数表示通知的重要程度,默认则只在通知栏闪烁一下
                    NotificationChannel notificationChannel = new NotificationChannel("AppTestNotificationId", "AppTestNotificationName", NotificationManager.IMPORTANCE_HIGH);
                    // 注册通道,注册后除非卸载再安装否则不改变
                    manager.createNotificationChannel(notificationChannel);
                    // 所有已发布的通知都必须指定通知通道 ID。
                    notification.setChannelId("AppTestNotificationId");
                }
                // 5、发出通知
                manager.notify(1, notification.build());
                break;
            default:
                break;
        }
    }
}

activity_main2:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    tools:context=".MainActivity2">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="241dp"
        android:gravity="center"
        android:text="恭喜您,中了250块......"
        android:textSize="30sp"
        android:textStyle="bold"
        android:layout_gravity="center" />

</LinearLayout>

MainActivity2:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
    }
}