Android前台服务的使用(二)--使用LiveEventBus实现进程间通讯(附源码)

本文详细介绍了如何在Android中利用LiveEventBus库实现跨进程消息通讯,替代传统的广播方式,简化代码并提高效率。通过在服务(MyService)中初始化LiveEventBus,使用postAcrossApp方法发送和接收消息,以及在MainActivity中订阅和发布消息,成功实现在不同进程间的解耦通信。同时提供了完整的服务和活动代码示例。
摘要由CSDN通过智能技术生成

学更好的别人,

做更好的自己。

——《微卡智享》

7293c46e1e688e7c4b162b0367cf3f8d.jpeg

本文长度为2654,预计阅读6分钟

前言

上一篇《Android前台服务的使用(一)》介绍了Android前台服务的使用,其中通讯用的广播方式在来接消息,在文中最后也说过LiveEventBus实现了进程中的通讯,在《Android使用LiveEventBus消息实现组件间通讯》中有介绍过LiveEventBus的使用(不包括跨进程),本篇就来看看实现进程间的消息通讯。

2a8b1c9bca22ebbc5aa9a703844ff4fe.png

实现效果

3388111932661fd0f546ed5d63a0a94d.png

cb0a41a856045589919f2b0bf7658ddd.jpeg

62187d4e0bbe8cc269b32d0948f706b4.jpeg

代码实现

19714d35069f8b26e63671ff8ff1cd4d.png

微卡智享

01

加入LiveEventBus依赖项

29cbc876a4ef62a61ca7c8201c5f8432.png

在build.gradle(app)和(testsrc)中都加入LiveEventBus的依赖

dependencies {
    implementation 'io.github.jeremyliao:live-event-bus-x:1.8.0'
}

02

LiveEventBus的使用

944c64b1f484b061d338d7a2d74fb672.png

在MyService中加入InitLiveEventBus的初始化,上图中可以看到这里使用的是observeforever模式,所以要注意两点:

  1. 单独定义observe方法,

  2. 需要手动释放才可以。

4cc0dc44c121406d13460d3754011394.png

单独定义Observer

定义的Observer中可以看到,接收到的字符串信息后,我们前面加上了一个“服务端接收到的消息:”后再发送回去。重点就是postAcrossApp

LiveEventBus.get<String>(MESSAGE_RET)
                .postAcrossApp(retstr)

原来介绍的发送消息一般只有post就可以了,而跨进程的消息通讯,必须使用postAcrossApp,否则是接收不到消息的。

6e9c10f543eedb6e729d184a54831109.png

手动释放

代码中我们也把上次开启广播的方式都已经注释掉了,完整的MyService代码:

package pers.vaccae.servicedemo


import android.app.*
import android.content.Intent
import android.os.IBinder
import android.util.Log
import androidx.lifecycle.Observer
import com.jeremyliao.liveeventbus.LiveEventBus




const val TAG = "MyService"
const val MESSAGE_ACTION = "MESSAGE_ACTION"
const val MESSAGE_ID = "MESSAGE_ID"
const val MESSAGE_TYPE = "MESSAGE_TYPE"
const val MESSAGE_RET = "MESSAGE_RET"


class MyService : Service() {


    private lateinit var mMsgRecv: MessageReceiver


    private val observer = Observer<String>{
        try {
            showNotification(it)
            val retstr = "服务端接收到消息:${it}"
            LiveEventBus.get<String>(MESSAGE_RET)
                .postAcrossApp(retstr)
        }
        catch (e:Exception){
            showNotification(e.message.toString())
        }
    }


    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "service onCreate()")


        //注册广播
//        mMsgRecv = MessageReceiver()
//        val mFilter = IntentFilter()
//        mFilter.addAction(MESSAGE_ACTION)
//        registerReceiver(mMsgRecv, mFilter)
        InitLiveEventBus()
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "service onStartCommand()")


        NotificationUtil.getInstance(this, MainActivity::class.java, packageName)


        val notification = NotificationUtil.mNotifiCationBuilder
            .setContentTitle("前台服务测试")
            .setContentText("我是一个前台服务的Demo")
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(androidx.loader.R.drawable.notification_bg)
            .setContentIntent(NotificationUtil.mPendingIntent)
            .build()
        // 开始前台服务
        startForeground(110, notification)
        NotificationUtil.mNotificationManager.notify(1, notification)
        return super.onStartCommand(intent, flags, startId)


    }


    override fun onBind(intent: Intent): IBinder {
        Log.d(TAG, "service onBind()")
        TODO("Return the communication channel to the service.")
    }


    override fun onDestroy() {
        Log.d(TAG, "service onDestroy")
        //停止前台服务
        stopForeground(true)
        //终止广播
        //unregisterReceiver(mMsgRecv)


        LiveEventBus
            .get<String>(MESSAGE_TYPE)
            .removeObserver(observer)


        super.onDestroy()


    }


    /**
     * 初始化LiveEventBus
     * 1、配置LifecycleObserver(如Activity)接收消息的模式(默认值true):
     * true:整个生命周期(从onCreate到onDestroy)都可以实时收到消息
     * false:激活状态(Started)可以实时收到消息,非激活状态(Stoped)无法实时收到消息,需等到Activity重新变成激活状
     * 态,方可收到消息
     * 2、autoClear
     * 配置在没有Observer关联的时候是否自动清除LiveEvent以释放内存(默认值false)
     * */
    fun InitLiveEventBus(){
        LiveEventBus.config()
            .lifecycleObserverAlwaysActive(true)
            .autoClear(false)


        LiveEventBus.get<String>(MESSAGE_TYPE)
            .observeForever(observer)
    }


    fun showNotification(msg:String,title:String="前台服务监听"){
        Log.d(TAG, msg)
        val notification = NotificationUtil.mNotifiCationBuilder
            .setContentTitle(title)
            .setContentText(msg)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(androidx.loader.R.drawable.notification_bg)
            .setContentIntent(NotificationUtil.mPendingIntent)
            .setSound(null)
            .build()
        NotificationUtil.mNotificationManager.notify(1, notification)
    }
}

03

MainActivity中调用

13dcae7b2d3418f6f61d024d06be7b16.png

MainActivity中的订阅可以看到,observe是用的普通模式,所以无需要再进行手动释放了,会根据生命周期自己释放,而当前的MainActivity中因为和MyService在一个项目中,所以这里直接用post发送消息也一样能接收到。

caff5fa135fe7b75cb10190cc14155e4.png

而在testsrv项目的MainActivity中,我们的发送就改为postAcrossApp了,这样才能实现跨进程的通讯。

2ccb4131e25cd13433b52b4077fee477.png

这样使用LiveEventBus加上前台服务就实现的我们最初想到的业务的硬件控制的解耦,并且用LiveEventBus后不需要使用广播的方式两边写好多的代码。

源码地址

https://github.com/Vaccae/AndroidServicewithLiveEventBus

点击阅读原文可以看到“码云”的代码地址

87101a436c9c04a45842d41021a66d56.png

88c06a4e4a84ea4603e91c20a040b2e0.png

往期精彩回顾

d3a38cbd05495be0b37779c82391f2be.jpeg

Android前台服务的使用(一)


12b9553441cb83fc150404f9fd1e42c0.jpeg

Android Kotlin使用ARouter组件化路由及DataStore替代SharedPreferences保存数据


206c0137adef029cd7174e76d4637e69.jpeg

Android本地Sqlite数据库的备份和还原


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vaccae

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值