Fouad
Fouad

Reputation: 855

Android check dependency availability at runtime

Let's say I add the following dependency to my app level build.gradle file:

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

How can I check at runtime that a certain dependency exists or not?

Upvotes: 1

Views: 1086

Answers (2)

cesarmax
cesarmax

Reputation: 434

I was looking for the same and I couldn't find the answer. What I would do is the following:

A- if you do have the dependency at compilation time, then I would call any method from that library surrounded by 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.

B- 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 using reflection instead.

Hope it helps

Upvotes: 0

Murat Karagöz
Murat Karagöz

Reputation: 37594

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. There is no run-time checking for gradle dependencies.

Upvotes: 1

Related Questions