通知notification

news2024/9/22 7:21:27

通知

权限:manifest.xml,可以不提前写,后面写代码时显示缺少点击添加即可。

<uses-permission android:name="android.permission.VIBRATE"/>//振动权限
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />//通知权限
通知用到的两个类:
NotificationManager manager;
Notification note;

主体内容:(振动可以在通道里设置也可以在通知样式里设置,设置一个就可以)

中间有一个权限申请,一般申请通知权限就可以,这会在下载打开后弹出跳窗申请权限

private NotificationManager manager;
private Notification note;
manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);


//利用PendingIntent,设置点击通知后跳转的页面
Intent intent=new Intent(this,NotificationActivity.class);
PendingIntent pending=PendingIntent.getActivity(this,0,intent, PendingIntent.FLAG_IMMUTABLE);


/*//申请通知权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.POST_NOTIFICATIONS},
                        REQUEST_CODE_POST_NOTIFICATIONS);
            }
        //申请振动权限,对我的手机版本没用申请不了,还是得去设置手动设置
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.VIBRATE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.VIBRATE},
                    REQUEST_CODE_VIBRATE);
        }*/


//在Android 8之后通知要建立一个通知通道
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            NotificationChannel channel=new NotificationChannel("hhhhh","hhhhhhh",
                    NotificationManager.IMPORTANCE_HIGH);
            //注册震动
            /*Vibrator vibrator=(Vibrator) getSystemService(Context.VIBRATOR_SERVICE);*/
           // long[] vibrationPattern = {100, 200, 300, 400}; // 设置震动模式,参数为一个 long 类型数组,表示震动的时长和间隔
            // 配置通知出现时的震动(如果 Android 设备支持的话)
            //channel.enableVibration(true);
            //channel.setVibrationPattern(vibrationPattern);
            manager.createNotificationChannel(channel);
        }


//设置通知样式
note=new NotificationCompat.Builder(this,"hhhhh")
                .setContentTitle("hhhhhhh")
                .setContentText("aaaaaaa")
                .setSmallIcon(R.drawable.ic_launcher_background)
              .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_foreground))
                .setColor(Color.parseColor("#ff0000"))//设置小图标颜色
                .setContentIntent(pending)//设置点击动作
                .setAutoCancel(true)
                .setVibrate(new long[] {0,300,500,700})//设置振动,但在高版本api里好像不管用                                    
                .build();
//发送通知 
manager.notify(1,note);
//取消通知
 manager.cancel(1);

振动器

前面对于通知振动的使用可能会在高版本的api里失效,可以使用振动器来实现

 1.VibrationEffect.createOneShot(500,VibrationEffect.DEFAULT_AMPLITUDE)

VibrationEffect 是在 Android 8.0(API 26)引入的一个类,它允许你更灵活地控制设备的振动模式。你可以创建单次振动、定时振动、或者组合多个振动模式。

createOneShot(long milliseconds, int amplitude)

这个方法用于创建一个单次振动的效果。

  • milliseconds:振动持续的时间,单位为毫秒。在这个例子中,振动持续 500 毫秒(0.5 秒)。
  • amplitude:振动的强度。可以使用 VibrationEffect.DEFAULT_AMPLITUDE,它会使用设备默认的振动强度。如果你想指定振动强度,值的范围是 1 到 255,其中 255 表示最大强度。

创建了一个振动持续时间为 500 毫秒,振动强度为设备默认值的 VibrationEffect 对象。

2. vibrator.vibrate(effect)

这是一个 Vibrator 类的实例,用于控制设备的振动功能。

vibrate(VibrationEffect effect)

这个方法接受一个 VibrationEffect 对象作为参数,并根据这个对象的配置触发相应的振动模式。

3.Build.VERSION_CODES.S

  • 意思:Android 12
  • 版本号:API Level 31

4.Build.VERSION_CODES.O

  • 意思:Android 8.0(Oreo)
  • 版本号:API Level 26
//实现发一次通知,振动一次,针对不同的api
 Vibrator vibrator;
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                VibratorManager vibratorManager = (VibratorManager) getSystemService(Context.VIBRATOR_MANAGER_SERVICE);
                vibrator=vibratorManager.getDefaultVibrator();
            }else{
                vibrator=(Vibrator) getSystemService(VIBRATOR_SERVICE);
            }
            manager.notify(1,note);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                VibrationEffect effect = VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE);
                vibrator.vibrate(effect);
            } else {
                vibrator.vibrate(500);
            }

记录一次实现:

activity_main.xml

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

    <Button
        android:id="@+id/sendnotificaftion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="显示notification"
        ></Button>
    <Button
        android:id="@+id/closenotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="关闭notification"
        ></Button>


</LinearLayout>

notification_activity.xml(点击通知后的跳转页面) 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".NotificationActivity"
    android:gravity="center">

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Hello"
       ></TextView>

</LinearLayout>

参考内容:

Android开发之Notification(实现消息弹窗、提示音以及点击事件)_qtandroid 系统消息提示-CSDN博客

MainActivity.java 

package com.mystudy.notification;

import static android.content.ContentValues.TAG;

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.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationAttributes;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.os.VibratorManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.Manifest;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

public class MainAvtivity extends AppCompatActivity implements View.OnClickListener {
    private NotificationManager manager;
    private Notification note;
    private static final int REQUEST_CODE_POST_NOTIFICATIONS = 1;
    private static final int REQUEST_CODE_VIBRATE = 2;
    private Button btn_show;
    private Button btn_close;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_show=findViewById(R.id.sendnotificaftion);
        btn_close=findViewById(R.id.closenotification);
        btn_close.setOnClickListener(this);
        btn_show.setOnClickListener(this);
        manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        /*//申请通知权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.POST_NOTIFICATIONS},
                        REQUEST_CODE_POST_NOTIFICATIONS);
            }
        //申请振动权限,对我的手机版本没用申请不了,还是得去设置手动设置
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.VIBRATE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.VIBRATE},
                    REQUEST_CODE_VIBRATE);
        }*/
        //通知通道,设立振动模式没用
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            NotificationChannel channel=new NotificationChannel("ShadyPi","ShadyPi的博客针不戳",
                    NotificationManager.IMPORTANCE_HIGH);
            //注册震动
            /*Vibrator vibrator=(Vibrator) getSystemService(Context.VIBRATOR_SERVICE);*/
            long[] vibrationPattern = {100, 200, 300, 400}; // 设置震动模式,参数为一个 long 类型数组,表示震动的时长和间隔
// 配置通知出现时的震动(如果 Android 设备支持的话)
            channel.enableVibration(true);
            channel.setVibrationPattern(vibrationPattern);
            manager.createNotificationChannel(channel);
        }

        Intent intent=new Intent(this,NotificationActivity.class);
        PendingIntent pending=PendingIntent.getActivity(this,0,intent, PendingIntent.FLAG_IMMUTABLE);

        note=new NotificationCompat.Builder(this,"ShadyPi")
                .setContentTitle("帅气的宝藏博主")
                .setContentText("ShadyPi")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_foreground))
                .setColor(Color.parseColor("#ff0000"))//设置小图标颜色
                .setContentIntent(pending)//设置点击动作
                .setAutoCancel(true)
                .setVibrate(new long[] {0,300,500,700})//通过这里设置也没用
                .build();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_POST_NOTIFICATIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "Notification permission granted.");
            } else {
                Log.i(TAG, "Notification permission denied.");
            }
        }

        if (requestCode == REQUEST_CODE_VIBRATE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "Vibrate permission granted.");
            } else {
                Log.i(TAG, "Vibrate permission denied.");
            }
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.sendnotificaftion){
            //设置这个振动管理器,在静音模式下也能振动
            Vibrator vibrator;
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                VibratorManager vibratorManager = (VibratorManager) getSystemService(Context.VIBRATOR_MANAGER_SERVICE);
                vibrator=vibratorManager.getDefaultVibrator();
            }else{
                vibrator=(Vibrator) getSystemService(VIBRATOR_SERVICE);
            }
            manager.notify(1,note);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                VibrationEffect effect = VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE);
                vibrator.vibrate(effect);
            } else {
                vibrator.vibrate(500);
            }
        }else {
            manager.cancel(1);
        }
    }
}

另外一个随便一下就一个文本

效果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1916052.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

洛谷 7.10 数数

Vanya and Books - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) ac代码 #include<bits/stdc.h> typedef long long ll;#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0) const ll N1e3; using namespace std;int main() {IOS;ll x;cin>>x;ll ans0,px…

阿一课代表随堂分享:红队反向代理之使用frp搭建反向代理

frp反向代理 frp简介 frp 是一个开源、简洁易用、高性能的内网穿透和反向代理软件&#xff0c;支持 tcp, udp, http, https等协议。 frp 是一个可用于内网穿透的高性能的反向代理应用&#xff0c;分为服务端frps和客户端frpc&#xff0c;支持 tcp, udp, http, https 协议。详…

明白这两大关键点,轻松脱单不再是难题!

很多未婚男女都渴望找到心仪的伴侣&#xff0c;建立稳定的情感关系&#xff0c;但往往在脱单的过程中跌跌撞撞。平时与同学、同事之间相处得很融洽&#xff0c;一旦遇到心仪的异性&#xff0c;情商直接掉线&#xff0c;难道情商也会选择性地发挥作用吗&#xff1f;其实&#xf…

怎么将3张照片合并成一张?这几种拼接方法很实用!

怎么将3张照片合并成一张&#xff1f;在我们丰富多彩的日常生活里&#xff0c;是否总爱捕捉那些稍纵即逝的美好瞬间&#xff0c;将它们定格为一张张珍贵的图片&#xff1f;然而&#xff0c;随着时间的推移&#xff0c;这些满载回忆的宝藏却可能逐渐演变成一项管理挑战&#xff…

wifi模组Ai-M62-32S的IO映射和UDP透传测试

wifi模组Ai-M62-32S的IO映射和UDP透传测试 基本IO 映射配网示例开启UDP透传示例复位AT查询wifi是否在线配置DHCP静态IP连接wifi连接UDP开启透传 基本IO 映射 对于wifi模组Ai-62-32S来说其模组 IO 引脚&#xff08;从模组左上角逆时针排序&#xff0c;引脚序号从 1 开始&#x…

10个JavaScript One-Liners让初学者看起来很专业

原文链接&#xff1a;https://pinjarirehan.medium.com/10-javascript-one-liners-for-beginner-developers-to-look-pro-b9548353330a 原文作者&#xff1a;Rehan Pinjari 翻译&#xff1a;小圆 你是不是在辛苦码字时&#xff0c;看到别人轻松甩出一行 JavaScript 就搞定难题…

GitLab和Git

GitLab保姆级教程 文章目录 GitLab保姆级教程一、GitLab安装二、添加组和用户三、新增项目四、Git上传项目说明五、命令行指引 根据以下说明从计算机中上传现有文件&#xff1a;六、创建与合并分支七、GitLab回滚到特定版本八、数据备份与恢复九、docker中创建gitlab GIT 常用命…

maven 依赖冲突

依赖冲突 1、对于 Maven 而言&#xff0c;同一个 groupId 同一个 artifactId 下&#xff0c;只能使用一个 version。 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-math3 --><dependency><groupId>org.apache.commons</groupId&…

MVC 生成验证码

在mvc 出现之前 生成验证码思路 在一个html页面上&#xff0c;生成一个验证码&#xff0c;在把这个页面嵌入到需要验证码的页面中。 JS生成验证码 <script type"text/javascript">jQuery(function ($) {/**生成一个随机数**/function randomNum(min, max) {…

从0-1搭建一个web项目(路由目录分析)详解

本章分析vue路由目录文件详解 ObJack-Admin一款基于 Vue3.3、TypeScript、Vite3、Pinia、Element-Plus 开源的后台管理框架。在一定程度上节省您的开发效率。另外本项目还封装了一些常用组件、hooks、指令、动态路由、按钮级别权限控制等功能。感兴趣的小伙伴可以访问源码点个赞…

【计算机网络03】不花钱怎么搭建一个网络实验室

使用GNS3和虚拟机搭建网络实验室 1、安装抓包工具分析数据包2、定义和使用抓包筛选器3、安装和配置GNS34、配置路由器和VPCS5、使用WireShark捕获GNS3网络数据包6、VMware创建虚拟机7、使用思科PacketTracer 1、安装抓包工具分析数据包 官网安装wireshark&#xff1a;https://…

前端面试题26(vue3中响应式实现原理)

Vue 3 中响应式系统的实现主要依赖于 ES6 的 Proxy 对象&#xff0c;这与 Vue 2 中使用 Object.defineProperty 的方式有着本质的区别。Proxy 提供了一种更为强大且灵活的方法来拦截和定制对象的操作&#xff0c;例如获取、设置属性值等。下面是对 Vue 3 响应式系统实现方式的详…

鸿蒙语言基础类库:【@ohos.util.TreeSet (非线性容器TreeSet)】

非线性容器TreeSet 说明&#xff1a; 本模块首批接口从API version 8开始支持。后续版本的新增接口&#xff0c;采用上角标单独标记接口的起始版本。开发前请熟悉鸿蒙开发指导文档&#xff1a;gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md点击或者复制转到。 T…

PLC数据采集网关的具体使用说明-天拓四方

PLC数据采集网关通过以太网、串口等通信接口与PLC设备连接&#xff0c;实现数据的实时采集。网关内置数据处理模块&#xff0c;可以对采集到的数据进行清洗、转换和存储&#xff0c;以满足不同应用场景的需求。同时&#xff0c;PLC数据采集网关支持多种通信协议&#xff0c;如M…

用python生成带图片的二维码(python实例二十二)

目录 1.认识Python 2.环境与工具 2.1 python环境 2.2 Visual Studio Code编译 3.带图片的二维码 3.1 代码构思 3.2 代码实例 3.3 运行结果 4.总结 1.认识Python Python 是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。 Python 的设计具有很强的可读…

每日一题~abc356(对于一串连续数字 找规律,开数值桶算贡献)

添加链接描述 题意&#xff1a;对于给定的n,m 。计算0~n 每一个数和m & 之后&#xff0c;得到的数 的二进制中 1的个数的和。 一位一位的算。最多是60位。 我们只需要计算 在 1-n这些数上&#xff0c;有多少个数 第i位 为1. 因为是连续的自然数&#xff0c;每一位上1 的…

32 华三vlan案例+STP

32 华三vlan案例STP 1 开启STP 显示根桥信息 查看stp中的接口角色 查看设备的根桥ID 最小的值是根网桥 原则一 网络初始化时&#xff0c;网络中所有的STP设备都认为自己是“根桥”&#xff0c;根桥ID为自身的设备ID。通过交换BPDU&#xff0c;设备之间比较根桥ID&#xff0c;网…

品牌策划必读:9本改变游戏规则的营销经典

作为深耕品牌十余年的策划人&#xff0c;这些年自学啃下的书不计其数。 这里特意挑选了几本知名度不高但是却非常有用的“遗珠”优质品牌策划书籍分享出来。 如果你是一位初步了解品牌的人&#xff0c;这些书籍既包含了品牌理论基础&#xff0c;也有实用的实践指导。 这些书…

【区块链 + 智慧政务】省级一体化区块链平台 | FISCO BCOS应用案例

在加强数字政府建设的大背景下&#xff0c;科大讯飞广泛应用数字技术于政府管理服务&#xff0c;推动政府数字化、智能化运行。同时&#xff0c; 统筹推进业务、数据和技术的融合&#xff0c;提升跨地域、跨层级、跨部门和跨业务的协同管理和服务水平。 当前政务信息化建设中&…

Apache配置与应用(企业网站架构部署与优化)

本章结构 如果要修改以上文件中的内容&#xff0c;想要生效&#xff0c;需要在主配置文件中能够扫描到这个默认文件的修改&#xff1a; 文件在&#xff1a; Apache 连接保持 Apache 的访问控制 针对IP地址的限制缺陷是不可预知性&#xff0c;需要事先直到对方的IP才能进行基于…