当前位置: 首页 > news >正文

Android activity与service通信的三种方法

本文梳理了activity与service通信的方法。

注意:请注意服务需要在AndroidManifest中注册!!!

           请注意服务需要在AndroidManifest中注册!!!

           请注意服务需要在AndroidManifest中注册!!!

一丶Activity使用Bind()绑定服务

  1. 定义自己的服务类

    package com.example.server_testimport android.app.Service
    import android.content.Intent
    import android.os.Binder
    import android.os.IBinderclass MyService: Service() {private val binder = MyBinder()/*** 注意使用inner,否则无法访问外部类*/inner class MyBinder : Binder(){fun getService(): MyService{return this@MyService}}// 当activity调用bingService绑定服务时时,这个方法会被调用override fun onBind(p0: Intent?): IBinder = binder// 获取数据fun getData(): String = "这是来自服务的数据!!!"override fun onCreate() {super.onCreate()}override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {return super.onStartCommand(intent, flags, startId)}override fun onDestroy() {super.onDestroy()}}
  2. 绑定服务

    package com.example.server_testimport android.content.ComponentName
    import android.content.Context
    import android.content.Intent
    import android.content.ServiceConnection
    import android.os.Bundle
    import android.os.IBinder
    import android.widget.Toast
    import androidx.activity.enableEdgeToEdge
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.view.ViewCompat
    import androidx.core.view.WindowInsetsCompat
    import com.example.server_test.databinding.ActivityMainBindingclass MainActivity : AppCompatActivity() {private lateinit var binding: ActivityMainBindingprivate lateinit var service : MyServiceprivate val connection = object :ServiceConnection{override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {service = (p1 as MyService.MyBinder).getService()// 绑定成功后可以立即做某些事情?binding.testBtn.isEnabled = true}override fun onServiceDisconnected(p0: ComponentName?) {// 当服务断开连接时}}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)binding = ActivityMainBinding.inflate(layoutInflater)setContentView(binding.root)binding.testBtn.isEnabled = falsebindService(Intent(this, MyService::class.java), connection, Context.BIND_AUTO_CREATE)setupEvent()}private fun setupEvent(){binding.testBtn.setOnClickListener{// 从服务获取数据Toast.makeText(this, service.getData(), Toast.LENGTH_SHORT).show()}}override fun onDestroy() {super.onDestroy()unbindService(connection)}
    }

二、使用广播,service与activity通信

  1. 定义自己的服务类

    package com.example.server_testimport android.app.Service
    import android.content.Intent
    import android.os.Binder
    import android.os.Handler
    import android.os.IBinder
    import android.os.Looper
    import android.util.Logclass MyService: Service() {private val handler = Handler(Looper.getMainLooper())private val interval: Long = 5000 // 5秒private var isRunning = falseoverride fun onBind(p0: Intent?): IBinder? = null// 获取数据private fun getMessage(): String = "这是来自服务的数据!!!"// 发送广播消息fun sendMessage() {Log.d("send", "消息已发出")val intent = Intent("SERVICE_MESSAGE").setPackage("com.example.server_test")intent.putExtra("msg", getMessage())sendBroadcast(intent)}override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {if (!isRunning)startScheduledMessage()return START_STICKY}override fun onDestroy() {super.onDestroy()stopScheduledMessage()}// 启动定时任务private fun startScheduledMessage() {isRunning = truehandler.postDelayed(messageRunnable, interval)}// 停止定时任务private fun stopScheduledMessage() {isRunning = falsehandler.removeCallbacks(messageRunnable)}// 定时任务执行体private val messageRunnable = object : Runnable {override fun run() {if (isRunning) {sendMessage()handler.postDelayed(this, interval)}}}}
  2.  在activity定义接收器

    private val receiver = object : BroadcastReceiver() {override fun onReceive(context: Context?, intent: Intent?) {val data = intent?.getStringExtra("msg")// 可以在这里做一些事情Toast.makeText(this@MainActivity, data ?: "没有数据", Toast.LENGTH_SHORT).show()}}
  3. 注册接收器并启动服务

    package com.example.server_testimport android.annotation.SuppressLint
    import android.content.BroadcastReceiver
    import android.content.Context
    import android.content.Intent
    import android.content.IntentFilter
    import android.os.Build
    import android.os.Bundle
    import android.widget.Toast
    import androidx.annotation.RequiresApi
    import androidx.appcompat.app.AppCompatActivity
    import com.example.server_test.databinding.ActivityMainBindingclass MainActivity : AppCompatActivity() {private lateinit var binding: ActivityMainBindingprivate val receiver = object : BroadcastReceiver() {override fun onReceive(context: Context?, intent: Intent?) {val data = intent?.getStringExtra("msg")// 可以在这里做一些事情Toast.makeText(this@MainActivity, data ?: "没有数据", Toast.LENGTH_SHORT).show()}}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)binding = ActivityMainBinding.inflate(layoutInflater)setContentView(binding.root)}@RequiresApi(Build.VERSION_CODES.TIRAMISU)@SuppressLint("UnspecifiedRegisterReceiverFlag")private fun setupServer(){val filter = IntentFilter("SERVICE_MESSAGE")registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)// 启动服务startService(Intent(this, MyService::class.java))}override fun onPause() {super.onPause()unregisterReceiver(receiver)}override fun onDestroy() {// 停止服务stopService(Intent(this, MyService::class.java))super.onDestroy()}
    }

三、使用回调

作者有事暂停更新

    http://www.dtcms.com/a/289568.html

    相关文章:

  1. 30天打牢数模基础-K均值聚类
  2. (DINO)Emerging Properties in Self-Supervised Vision Transformers论文精读(逐段解析)
  3. (苍穹外卖)暑假学习理解P2
  4. 从零搭建智能搜索代理:LangGraph + 实时搜索 + PDF导出完整项目实战
  5. [C/C++安全编程]_[中级]_[如何安全使用循环语句]
  6. k8s:离线部署存在的相关问题
  7. 近期工作感想:职业规划篇
  8. 【单片机外部中断实验修改动态数码管0-99】2022-5-22
  9. Linux文件系统三要素:块划分、分区管理与inode结构解析
  10. 本地部署开源离线内容浏览器 Kiwix 并实现外部访问( Windows 版本)
  11. 【Java新特性】Java 21 新特性全解析
  12. CSS面试题及详细答案140道之(121-140)
  13. 快速理解LLM的temperature和top_p参数
  14. 设备健康管理实施案例:从技术架构到落地效果的全栈解析
  15. MCP实战案例|Trae2.0 一键创建旅行助手并一键部署EdgeOne
  16. ARFoundation系列讲解 - 101 VisionPro 真机调试
  17. Vue中组件的生命周期
  18. 建筑墙壁损伤缺陷分割数据集labelme格式7820张20类别
  19. Django ORM系统
  20. [学习] Hilbert变换:从数学原理到物理意义的深度解析与仿真实验(完整实验代码)
  21. 平安车管家|中国平安车管家入职测评16PF瑞文IQ测评答题攻略及真题题库
  22. 嵌入式系统内核镜像相关(十七)
  23. AI 的广泛应用是否会削弱人的思考能力和创造力?
  24. GaussDB select into和insert into的用法
  25. 字符串处理
  26. MySQL学习----Explain
  27. 关于堆的判断
  28. 【工具变量】A股上市公司企业合作文化数据集(2007-2023年)
  29. 测试中的bug
  30. adb常用命令