Android笔记(十七):PendingIntent简介

2023-12-10 15:15

本文主要是介绍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","歌曲")}//定义跳转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?) {}override fun onServiceDisconnected(name: ComponentName?) {}}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

这篇关于Android笔记(十七):PendingIntent简介的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/477472

相关文章

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

Qt QCustomPlot库简介(最新推荐)

《QtQCustomPlot库简介(最新推荐)》QCustomPlot是一款基于Qt的高性能C++绘图库,专为二维数据可视化设计,它具有轻量级、实时处理百万级数据和多图层支持等特点,适用于科学计算、... 目录核心特性概览核心组件解析1.绘图核心 (QCustomPlot类)2.数据容器 (QCPDataC

Android DataBinding 与 MVVM使用详解

《AndroidDataBinding与MVVM使用详解》本文介绍AndroidDataBinding库,其通过绑定UI组件与数据源实现自动更新,支持双向绑定和逻辑运算,减少模板代码,结合MV... 目录一、DataBinding 核心概念二、配置与基础使用1. 启用 DataBinding 2. 基础布局

Android ViewBinding使用流程

《AndroidViewBinding使用流程》AndroidViewBinding是Jetpack组件,替代findViewById,提供类型安全、空安全和编译时检查,代码简洁且性能优化,相比Da... 目录一、核心概念二、ViewBinding优点三、使用流程1. 启用 ViewBinding (模块级

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

rust 中的 EBNF简介举例

《rust中的EBNF简介举例》:本文主要介绍rust中的EBNF简介举例,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 什么是 EBNF?2. 核心概念3. EBNF 语法符号详解4. 如何阅读 EBNF 规则5. 示例示例 1:简单的电子邮件地址

Android NDK版本迭代与FFmpeg交叉编译完全指南

《AndroidNDK版本迭代与FFmpeg交叉编译完全指南》在Android开发中,使用NDK进行原生代码开发是一项常见需求,特别是当我们需要集成FFmpeg这样的多媒体处理库时,本文将深入分析A... 目录一、android NDK版本迭代分界线二、FFmpeg交叉编译关键注意事项三、完整编译脚本示例四

Android与iOS设备MAC地址生成原理及Java实现详解

《Android与iOS设备MAC地址生成原理及Java实现详解》在无线网络通信中,MAC(MediaAccessControl)地址是设备的唯一网络标识符,本文主要介绍了Android与iOS设备M... 目录引言1. MAC地址基础1.1 MAC地址的组成1.2 MAC地址的分类2. android与I

Python 异步编程 asyncio简介及基本用法

《Python异步编程asyncio简介及基本用法》asyncio是Python的一个库,用于编写并发代码,使用协程、任务和Futures来处理I/O密集型和高延迟操作,本文给大家介绍Python... 目录1、asyncio是什么IO密集型任务特征2、怎么用1、基本用法2、关键字 async1、async