添加依赖
implementation 'com.google.auto.service:auto-service:1.0.1'
kapt 'com.google.auto.service:auto-service:1.0.1'
加载类工具
object AutoServiceUtil {
fun <S> load(clazz: Class<S>): S? {
val service = ServiceLoader.load(clazz).iterator()
try {
if (service.hasNext()) {
return service.next()
}
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
}
子项目
interface AdService {
companion object {
const val BANNER_PHOTO_SELECT = "banner_photo_select"
}
/**
* 展示Banner广告
* @param adContainer 广告容器
* @param scene banner类型
*/
fun showBannerAd(context: AppCompatActivity, adContainer: ViewGroup, scene: String)
}
object AdServiceWrap {
private val service by lazy {
AutoServiceUtil.load(AdService::class.java)
}
fun showBannerAd(context: AppCompatActivity, adContainer: ViewGroup, scene: String) {
service?.showBannerAd(context, adContainer, scene)
}
}
主项目
@AutoService(AdService::class)
class AdServiceImpl : AdService {
override fun showBannerAd(context: AppCompatActivity, adContainer: ViewGroup, scene: String) {
when (scene) {
AdService.BANNER_PHOTO_SELECT -> {
context.loadBanner(adContainer,AdPlacementId.Banner.MAIN_BANNER)
}
}
}
}