简体   繁体   English

Android 在运行时检查依赖可用性

[英]Android check dependency availability at runtime

Let's say I add the following dependency to my app level build.gradle file:假设我将以下依赖项添加到我的应用程序级别build.gradle文件中:

compile 'com.squareup.retrofit2:retrofit:2.3.0'

How can I check at runtime that a certain dependency exists or not?如何在运行时检查某个依赖项是否存在?

You would not be able to run the App in the first place, because if the dependency does not exist you can not build the .apk . 首先,您将无法运行该应用程序,因为如果不存在依赖项,则无法构建.apk There is no run-time checking for gradle dependencies. 没有针对gradle依赖项的运行时检查。

I was looking for the same and I couldn't find the answer.我一直在寻找相同的东西,但找不到答案。 What I would do is the following:我会做的是以下几点:

  1. if you do have the dependency at compilation time , then I would call any method from that library surrounded by try/catch :如果您在编译时确实有依赖项,那么我会调用该库中由try/catch包围的任何方法:

     try { Retrofit().whateverRetrofitApi() // if you get to this line it means the library is present } catch(e: Throwable) { // if you get to this line it means the library is not present }

Probably some other exception/error like NoClassDefFoundError would be better to catch.可能会更好地捕获其他一些exception/error ,例如NoClassDefFoundError

  1. if you do not have the dependency at compilation time , and you do want to check if it's present at runtime , then you could perform the same thing, but use reflection instead.如果您在编译时没有依赖关系,并且您确实想检查它是否在运行时存在,那么您可以执行相同的操作,但使用reflection代替。

Hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM