Android笔记(十七):PendingIntent简介

PendingIntent翻译成中文为“待定意图”,这个翻译很好地表示了它的涵义。PendingIntent描述了封装Intent意图以及该意图要执行的目标操作。PendingIntent封装Intent的目标行为的执行是必须满足一定条件,只有条件满足,才会触发意图的目标操作。

一.获取PendingIntent对象

获取PendingIntent对象有以下几种方式:

  • PendingIntent.getActivity(Context, int, Intent, int):启动活动
  • PendingIntent.getActivities(Context, int, Intent[], int):启动多个活动,意图中为数组
  • PendingIntent.getBroadcast(Context, int, Intent, int):启动广播
  • PendingIntent.getService(Context, int, Intent, int):启动服务

参数说明:

  • Context:context上下文,PendingIntent启动活动的上下文
  • int:requestCode请求码 ,发送者发送的请求码
  • Intent:intent意图:要加载活动的意图
  • int:flags 标记

对于其中的标记可以定义为下列形式

  • FLAG_ONE_SHOT:PendingIntent对象仅使用一次;
  • FLAG_NO_CREATE:如果PendingIntent对象不存在则返回null
  • FLAG_CANCEL_CURRENT:如果PendingIntent对象已存在,则取消原有的对象,创建新的PendingIntent对象
  • FLAG_UPDATE_CURRENT:如果PendingIntent对象已存在,则保留原有的对象,修改原有对象的属性数据
  • FLAG_IMMUTABLE:PendingIntent对象是不可变的
  • FLAG_MUTABLE:PendingIntent对象是可变的
  • 另外其他Intent中支持的标记都可以在标记参数中使用。

二、应用实例

例如:在MainActivity启动前台服务播放音乐,利用前台服务的通知提供的内容跳转到其他活动例如SongActivity介绍歌曲。界面如下所示。
在这里插入图片描述
点击第一张图的播放,会播放音频,同时发布通知如第二张图所示。在第二张图的红色箭头区域点击,可以屏幕会跳转到第三张图。在第三张图中点击“返回”,则返回主活动。

1. AndroidManifest.xml清单配置权限

  <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /><uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />

2. 定义MusicService

class MusicService : Service() {lateinit var mediaPlayer: MediaPlayeroverride fun onCreate() {super.onCreate()mediaPlayer = MediaPlayer.create(this,R.raw.song3)}override fun onBind(intent: Intent): IBinder? {postNotification()playMusic()return null}override fun onUnbind(intent: Intent?): Boolean {stopMusic()return super.onUnbind(intent)}/*** 播放音乐*/private fun playMusic(){mediaPlayer.setOnPreparedListener {mediaPlayer.start()}mediaPlayer.setOnCompletionListener {mediaPlayer.release()}}/*** 停止播放*/private fun stopMusic(){if(mediaPlayer.isPlaying){mediaPlayer.stop()mediaPlayer.release()}}/*** 创建通知渠道* @param id String* @param name String*/private fun createNotificationChannel(id:String,name:String){//创建通知管理器val notificationManager =getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager//定义通知渠道val channel = NotificationChannel(id,name,NotificationManager.IMPORTANCE_DEFAULT)//创建通知渠道notificationManager.createNotificationChannel(channel)}/*** 发布通知*/private fun postNotification(){if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {createNotificationChannel("music_service","歌曲")}//定义启动服务的意图val intent = Intent(this,SongActivity::class.java)//定义跳转SongActivity的PendingIntentval descPendingIntent = getSongPendingIntent()//定义启动控制音乐播放广播接受器的PendingIntentval playPendingIntent = getPlayPendingIntent()//定义启动控制音乐停止播放广播接受器的PendingIntentval stopPendingIntent = getStopPendingIntent()//定义动作val playAction = NotificationCompat.Action(android.R.drawable.ic_media_play,"播放",playPendingIntent)val stopAction = NotificationCompat.Action(android.R.drawable.ic_media_pause,"停止",stopPendingIntent)//创建通知val notification = NotificationCompat.Builder(this,"music_service").apply{setOngoing(true)setOnlyAlertOnce(true)setContentTitle("播放音乐")setContentText("正在播放歌曲...")setSmallIcon(R.mipmap.ic_launcher)setColorized(true)color = resources.getColor(R.color.teal_200,null)setContentIntent(descPendingIntent)//            addAction(android.R.drawable.ic_media_play,"播放",playPendingIntent) //android23开始不支持
//            addAction(android.R.drawable.ic_media_pause,"停止",stopPendingIntent)//android23开始不支持addAction(playAction)addAction(stopAction)}.build()startForeground(1,notification)}/*** 跳转到歌曲介绍的界面* @return PendingIntent*/private fun getSongPendingIntent():PendingIntent{//定义启动服务的意图val intent = Intent(this,SongActivity::class.java)//定义PendingIntentreturn PendingIntent.getActivity(this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)}private fun getPlayPendingIntent(): PendingIntent {//创建意图过滤器val intentFilter = IntentFilter()//增加动作intentFilter.addAction("PLAY_ACTION")//创建音乐播放广播接受器val playReceiver = object: BroadcastReceiver(){override fun onReceive(context: Context?, intent: Intent?) {playMusic()}}//注册播放音乐广播器registerReceiver(playReceiver,intentFilter)//创建播放意图val intent = Intent("PLAY_ACTION")return PendingIntent.getBroadcast(this,2,intent,PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)}private fun getStopPendingIntent():PendingIntent{//创建意图过滤器val intentFilter = IntentFilter()//增加动作intentFilter.addAction("STOP_ACTION")//创建停止播放广播接受器val stopReceiver = object: BroadcastReceiver(){override fun onReceive(context: Context?, intent: Intent?) {stopMusic()}}//注册广播接收器registerReceiver(stopReceiver,intentFilter)//创建意图val intent = Intent("STOP_ACTION")return PendingIntent.getBroadcast(this,3,intent,PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)}
}

3.定义主活动MainActivity

class MainActivity : ComponentActivity() {lateinit var intent1:Intentval conn = object:ServiceConnection{override fun onServiceConnected(name: ComponentName?, service: IBinder?) {playMusic()}override fun onServiceDisconnected(name: ComponentName?) {stopMusic()}}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)intent1 = Intent(this,MusicService::class.java)requestNotificationPermission()setContent {Lab03Theme {// A surface container using the 'background' color from the themeSurface(modifier = Modifier.fillMaxSize(),color = MaterialTheme.colorScheme.background) {MainScreen(playAction=::playMusic,stopAction=::stopMusic)}}}}/*** 请求通知权限*/private fun requestNotificationPermission(){if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.TIRAMISU) {ActivityCompat.requestPermissions(this,arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),0)}}/*** 绑定播放音频的服务*/private fun playMusic(){bindService(intent1,conn, Context.BIND_AUTO_CREATE)}/*** 解除绑定*/private fun stopMusic(){unbindService(conn)}
}@Composable
fun MainScreen(playAction:()->Unit,stopAction:()->Unit) {Column(horizontalAlignment = Alignment.CenterHorizontally,verticalArrangement = Arrangement.Center){Row{TextButton(onClick = {playAction.invoke()}){Row{Icon(imageVector = Icons.Filled.PlayArrow,contentDescription = "play")Text("播放")}}TextButton(onClick = {stopAction.invoke()}){Row{Icon(imageVector = Icons.Filled.Stop,contentDescription = "play")Text("停止")}}}}
}

4.定义显示歌曲介绍的SongActivity

class SongActivity : ComponentActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent{Column{Text("正在播放歌曲,歌曲介绍内容描述暂时没有定义")TextButton(onClick = {//结束当前活动finish()}){Text("返回")}}}}
}

参考文献

1.PendingIntent
https://developer.android.google.cn/reference/android/app/PendingIntent

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

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

相关文章

Kotlin 中的 also 和 run:选择正确的作用域函数

在 Kotlin 中&#xff0c;also 和 run 是两个十分有用的作用域函数。 虽然它们在功能上相似&#xff0c;但各自有独特的用途和适用场景。 一、分析&#xff1a; also&#xff1a;在对象的上下文中执行给定的代码块&#xff0c;并返回对象本身。它的参数是一个接收对象并返回…

分布式分布式事务分布式锁分布式ID

目录 分布式分布式系统设计理念目标设计思路中心化去中心化 基本概念分布式与集群NginxRPC消息中间件&#xff08;MQ&#xff09;NoSQL&#xff08;非关系型数据库&#xff09; 分布式事务1 事务2 本地事务3 分布式事务4 本地事务VS分布式事务5 分布式事务场景6 CAP原理7 CAP组…

ChatGPT发展历程

ChatGPT是一个在2020年成立的在线聊天平台&#xff0c;它的发展历程如下&#xff1a; 初期阶段&#xff1a;2020年&#xff0c;在全球疫情爆发的情况下&#xff0c;ChatGPT创始人开始思考如何为人们提供一个快捷、安全、便利的在线聊天平台。他们选择使用GPT&#xff08;生成对…

(2/2)敏捷实践指南 Agile Practice Guide ([美] Project Management institute 著)

附录 A1 - 《PMBOK指南》映射 表A1显示了第六版《PMBOK指南》中定义的项目管理过程组与知识领域之间的对应关系 本附录说明了如何利用混合和敏捷方法处理《PMBOK指南》知识领域&#xff08;请参见表A1-2&#xff09;中所述的属性&#xff0c;其中涵盖了相同和不同的属性&…

conda 安装教程分享

大家好&#xff0c;我是微赚淘客系统的小编&#xff0c;也是冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01;今天我将向大家介绍如何使用conda进行安装。 首先&#xff0c;让我们来了解一下conda。conda是Anaconda发行版的一部分&#xff0c;它是一个开源的包管理系…

为什么那些删库跑路的人都极其下流

为什么那些删库跑路的人都极其下流&#xff1f;因为真的下流。注意&#xff0c;我不是针对跑路者的人品&#xff0c;遇到不公正待遇不敢反抗本身就比下流还下流&#xff0c;我说的是这种对抗方式太多低等。 干不好是能力问题&#xff0c;你不干是态度问题。记住我的话&#xf…

golang版aes-cbc-pkcs7加密解密base64hex字符串输入输出

最近项目中golang项目中使用aes加解密&#xff0c;做个记录方便以后使用 aes-cbc-pkcs7加密解密base64输入输出 type AesBase64 struct {key []byte // 允许16,24,32字节长度iv []byte // 只允许16字节长度 }func NewAesBase64(key []byte, iv []byte) *AesBase64 {return &…

C#网络应用程序(Web页面浏览器、局域网聊天程序)

目录 一、创建Web页面浏览器 1.示例源码 2.生成效果 二、局域网聊天程序 1.类 2.服务器端 3.客户端 一、创建Web页面浏览器 TextBox 控件用来输入要浏览的网页地址&#xff0c;Button控件用来执行浏览网页操作&#xff0c; WebBrowser控件用来显示要浏览的网页。这个控…

Matlab 曲线动态绘制

axes(handles.axes1); % 选定所画坐标轴 figure也可 h1 animatedline; h1.Color b; h1.LineWidth 2; h1.LineStyle -; % 线属性设置 for i 1 : length(x)addpoints(h1,x(i),y(i)); % x/y为待绘制曲线数据drawnow;pause(0.01); % 画点间停顿 end 示例&#xff1a; figure…

exynos4412—中断处理

一、什么是中断 一种硬件上的通知机制&#xff0c;用来通知CPU发生了某种需要立即处理的事件 分为&#xff1a; 内部中断 CPU执行程序的过程中&#xff0c;发生的一些硬件出错、运算出错事件&#xff08;如分母为0、溢出等等&#xff09;&#xff0c;不可屏蔽外部中断 外设发…

scitb包1.6版本发布,一个为制作专业统计表格而生的R包

目前&#xff0c;本人写的scitb包1.6版本已经正式在R语言官方CRAN上线&#xff0c;scitb包是一个为生成专业化统计表格而生的R包。 可以使用以下代码安装 install.packages("scitb")安装过旧版本的从新安装一次就可以升级了,根据粉丝的建议&#xff0c;增加了Overal…

RocketMQ-RocketMQ集群实践(搭建)

搭建RocketMQ可视化管理服务 下载可视化客户端源码下载 | RocketMQ 这里只提供了源码&#xff0c;并没有提供直接运行的jar包。将源码下载下来后&#xff0c;需要解压并进入对应的目录&#xff0c;使用maven进行编译。(需要提前安装maven客户端) mvn clean package -Dmaven.t…

手动部署1个Cloud Run service

什么是Cloud Run 来自chatgpt&#xff1a; Google Cloud Run 是一项全托管的服务器托管平台&#xff0c;它允许您在容器化的环境中运行无服务器应用程序。Cloud Run 提供了一种简单而灵活的方式来构建、部署和扩展应用程序&#xff0c;无需管理底层基础设施。 以下是 Cloud …

sql常用语法练习

表名word namecontinentareapopulationgdpAfghanistanAsia6522302550010020343000000AlbaniaEurope28748283174112960000000AlgeriaAfrica238174137100000188681000000AndorraEurope468781153712000000AngolaAfrica124670020609294100990000000.... 基础练习 基础查询 1、阅…

RocketMq实战(待完善)

目录 生产者 发送消息固定步骤 发送模式 1. 单向发送 2. 同步发送 3. 异步发送 生产消息完整代码 消费者 消费消息固定步骤 简单消费代码示例 消息模型 广播消息 顺序消息 延迟消息 批量消息 事务消息 生产者 发送消息固定步骤 1.创建消息生产者producer&#…

操作系统的运行机制+中断和异常

一、CPU状态 在CPU设计和生产的时候就划分了特权指令和非特叔指令&#xff0c;因此CPU执行一条指令前就能断出其类型 CPU有两种状态&#xff0c;“内核态”和“用户态” 处于内核态时&#xff0c;说明此时正在运行的是内核程序&#xff0c;此时可以执行特权指令。 处于用户态…

Jenkins+Maven+Gitlab+Tomcat 自动化构建打包,部署

环境准备Jenkins工具、环境、插件配置全局变量配置安装插件Deploy to containerMaven Integration plugin配置国内mvn源 创建maven项目 环境准备 1、安装服务 Jenkins工具、环境、插件配置 全局变量配置 Manage Jenkins>tools>JDK 安装 安装插件 Deploy to contai…

231206日课:高原反应的第三天

早冥读写跑&#xff08;早起、冥想、阅读、写作、跑步&#xff09; 践行第三天 一、知识基础 早起 冥想 阅读 写作 运动 二、个人化运用 日程复盘 优秀的AI生成的表格 汇总信息时间段安排睡眠时间20:54-04:57睡眠时间 (8小时3分钟)早晨时间安排04:57-05:00起床、洗漱早晨时间安…

C++异常抛出机制:throw和try_catch

文章目录 前言正文初识throw和try_catch深入&#xff08;std::runtime_error和std::exception&#xff09;异常处理的必要性 前言 还记得初学C的时候&#xff0c;我抱着《C primer 5th》这本书硬啃&#xff0c;作为一个初学者&#xff0c;里面很多东西当时都很不理解&#xff…

Docke自学笔记

概述 docker是什么呢&#xff1f;就是容器呀&#xff0c;像你用的Tomcat一样都是容器&#xff0c;只不过&#xff0c;docker可以用极少的资源来运行&#xff0c;极大的利用计算资源&#xff0c;不像你要隔离应用一样需要启用虚拟机&#xff0c;你的应用是部署在虚拟机上&#…