美文网首页
AutoService 使用

AutoService 使用

作者: 河马过河 | 来源:发表于2024-07-03 11:39 被阅读0次

添加依赖

    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)
            }

        }

    }
}

相关文章

网友评论

      本文标题:AutoService 使用

      本文链接:https://www.haomeiwen.com/subject/lovbcjtx.html