Android中的SPI实现

news/2024/7/27 7:32:26/文章来源:https://blog.csdn.net/u011897062/article/details/135590567

Android中的SPI实现

SPI是JVM世界中的标准API,但在Android应用程序中并不常用。然而,它可以非常有用地实现插件架构。让我们探讨一下如何在Android中利用SPI。

问题

在Android中,不同的提供者为推送功能提供服务,而在大型项目中,使用单一实现是不可行的。以下是一些可用的提供者:

  • FCM(Firebase Cloud Messaging):主要的推送服务实现,但需要Google服务,可能无法在所有设备上使用。
  • ADM(Amazon Device Messaging):Amazon设备(Kindle设备)上的实现,仅在Amazon设备上运行。
  • HCM(Huawei Cloud Messaging):华为设备上的实现。
  • Baidu(Baidu Push SDK):主要用于中国的推送服务实现。

由于有如此多的服务,管理和初始化它们变得具有挑战性。

当我们需要为不同的应用程序构建提供不同的服务集时,问题变得更加困难。以下是一些示例:

  • Google Play控制台不允许发布包含百度服务的应用程序。因此,百度服务应仅包含在面向中国的构建中。
  • Amazon设备消息传递仅适用于Amazon设备,因此在仅针对Amazon应用商店的构建中包含它是有意义的。
  • 华为实现在面向华为商店的构建中是有意义的。

解决方案

为了解决这个问题,我们可以从创建推送服务实现的抽象层开始。这个抽象层应该放在一个单独的Gradle模块中,以便它可以轻松地作为其他实现模块的依赖项添加。

抽象层

我们可以通过创建以下通用接口来为推送服务定义抽象层:

package com.kurantsov.pushserviceimport android.content.Context/*** Interface used to provide push service implementation via SPI*/
interface PushService {/*** Type of the push service implementation*/val type: PushServiceType/*** Priority of the push service implementation*/val priority: PushServicePriority/*** Returns if the push service implementation is available on the device*/fun isAvailable(context: Context): Boolean/*** Initializes push service*/fun initialize(context: Context)
}/*** Describes type of the push service implementation*/
interface PushServiceType {val name: Stringval description: String
}sealed class PushServicePriority(val value: Int) {object High : PushServicePriority(0)object Medium : PushServicePriority(1)object Low : PushServicePriority(2)
}

实现

然后,我们可以基于推送服务提供者实现一个通用接口。

为此,我们可以为每个实现创建一个Gradle模块。

Firebase Cloud Messaging实现示例:

package com.kurantsov.pushservice.firebaseimport android.content.Context
import android.util.Log
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.ktx.messaging
import com.kurantsov.pushservice.PushService
import com.kurantsov.pushservice.PushServiceManager
import com.kurantsov.pushservice.PushServicePriority
import com.kurantsov.pushservice.PushServiceTypeclass FirebasePushService : PushService {override val type: PushServiceType = FirebasePushServiceTypeoverride val priority: PushServicePriority = PushServicePriority.Highoverride fun isAvailable(context: Context): Boolean {val availability =GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)return availability == ConnectionResult.SUCCESS}override fun initialize(context: Context) {Firebase.messaging.token.addOnCompleteListener { task ->if (!task.isSuccessful) {Log.w(TAG, "Fetching FCM registration token failed", task.exception)}val token = task.resultPushServiceManager.setPushToken(token, FirebasePushServiceType)}}private companion object {const val TAG = "FirebasePushService"}
}object FirebasePushServiceType : PushServiceType {override val name: String = "FCM"override val description: String = "Firebase"
}

Amazon Device Messaging实现示例:

package com.kurantsov.pushservice.amazonimport android.content.Context
import com.amazon.device.messaging.ADM
import com.kurantsov.pushservice.PushService
import com.kurantsov.pushservice.PushServicePriority
import com.kurantsov.pushservice.PushServiceType/*** Amazon device messaging implementation of the push service*/
class AmazonPushService : PushService {override val type: PushServiceType = AmazonPushServiceTypeoverride val priority: PushServicePriority = PushServicePriority.Highoverride fun isAvailable(context: Context): Boolean {return isAmazonServicesAvailable}override fun initialize(context: Context) {val adm = ADM(context)adm.registrationId?.let { token ->handleRegistrationSuccess(token)} ?: run {adm.startRegister()}}
}object AmazonPushServiceType : PushServiceType {override val name: String = "ADM"override val description: String = "Amazon"
}/*** Returns if amazon device messaging is available on the device*/
val isAmazonServicesAvailable: Boolean by lazy {try {Class.forName("com.amazon.device.messaging.ADM")true} catch (e: ClassNotFoundException) {false}
}

实现注册

为了使实现通过SPI“可发现”,我们需要进行注册。这可以通过在META-INF/services/{接口的全限定名}中添加实现的完全限定名称来完成。这需要在提供接口实现的每个模块中完成。

Firebase实现文件示例内容:

com.kurantsov.pushservice.firebase.FirebasePushService
请注意,要将服务文件夹的完整路径包含在模块的结果AAR中,路径是:{模块路径}/src/main/resources/META-INF/services

Android Studio项目视图中的SPI注册示例

用法

最后一步是使用接口实现。以下是SPI使用示例:

import java.util.ServiceLoaderprivate fun listImplementations(context: Context) {//Loading push service implementationsval serviceLoader = ServiceLoader.load(PushService::class.java)//Logging implementationsserviceLoader.sortedBy { pusService -> pusService.priority.value }.forEach { pushService ->val isAvailable = pushService.isAvailable(context)Log.d(TAG, "Push service implementation - ${pushService.type.description}, " +"available - $isAvailable")}
}

示例输出如下:

Push service implementation - Firebase, available - true
Push service implementation - Amazon, available - false
Push service implementation - Huawei, available - true
Push service implementation - Baidu, available - true

完整代码请参考

https://github.com/ArtsemKurantsou/SPI4Android

额外内容

PushServiceManager

以下是一个更“真实”的示例,展示了PushServiceManager的用法:

package com.kurantsov.pushserviceimport android.content.Context
import android.util.Log
import java.util.ServiceLoader
import java.util.concurrent.CopyOnWriteArraySet
import java.util.concurrent.atomic.AtomicBooleanobject PushServiceManager {private const val TAG = "PushServiceManager"var pushToken: PushToken = PushToken.NotInitializedprivate setprivate val isInitialized: AtomicBoolean = AtomicBoolean(false)private val tokenChangedListeners: MutableSet<OnPushTokenChangedListener> =CopyOnWriteArraySet()private var selectedPushServiceType: PushServiceType? = nullfun initialize(context: Context) {if (isInitialized.get()) {Log.d(TAG, "Push service is initialized already")return}synchronized(this) {if (isInitialized.get()) {Log.d(TAG, "Push service is initialized already")return}performServiceInitialization(context)}}private fun performServiceInitialization(context: Context) {//Loading push service implementationsval serviceLoader = ServiceLoader.load(PushService::class.java)val selectedImplementation = serviceLoader.sortedBy { pusService -> pusService.priority.value }.firstOrNull { pushService ->val isAvailable = pushService.isAvailable(context)Log.d(TAG, "Checking push service - ${pushService.type.description}, " +"available - $isAvailable")isAvailable}if (selectedImplementation != null) {selectedImplementation.initialize(context)selectedPushServiceType = selectedImplementation.typeisInitialized.set(true)Log.i(TAG, "Push service initialized with ${selectedImplementation.type.description}")} else {Log.e(TAG, "Push service implementation failed. No implementations found!")throw IllegalStateException("No push service implementations found!")}}/*** Adds listener for the push token updates. Called immediately if token is available* already.*/fun addOnPushTokenChangedListener(listener: OnPushTokenChangedListener) {tokenChangedListeners.add(listener)val currentToken = pushTokenif (currentToken is PushToken.Initialized) {listener.onPushTokenChanged(currentToken)}}/*** Removes listener for the push token updates.*/fun removeOnPushTokenChangedListener(listener: OnPushTokenChangedListener) {tokenChangedListeners.remove(listener)}/*** Called by push service implementation to notify about push token change.*/fun setPushToken(token: String, serviceType: PushServiceType) {if (selectedPushServiceType != serviceType) {Log.w(TAG, "setPushToken called from unexpected implementation. " +"Selected implementation - ${selectedPushServiceType?.description}, " +"Called by - ${serviceType.description}")return}val initializedToken = PushToken.Initialized(token, serviceType)this.pushToken = initializedTokentokenChangedListeners.forEach { listener ->listener.onPushTokenChanged(initializedToken)}}/*** Called by push service implementation to notify about push message.*/fun processMessage(message: Map<String, String>, sender: String) {Log.d(TAG, "processMessage: sender - $sender, message - $message")}}

PushServiceInitializer

为了简化推送服务的最终集成,我们可以使用App启动库,这样“app”模块就不需要添加其他内容。

Initializer:

package com.kurantsov.pushserviceimport android.content.Context
import android.util.Log
import androidx.startup.Initializerclass PushServiceInitializer : Initializer<PushServiceManager> {override fun create(context: Context): PushServiceManager {runCatching {PushServiceManager.initialize(context)}.onFailure { e ->Log.e(TAG, "create: failed to initialize push service", e)}.onSuccess {Log.d(TAG, "create: Push service initialized successfully")}return PushServiceManager}override fun dependencies(): List<Class<out Initializer<*>>> = emptyList()private companion object {const val TAG = "PushServiceInitializer"}
}

AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><application><providerandroid:name="androidx.startup.InitializationProvider"android:authorities="${applicationId}.androidx-startup"android:exported="false"tools:node="merge"><meta-dataandroid:name="com.kurantsov.pushservice.PushServiceInitializer"android:value="androidx.startup" /></provider></application>
</manifest>

编译时实现选择

由于使用了推送服务实现的SPI,我们有几个模块提供了实现。要将其添加到最终的apk中,我们只需要在实现模块上添加依赖关系。

有几种方法可以在编译时添加/删除依赖项。例如:

我们可以创建几个应用程序的构建变体,并使用基于变体的依赖关系(例如,如果我们有华为变体,我们可以使用huaweiImplementation而不是implementation;这样只会为中国变体添加依赖项)。
基于编译标志进行依赖项的添加。
以下是基于标志的方法示例( app/build.gradle.kts):

dependencies {implementation(project(":push-service:core"))implementation(project(":push-service:firebase"))if (getBooleanProperty("amazon")) {implementation(project(":push-service:amazon"))}if (getBooleanProperty("huawei")) {implementation(project(":push-service:huawei"))}if (getBooleanProperty("baidu")) {implementation(project(":push-service:baidu"))}
}fun getBooleanProperty(propertyName: String): Boolean {return properties[propertyName]?.toString()?.toBoolean() == true
}

然后,我们可以在编译过程中使用命令行中的-P{标志名称}={值}来添加这些标志。以下是添加所有实现的命令示例:

gradle :app:assemble -Pamazon=true -Phuawei=true -Pbaidu=true

aar/apk中的SPI实现

您可以使用Android Studio内置的apk资源管理器验证aar/apk文件中的SPI实现。

在aar文件中,META-INF/services文件夹位于classes.jar内部。Firebase实现aar示例:
Firebase 实现AAR 示例
在apk文件中,META-INF/services文件夹位于apk根目录中。以下是最终apk示例:
APK 示例

参考链接

https://github.com/ArtsemKurantsou/SPI4Android
https://en.wikipedia.org/wiki/Service_provider_interface
https://developer.android.com/topic/libraries/app-startup

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

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

相关文章

使用micro-app将现有项目改造成微前端,对现有项目实现增量升级

使用micro-app将现有项目改造成微前端&#xff0c;对现有项目实现增量升级 基座应用 1、安装依赖 npm i micro-zoe/micro-app --save2、在入口引入 //main.js import microApp from micro-zoe/micro-appnew Vue({ }) //在new Vue 下面执行 microApp.start()3、新增一个vue页…

Nacos和Eureka比较、统一配置管理、Nacos热更新、多环境配置共享、Nacos集群搭建步骤

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、Nacos和eureka的对比二、统一配置管理二、Nacos热更新方式一方式二 三、多环境配置共享四、Nacos集群搭建步骤&#xff08;黑马springCloud的p29&#xff0…

SpringCloud 源码系列之全局 Fegin 日志收集(okHttpClient、httpClient)

SpringCloud 源码系列之全局 Fegin 日志收集&#xff08;okHttpClient、httpClient&#xff09;目录 HttpClient 全局日志收集思路切换成HttpClient验证配置效果HttpClient 全局日志收集源码分析看源码顺带产物okHttpClient 全局日志收集总结 接上文SpringCloud OpenFegin 底层…

Python爬虫---scrapy shell 调试

Scrapy shell是Scrapy提供的一个交互式shell工具&#xff0c;它可以帮助我们进行爬虫的开发和调试。可以使用它来测试xpath或css表达式&#xff0c;查看它们是如何工作的&#xff0c;以及它们从你试图抓取的网页中提取的数据。它允许你在编写spider时交互地测试表达式&#xff…

【QT】自定义对话框及其调用

目录 1 对话框的不同调用方式 2 对话框QWDialogSize的创建和使用 3 对话框QWDialogHeaders的创建和使用 4 对话框QWDialogLocate的创建与使用 5 利用信号与槽实现交互操作 1 对话框的不同调用方式 在一个应用程序设计中&#xff0c;为了实现一些特定的功能&#xff0c;必须设计…

UI设计中插画赏析和产品色彩分析

插画赏析&#xff1a; 1. 插画是设计的原创性和艺术性的基础 无论是印刷品、品牌设计还是UI界面&#xff0c;更加风格化的插画能够将不同的风格和创意加入其中&#xff0c;在激烈的竞争中更容易因此脱颖而出。留下用户才有转化。 2. 插画是视觉触发器&#xff0c;瞬间传达大量…

13 | 使用代理ip爬取安居客房源信息

这是一个简单的Python爬虫代码,用于从安居客网站爬取房地产信息。该爬虫使用了代理IP来绕过可能的封禁,并提供了一些基本的信息抽取功能。 如果访问过多,那么可能出现了验证码 对此,最好的方法就是换ip。 使用代理IP的主要目的是保护爬虫的稳定性和隐私。以下是一些常见的原…

8.临床预测模型验证——交叉验证/Bootstrap法

基本概念 交叉验证&#xff1a; 将一定比例的数据挑选出来作为训练集&#xff0c;将其余未选中的样本作为测试集&#xff0c;先在训练集中构建模型&#xff0c;再在测试集中做预测。 内部验证&#xff1a;手动将样本随机分为训练集和测试集&#xff0c;先在训练集中构建模型…

世邦通信 SPON IP网络对讲广播系统getzoneterminaldata.php 未授权访问

产品介绍 世邦通信SPON IP网络对讲广播系统采用领先的IPAudio™技术,将音频信号以数据包形式在局域网和广域网上进行传送,是一套纯数字传输系统。 漏洞描述 spon IP网络对讲广播系统getuserdata.php存在未授权访问漏洞&#xff0c;攻击者可通过该漏洞获取后台敏感数据。 资…

解决kali beef启动失败解问题

只限于出现这个提示的时候使用 卸载 ruby apt remove ruby 卸载 beef apt remove beef-xss 重新安装ruby apt-get install ruby apt-get install ruby-dev libpcap-dev gem install eventmachine 重新安装beef apt-get install beef-xss 弄完以上步骤如果还是不行就重启kali再试…

现代雷达车载应用——第3章 MIMO雷达技术 3.4节 自动驾驶使用的高分辨成像雷达

经典著作&#xff0c;值得一读&#xff0c;英文原版下载链接【免费】ModernRadarforAutomotiveApplications资源-CSDN文库。 3.4 自动驾驶使用的高分辨成像雷达 如今&#xff0c;许多专为ADAS功能设计的汽车雷达收发器&#xff0c;如NXP半导体的MR3003和德州仪器的AWR2243&…

力扣hot100 打家劫舍 DP 滚动数组

Problem: 198. 打家劫舍 文章目录 思路复杂度&#x1f496; Code&#x1f496; DP空间优化版 思路 &#x1f468;‍&#x1f3eb; 参考地址 复杂度 时间复杂度: O ( n ) O(n) O(n) 空间复杂度: O ( n ) O(n) O(n) &#x1f496; Code class Solution {public static …

七、Qt 信号和槽

在QT4以上的版本&#xff0c;在窗体上用可以通过选中控件&#xff0c;然后点击鼠标右键单击按钮&#xff0c;选择“转到槽”。可以自动创建信号和槽。 选择clicked(),并点击 ok Qt Creator会给头文件和代码文件自动添加 这个按钮的单击事件&#xff08;信号和槽&#xff09;。 …

【征服redis5】redis的Redisson客户端

目录 1 Redisson介绍 2. 与其他Java Redis客户端的比较 3.基本的配置与连接池 3.1 依赖和SDK 3.2 配置内容解析 4 实战案例&#xff1a;优雅的让Hash的某个Field过期 5 Redisson的强大功能 1 Redisson介绍 Redisson 最初由 GitHub 用户 “mrniko” 创建&#xff0c;并在…

蓝桥杯练习题(九)

&#x1f4d1;前言 本文主要是【算法】——蓝桥杯练习题&#xff08;九&#xff09;的文章&#xff0c;如果有什么需要改进的地方还请大佬指出⛺️ &#x1f3ac;作者简介&#xff1a;大家好&#xff0c;我是听风与他&#x1f947; ☁️博客首页&#xff1a;CSDN主页听风与他 …

网络基础学习(3):交换机

1.交换机结构 &#xff08;1&#xff09;网线接口和后面的电路部分加在一起称为一个端口&#xff0c;也就是说交换机的一个端口就相当于计算机上的一块网卡。 如果在计算机上安装多个网卡&#xff0c;并让网卡接收所有网络包&#xff0c;再安装具备交换机功能的软件&#xff0…

介绍下Redis?Redis有哪些数据类型?

一、Redis介绍 Redis全称&#xff08;Remote Dictionary Server&#xff09;本质上是一个Key-Value类型的内存数据库&#xff0c;整个数据库统统加载在内存当中进行操作&#xff0c;定期通过异步操作把数据库数据flush到硬盘上进行保存。因为是纯内存操作&#xff0c;Redis的性…

【零基础入门Python数据分析】Anaconda3 JupyterNotebookseaborn版

目录 一、安装环境 python介绍 anaconda介绍 jupyter notebook介绍 anaconda3 环境安装 解决JuPyter500&#xff1a;Internal Server Error问题-CSDN博客 Jupyter notebook快捷键操作大全 二、Python基础入门 数据类型与变量 数据类型 变量及赋值 布尔类型与逻辑运算…

【HarmonyOS】消息通知场景的实现

从今天开始&#xff0c;博主将开设一门新的专栏用来讲解市面上比较热门的技术 “鸿蒙开发”&#xff0c;对于刚接触这项技术的小伙伴在学习鸿蒙开发之前&#xff0c;有必要先了解一下鸿蒙&#xff0c;从你的角度来讲&#xff0c;你认为什么是鸿蒙呢&#xff1f;它出现的意义又是…

SpringAOP-说说 JDK动态代理和 CGLIB 代理

Spring 的 AOP 是通过动态代理来实现的&#xff0c;动态代理主要有两种方式 JDK 动态代理和 Cglib 动态代理&#xff0c;这两种动态代理的使用和原理有些不同。 JDK 动态代理 Interface&#xff1a;JDK动态代理是基于接口的代理&#xff0c;它要求目标类实现一个接口。Invoca…