Library弱依赖打包

为减少强依赖,运行时动态监测依赖是否存在。

例如:内置的 HTTP client 可以是 OkHttpClient 或者是 HttpURLConnection。前者拥有更高的性能,但需要引入 OkHttp 作为依赖。如果用户不愿意引入 OKHttp 的话,它将会自动用回标准库的 HttpURLConnection。

public final class PlacesHttpClientResolver {
  public static final PlacesHttpClient PLACES_HTTP_CLIENT;

  static {
    boolean hasOkHttp;
    
    try {
      Class.forName("com.squareup.okhttp.OkHttpClient");
      hasOkHttp = true;
    } catch (ClassNotFoundException e) {
      hasOkHttp = false;
    }

    PlacesApiJsonParser parser = JsonParserResolver.JSON_PARSER;

    PLACES_HTTP_CLIENT = hasOkHttp ? new OkHttpPlacesHttpClient(parser) : new HttpUrlConnectionMapsHttpClient(parser);
  }

  private PlacesHttpClientResolver() {
    throw new RuntimeException("No Instances!");
  }
}

 

 

参考:https://github.com/hehonghui/android-tech-frontier/blob/master/issue-33/Android%20Libraries%E7%9A%84%E4%BE%9D%E8%B5%96%E7%AE%A1%E7%90%86.md

点赞