Android 学习之《第一行代码》第二版 笔记(十七)使用通知(N)

一、通知

应用程序发出一条通知后,手机最上方的状态栏中会显示一个通知图标,下拉状态栏后可以看到通知的详细信息。

二、用法

1. 可以在活动、广播接收器以及服务里面创建。

2. 创建通知的详细步骤:

A.)使用NotificationManager对通知进行管理:

 NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

B.)使用Builder构造器创建Notification对象(Android的很多版本对通知这部分都有或多或少的修改,为了兼容SdkVersion25及以下,使用NotificationCompat类的构造器来创建Notification对象)

//使用Builder构造器来创建Notification对象
//使用NotificationCompat来解决兼容性问题
//Notification notification = new NotificationCompat.Builder(this).build(); 已过时
//Notification notification = new NotificationCompat.Builder(this,channelId:String类型)
//channelId的实际作用是将notification进行分类,如设置不同优先级等。
Notification notification = new NotificationCompat.Builder(this,"1")
	.setContentTitle("圣旨") //设置通知标题
    .setContentText("圣旨内容嘛,好好学Android日后封你做Android程序员")//设置通知内容
    .setWhen(System.currentTimeMillis())//设置通知被创建时间,以毫秒为单位
    .setSmallIcon(R.mipmap.ic_launcher) //设置通知小图标,只能使用纯alpha图层的图片
    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))//设置通知大图标
    .setContentIntent(pi) //构建出一个延迟执行的“意图”,处理用户点击逻辑
    .setAutoCancel(true) //在点击后取消该通知
    //设置通知发出时播放一段音频,接收一个Uri参数
    .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")))
    //设置手机静止和振动的时长,以毫秒为时长,奇数下标表示振动时长,偶数下标表示静止时长
    //控制手机振动需要声明权限
    .setVibrate(new long[]{0,1000,1000,1000})
    //控制手机呼吸灯 参数一:颜色;参数二:亮起时长,毫秒为单位;参数三:暗去时长
    .setLights(Color.GREEN,1000,1000)
    //可以直接使用通知的默认效果,系统会根据当前手机环境决定播放什么铃声以及如何振动
     // .setDefaults(NotificationCompat.DEFAULT_ALL)
     .build();
manager.notify(2,notification);//调用该方法让通知显示出来,参数为id和Notification对象

对于Android 8.0 奥利奥 来说使用通知还需要配置相关的NotificationChannel

//兼容Android 8.0 需要对NotificationChannel进行相应配置
//ChannelId为"1",ChannelName为"Channel1"
NotificationChannel channel = new NotificationChannel("1","Channel1", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true); //是否在桌面icon右上角展示小红点,仅在安装后第一次显示出小红点
channel.setLightColor(Color.GREEN); //小红点颜色 依旧是红色
channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
channel.enableVibration(true); //是否开启通知振动
manager.createNotificationChannel(channel);

以上步骤,下拉系统状态栏可以看到通知的详细信息,但是点击无效果
C.)设置点击效果

  • Intent 立即执行某个动作
    PendingIntent 在某个合适的时机去执行某个动作,延迟执行的Intent
    二者都可以指明某一个“意图”,都可以用于启动活动、启动服务以及发送广播等。
  • PendingIntent 的获取方法:
    getActivity();getBroadcast();getService()
    这三个方法所接收的参数都相同:
    第一个参数:Context
    第二个参数:一般用不到,通常传入0
    第三个参数:一个Intent对象,用于构建出PendingIntent的“意图”
    第四个参数:用于确定PendingIntent的行为,四种值可选:
    FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT,通常传入0
  • NotificationCompat.Builder构造器可连缀一个setContentIntent()方法,接收一个PendingIntent对象
Intent intent = new Intent(this,NotificationActivity.class);
//参数一:Context;参数二:一般用不到,传入0即可;参数三:Intent对象;参数四:用于确定PendingIntent的行为
//参数四有四个值可选:FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT
PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);

三、Demo示例

1. 效果图

Android 学习之《第一行代码》第二版 笔记(十七)使用通知(N)
Android 学习之《第一行代码》第二版 笔记(十七)使用通知(N)
Android 学习之《第一行代码》第二版 笔记(十七)使用通知(N)
Android 学习之《第一行代码》第二版 笔记(十七)使用通知(N)
Android 学习之《第一行代码》第二版 笔记(十七)使用通知(N)

2. 代码

A.)activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.example.thinkpad.notificationtest.MainActivity">

    <Button
        android:id="@+id/send_notice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="颁布诏令"/>

</android.support.constraint.ConstraintLayout>

B.)activity_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.example.thinkpad.notificationtest.NotificationActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="24sp"
        android:text="皇上下令让我来的"/>
</android.support.constraint.ConstraintLayout>

C.)MainActivity.java

import android.app.Notification;
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.graphics.Color;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
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 = (Button)findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.send_notice:
                Intent intent = new Intent(this,NotificationActivity.class);
                //参数一:Context;参数二:一般用不到,传入0即可;参数三:Intent对象;参数四:用于确定PendingIntent的行为
                //参数四有四个值可选:FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT
                PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
                //需要使用NotificationManager类来对通知进行管理
                //通过调用getSystemService(一个字符串参数)获得 Context.NOTIFICATION_SERVICE
                NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                //兼容Android 8.0 需要对NotificationChannel进行相应配置
                //ChannelId为"1",ChannelName为"Channel1"
                NotificationChannel channel = new NotificationChannel("1",
                        "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
                channel.enableLights(true); //是否在桌面icon右上角展示小红点,仅在安装后第一次显示出小红点
                channel.setLightColor(Color.GREEN); //小红点颜色 依旧是红色
                channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                channel.enableVibration(true); //是否开启通知振动
                manager.createNotificationChannel(channel);

                //使用Builder构造器来创建Notification对象
                //使用NotificationCompat来解决兼容性问题
                //Notification notification = new NotificationCompat.Builder(this).build(); 已过时
                //Notification notification = new NotificationCompat.Builder(this,channelId:String类型)
                //channelId的实际作用是将notification进行分类,如设置不同优先级等。
                Notification notification = new NotificationCompat.Builder(this,"1")
                        .setContentTitle("圣旨") //设置通知标题
                        .setContentText("圣旨内容嘛,好好学Android日后封你做Android程序员")//设置通知内容
                        .setWhen(System.currentTimeMillis())//设置通知被创建时间,以毫秒为单位
                        .setSmallIcon(R.mipmap.ic_launcher) //设置通知小图标,只能使用纯alpha图层的图片
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))//设置通知大图标
                        .setContentIntent(pi) //构建出一个延迟执行的“意图”,处理用户点击逻辑
                        .setAutoCancel(true) //在点击后取消该通知
                        //设置通知发出时播放一段音频,接收一个Uri参数
                        .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")))
                        //设置手机静止和振动的时长,以毫秒为时长,奇数下标表示振动时长,偶数下标表示静止时长
                        //控制手机振动需要声明权限
                        .setVibrate(new long[]{0,1000,1000,1000})
                        //控制手机呼吸灯 参数一:颜色;参数二:亮起时长,毫秒为单位;参数三:暗去时长
                        .setLights(Color.GREEN,1000,1000)
                        //可以直接使用通知的默认效果,系统会根据当前手机环境决定播放什么铃声以及如何振动
                       // .setDefaults(NotificationCompat.DEFAULT_ALL)
                        .build();
                manager.notify(2,notification);//调用该方法让通知显示出来,参数为id和Notification对象
                break;
            default:
                break;
        }
    }

}

D.)NotificationActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class NotificationActivity extends AppCompatActivity {

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

E.)AndroidManifest.xml
添加

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

F.)build.gradle
Android 学习之《第一行代码》第二版 笔记(十七)使用通知(N)


整理学习自郭霖大佬的《第一行代码》
目前小白一名,持续学习Android中,如有错误请批评指正!