ChinaAppsDataDownloader.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package com.chinaappsremover.network;
  2. import android.content.Context;
  3. import android.util.Log;
  4. import com.chinaappsremover.BuildConfig;
  5. import java.io.File;
  6. import java.io.IOException;
  7. import java.util.ArrayList;
  8. import okhttp3.Cache;
  9. import okhttp3.CacheControl;
  10. import okhttp3.OkHttpClient;
  11. import okhttp3.Protocol;
  12. import okhttp3.Request;
  13. import okhttp3.Response;
  14. import okhttp3.ResponseBody;
  15. public class ChinaAppsDataDownloader {
  16. private static volatile ChinaAppsDataDownloader sInstance = null;
  17. private final OkHttpClient okHttpClient;
  18. public static ChinaAppsDataDownloader getInstance(Context applicationContext) {
  19. if (sInstance == null) {
  20. synchronized (ChinaAppsDataDownloader.class) {
  21. if (sInstance == null) {
  22. sInstance = new ChinaAppsDataDownloader(applicationContext);
  23. }
  24. }
  25. }
  26. return sInstance;
  27. }
  28. private ChinaAppsDataDownloader(Context context) {
  29. ArrayList<Protocol> protocols = new ArrayList<>();
  30. protocols.add(Protocol.HTTP_1_1);
  31. protocols.add(Protocol.HTTP_2);
  32. long cacheSize = 2L * 1024 * 1024; // 2 MiB
  33. File cacheDir = context.getDir("china_apps_data", Context.MODE_PRIVATE);
  34. Cache cache = new Cache(cacheDir, cacheSize);
  35. okHttpClient = new OkHttpClient.Builder()
  36. .protocols(protocols)
  37. .cache(cache)
  38. .build();
  39. if (sInstance != null) {
  40. throw new AssertionError(
  41. "Another instance of "
  42. + ChinaAppsDataDownloader.class.getName()
  43. + " class already exists, Can't create a new instance.");
  44. }
  45. }
  46. public Response fetch(boolean fromCache) throws IOException {
  47. String url = BuildConfig.BLACKLISTED_APP_JSON_URL;
  48. Request request = new Request.Builder()
  49. .url(url)
  50. .cacheControl(fromCache ? CacheControl.FORCE_CACHE : CacheControl.FORCE_NETWORK)
  51. .build();
  52. try {
  53. Response response = okHttpClient.newCall(request).execute();
  54. ResponseBody responseBody = response.body();
  55. if (responseBody != null) {
  56. Log.d("ChinaAppsDataDownloader", fromCache ? "Loaded cache. bytes: " + responseBody.contentLength() : "Fetched bytes: " + responseBody.contentLength());
  57. }
  58. if (response.code() == 504) {
  59. return null;
  60. }
  61. return response;
  62. } catch (IOException e) {
  63. e.printStackTrace();
  64. throw new IOException("Network error");
  65. }
  66. }
  67. }