Android标准入门-Notification

1,091 阅读2分钟

创建一个NotificationManager

NotificationManager是一个通知管理器,这个对象是由系统维护的服务。是以单例模式的情况获得的。所以一般不直接实例化这个对象。再Activity中。可以使用Activity.getSystemService(String)方法来获取Notification对象。Activity.getSystemService(string)方法可以通过系统级的服务句柄。返回对应的对象。这里需要返回NotificationMnageer。所以直接传递Context.NOTIFICATION_SERVICE即可。

使用Builder构造器来创建Notification对象

使用NotificationCompat类的Builder来创建Notification对象。可以保证程序在所有的版本上都能够正常工作。Android8.0新增了通知渠道这个概念,如果没有设置。则无法通知Android8.0的机器上显示。

通知渠道(NotificationChannel)

通知渠道: Android8.0引入了通知渠道。其允许您为要显示的每种通知类型创建用户可以自定义的渠道。

通知重要程度设置,NotificationManager类中

  • IMPORTANCE_NONE: 关闭通知
  • IMPORTANCE_MIN: 开启通知,不回弹出,但是没有提升音。状态栏中无法显示
  • IMPORTANCE_LOW: 开启通知,不会弹出。不发出提示音。状态栏中显示
  • IMPORTANCE_DEFAULT: 开启通知,不回弹出,发出提示音。状态栏中显示
  • IMPORTANCE_HIGH: 开启通知。会弹出。发出提示音,状态栏中显示。

Notification常用方法说明

  1. setContentTitle(String string) 设置标题
  2. setContentText(String string) 设置文本内容
  3. setSmallIcon(int icon) 设置小图标
  4. setLargeIcon(Bitmap icon) 设置通知的大图标
  5. setColor(int argb) 设置小图标的颜色
  6. setContentIntent(PendingIntent intent) 设置点击通知后的跳转视图
  7. setAutoCancel(Boolean boolean) 设置点击通知自动清除通知
  8. setWhen(long when) 设置通知被创建的时间
package com.gm.notification_application;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.gm.notification_application.utils.notification_utils;


public class MainActivity extends AppCompatActivity {


    private Button sendNotification;
    private Button updateNotification;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendNotification = (Button)findViewById(R.id.bt_send);
        updateNotification = (Button)findViewById(R.id.bt_update);
        sendNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notification_utils.sendNotification(MainActivity.this);
                //显示更新按钮
                updateNotification.setVisibility(View.VISIBLE);
            }
        });

        updateNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notification_utils.updateNotification();
            }
        });

    }
}

注意点

  • 从Android 5.0系统开始,对于通知栏的图标进行了修改。现在Google要求,所有的应用程序通知栏的图标,应该只使用alpha图层来进行绘制。而不应该包括RGB图层

代码部分

MainActivity

package com.gm.notification_application;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.gm.notification_application.utils.notification_utils;


public class MainActivity extends AppCompatActivity {


    private Button sendNotification;
    private Button updateNotification;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendNotification = (Button)findViewById(R.id.bt_send);
        updateNotification = (Button)findViewById(R.id.bt_update);
        sendNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notification_utils.sendNotification(MainActivity.this);
                //显示更新按钮
                updateNotification.setVisibility(View.VISIBLE);
            }
        });

        updateNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notification_utils.updateNotification();
            }
        });

    }
}

notification_utils

package com.gm.notification_application.utils;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;

import androidx.core.app.NotificationCompat;

import com.gm.notification_application.MainActivity;

public class notification_utils {
    private  static NotificationManager mNotificationManager;
    private static NotificationCompat.Builder mBuilder;

    /**
     * 发送通知
     */
    public static void sendNotification(Context context){
        //设置 channel_id
        final String CHANNAL_ID = "chat";

        //获取系统通知服务
        mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

        //Android 8.0开始要设置通知渠道
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(CHANNAL_ID,
                    "chat message",NotificationManager.IMPORTANCE_DEFAULT);
            mNotificationManager.createNotificationChannel(channel);
        }

        //创建通知
        mBuilder = new NotificationCompat.Builder(context,CHANNAL_ID)
                .setContentTitle("这是通知标题")
                .setContentText("这是通知内容")
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true);

        //发送通知( id唯一,可用于更新通知时对应旧通知; 通过mBuilder.build()拿到notification对象 )
        mNotificationManager.notify(1,mBuilder.build());
    }

    /**
     * 更新通知
     */
    public static void updateNotification(){
        mBuilder.setContentTitle("你更新了通知标题");
        mBuilder.setContentText("你更新了通知内容");
        mNotificationManager.notify(1,mBuilder.build());
    }
}

页面布局

<?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:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bt_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send"
        android:textAllCaps="false"/>

    <Button
        android:id="@+id/bt_update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:text="update"
        android:textAllCaps="false"/>

</LinearLayout>