【Android Studio】Notification通知提醒功能完整代码以及踩坑记录

news2024/10/7 4:34:34

前言:在最近学习安卓通知功能的开发中,遇到了一些坑,困扰了我一些时间,搜集了大量资料写个博客总结一下,希望对大家有帮助。 

目录

一、启动项目闪退

1.1、问题详情

1.2、解决方法

二、点击通知无法跳转

2.1、问题详情

2.2、解决方法

三、通知功能完整代码

MainActivity

activity_main.xml

NotificationActivity 


一、启动项目闪退

1.1、问题详情

完整报错如下:

Caused by: java.lang.IllegalArgumentException: com.example.myapplication: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles. at android.app.PendingIntent.checkPendingIntent(PendingIntent.java:461) at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:577) at android.app.PendingIntent.getActivity(PendingIntent.java:563) at android.app.PendingIntent.getActivity(PendingIntent.java:527) at com.example.myapplication.MainActivity.onCreate(MainActivity.java:46) at android.app.Activity.performCreate(Activity.java:8980) at android.app.Activity.performCreate(Activity.java:8958) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1526) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4013) ... 13 more

1.2、解决方法

查阅了大量资料发现在创建PendingIntent的时候因为SDK的版本导致启动app闪退,需要根据不同系统版本创建带有不同flag的PendingIntent,代码如下:

PendingIntent pendingIntent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
    pendingIntent = PendingIntent.getActivity(this, 123, intent, PendingIntent.FLAG_IMMUTABLE);
} else {
    pendingIntent = PendingIntent.getActivity(this, 123, intent, PendingIntent.FLAG_ONE_SHOT);
}

二、点击通知无法跳转

2.1、问题详情

点击通知后无法进行跳转。

2.2、解决方法

需要在AndroidManifest.xml文件里面配置一下自己创建的实体类。

三、通知功能完整代码

MainActivity

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

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.os.Build;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "leo";

    public NotificationManager manager;

    public Notification notification;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel("leo","测试通知",NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
        }

        Intent intent = new Intent(this,NotificationActivity.class);
        PendingIntent pendingIntent;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 123, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 123, intent, PendingIntent.FLAG_ONE_SHOT);
        }

        notification = new NotificationCompat.Builder(this, "leo")
                .setContentTitle("官方通知")
                .setContentText("世界那么大,我想去看看")
                .setSmallIcon(R.drawable.baseline_star_rate_24)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.baseline_star_rate_24))
                .setColor(Color.parseColor("#ff0000"))
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .build();
    }

    public void sendNotification(View view){
        manager.notify(1,notification);
    }

    public void cancelNotification(View view){
        manager.cancel(1);

    }

}

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">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="sendNotification"
        android:text="发出通知"
        >
    </Button>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="cancelNotification"
        android:text="取消通知"
        >
    </Button>

</LinearLayout>

NotificationActivity 

package com.example.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;

public class NotificationActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("leo","onCreate:进步NotificationActivity");
    }
}

运行成功:

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

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

相关文章

计算机缺失OpenCL.dll怎么办,OpenCL.dll丢失的多种解决方法

在使用电脑的过程中&#xff0c;我们经常会遇到一些开机弹窗问题。其中&#xff0c;开机弹窗找不到OpenCL.dll是一种常见的情况。本文将详细介绍开机弹窗找不到OpenCL.dll的原因分析、解决方法以及预防措辞&#xff0c;帮助大家更好地解决这一问题。 一&#xff0c;了解OpenCL.…

[AIGC] Doris:一款高效的MPP数据仓库引擎

在大数据处理的领域中&#xff0c;Apache Doris&#xff08;原百度 Palo&#xff09;是一个高效的MPP&#xff08;大规模并行处理&#xff09;数据仓库&#xff0c;最初由百度开发&#xff0c;现在已经成为Apache的孵化项目。 (图片取自百度) – 文章目录 1. Doris的基础知识…

并发 多线程

目录 thread thread 类总览 构造函数 join joinable ​编辑 detach swap yield swap 成员函数的调用 namespace::this_thread 线程同步--锁 互斥锁mutex 递归锁recursive_mutex 定时锁 Lock 锁辅助类 lock_guard​编辑 unique_lock std::lock 解决死锁问题 消息…

华为认证hcna题库背诵技巧有哪些?hcna和hcia有什么区别?

大家都知道华为认证hcna是有题库供考生刷题备考的&#xff0c;但题库中海量的题目想要在短时间背诵下来可并不是一件容易的事情&#xff0c;这就需要我们掌握一定的技巧才行。华为认证hcna题库背诵技巧有哪些? hcna和hcna这二者又有什么区别呢?今天的文章将为大家进行详细解…

鸿蒙开发设备管理:【@ohos.batteryInfo (电量信息)】

电量信息 该模块主要提供电池状态和充放电状态的查询接口。 说明&#xff1a; 本模块首批接口从API version 6开始支持。后续版本的新增接口&#xff0c;采用上角标单独标记接口的起始版本。 导入模块 import batteryInfo from ohos.batteryInfo;属性 描述电池信息。 系统能…

汇川学习笔记7 - 雕刻机项目

1、系统上电轴准备好之后&#xff0c;自动复回原点一次&#xff0c; 2、在雕刻机面板上有三个按钮用来控制画三种图形 3、注意cnc代码放置的文件夹 4、FILE0文件内容 5、FILE1文件内容 6、FILE2文件内容 7、程序代码下载地址 https://download.csdn.net/download/qq_6191667…

设置日历程序

目录 一 设计原型 二 后台源码 一 设计原型 二 后台源码 namespace 设置日历 {public partial class Form1 : Form{public Form1(){InitializeComponent();}private void dateTimePicker1_ValueChanged(object sender, EventArgs e){richTextBox1.Text dateTimePicker1.T…

CCSP自考攻略+经验总结

备考攻略 备考攻略准备阶段通读阶段精度阶段总复习阶段刷题阶段命运审判 写到最后 备考攻略 趁着对ssp知识点的理解还在&#xff0c;开始ccsp的考证之路&#xff0c;文章结构还是按照cissp备考篇的结构梳理。本次备考和cissp的离职在家备考不同&#xff0c;ccsp是在职利用非工…

鸿蒙开发Ability Kit(程序框架服务):【ServiceAbility切换】 组件切换

ServiceAbility切换 FA模型中的ServiceAbility对应Stage模型中的ServiceExtensionAbility。Stage模型下的ServiceExtensionAbility为系统API&#xff0c;只有系统应用才可以创建。因此&#xff0c;FA模型的ServiceAbility的切换&#xff0c;对于系统应用和三方应用策略有所不同…

【深度学习】实践方法论

李宏毅深度学习笔记 优化问题 训练数据的损失不够低的时候&#xff0c;到底是模型偏差&#xff0c;还是优化的问题&#xff1f; 判断方法是通过比较不同的模型来判断模型现在到底够不够大 看到一个从来没有做过的问题&#xff0c;可以先跑一些比较小的、比较浅的网络&#x…

React@16.x(42)路由v5.x(7)常见应用场景(4)- 路由切换动画

目录 1&#xff0c;实现路由切换基础样式 2&#xff0c;使用 CSSTransition 添加动画1&#xff0c;自定义动画组件 *TransitionRoute.jsx*2&#xff0c;*App.jsx*3&#xff0c;样式改动 3&#xff0c;注意点 通过一个例子来说明如何实现。 1&#xff0c;实现路由切换 基础样式…

【Linux:文件描述符】

文件描述符&#xff1a; 文件描述符的分配原则&#xff1a;最小未分配原则 每一个进程中有一个task_struct结构体&#xff08;PCB)&#xff0c;而task_struct中含有struct file_sturct*file的指针&#xff0c;该指针指向了一个struct files_struct的结构体该结构体中含有一个f…

win10系统打开Windows更新是空白的如何解决?

最近装wsl的时候&#xff0c;遇到了这个问题。查阅了很多相关资料&#xff0c;发现导致wsl --install安装不了的主要原因都集中在于windows更新组件损坏导致的&#xff0c;经过排查&#xff0c;我的这个组件确实不能够正常使用&#xff0c;可能是因为之前使用了windows激活工具…

网络治理新模式:Web3时代的社会价值重构

随着Web3技术的崛起&#xff0c;传统的网络治理模式正在经历革新&#xff0c;这不仅仅是技术的进步&#xff0c;更是对社会价值观念的挑战和重构。本文将深入探讨Web3时代的网络治理新模式&#xff0c;其背后的技术基础、社会影响以及未来的发展方向。 1. 引言 Web3时代&#…

【机器学习300问】134、什么是主成分分析(PCA)?

假设你的房间堆满了各种各样的物品&#xff0c;书籍、衣服、玩具等等&#xff0c;它们杂乱无章地散落各处。现在&#xff0c;你想要清理房间&#xff0c;但又不想扔掉任何东西&#xff0c;只是希望让房间看起来更整洁&#xff0c;更容易管理。 你开始思考&#xff0c;能否将物品…

Docker之jekins的安装

jekins官网地址&#xff1a;Jenkins Plugins &#xff08;https://plugins.jenkins.io/&#xff09; jekins 的docker 官方地址&#xff1a;https://hub.docker.com/r/jenkins/jenkins jekins 的docker 允许命令文档地址&#xff1a; docker/README.md at master jenkinsci…

Linux源码阅读笔记07-进程管理4大常用API函数

find_get_pid find_get_pid(...)函数功能&#xff1a;根据进程编号获取对应的进程描述符&#xff0c;具体Linux内核源码对应函数设计如下&#xff1a; 获取进程描述符&#xff0c;且描述符的count1&#xff0c;表示进程多一个用户 pid_task pid_task(...)函数功能&#xff1…

通达信短线抄底主升浪幅图指标公式源码

通达信短线抄底主升浪幅图指标公式源码&#xff1a; A1:REF(C,1); A2:SMA(MAX(C-A1,0),5,1)/SMA(ABS(C-A1),5,1)*1000; A3:BARSLAST(REF(CROSS("RSI.RSI1"(6,12,24),"RSI.RSI2"(6,12,24)),1)); A4:A2-LLV(A2,10); A5:(MA(A4,2)*3A4*13)/16; A6:IF(A5>1…

cuda 学习笔记4

一 基本函数 在GPU上开辟空间&#xff0c;无论定义的数据是float还是int ,还是****gpu_int,分配空间的函数都是下面固定的形式 (void**)& 1.函数定义&#xff0c;global void 是配套使用的&#xff0c;是在GPU上定义&#xff0c;也就是GPU上执行&#xff0c;CPU上调用的函数…

关于0xc000007b的一种解决方案

今天我在安装qview并运行时时&#xff0c;遇到了这个问题。 我在网上查找了许多解决方案&#xff0c;但它们大多都说是某些dll缺失或错误引起的。 这些说法应该是正确的&#xff0c;但我用了dll修复工具后&#xff0c;一点用都没有。 后来捣鼓半天后&#xff0c;我发现很可能…