Пример #1
0
  private void configImageLoader() {
    File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
    if (cacheDir == null) {
      cacheDir = Environment.getDownloadCacheDirectory();
    }

    // TODO config image resolution cache for low end devices

    DisplayImageOptions options = getDefaultDisplayOptionsBuilder().build();
    int maxWidth = 800;
    int maxHeight = 480;
    int threadPoolSize = 1;

    ImageLoaderConfiguration.Builder builder =
        new ImageLoaderConfiguration.Builder(getApplicationContext())
            .threadPoolSize(threadPoolSize)
            .memoryCacheExtraOptions(maxWidth, maxHeight)
            .memoryCache(new LRULimitedMemoryCache(3 * 1024 * 1024))
            .diskCacheExtraOptions(maxWidth, maxHeight, null)
            .diskCache(new LimitedAgeDiskCache(cacheDir, 3600 * 24 * 7))
            .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
            .imageDownloader(new BaseImageDownloader(getApplicationContext()))
            .defaultDisplayImageOptions(options);

    ImageLoaderConfiguration config = builder.build();
    ImageLoader mImageLoader = ImageLoader.getInstance();
    mImageLoader.init(config);
  }
Пример #2
0
  public static void initImageLoaderConfig(Context context) {
    try {
      File cacheDir =
          StorageUtils.getOwnCacheDirectory(
              context, CommonUtil.getSavePath(SysConstant.FILE_SAVE_TYPE_IMAGE));
      File reserveCacheDir = StorageUtils.getCacheDirectory(context);

      int maxMemory = (int) (Runtime.getRuntime().maxMemory());
      // 使用最大可用内存值的1/8作为缓存的大小。
      int cacheSize = maxMemory / 8;
      DisplayMetrics metrics = new DisplayMetrics();
      WindowManager mWm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
      mWm.getDefaultDisplay().getMetrics(metrics);

      IMImageLoaderConfig =
          new ImageLoaderConfiguration.Builder(context)
              .memoryCacheExtraOptions(metrics.widthPixels, metrics.heightPixels)
              .threadPriority(Thread.NORM_PRIORITY - 2)
              //                    .denyCacheImageMultipleSizesInMemory()
              .memoryCache(new UsingFreqLimitedMemoryCache(cacheSize))
              .diskCacheFileNameGenerator(new Md5FileNameGenerator())
              .tasksProcessingOrder(QueueProcessingType.LIFO)
              .diskCacheExtraOptions(metrics.widthPixels, metrics.heightPixels, null)
              .diskCache(
                  new UnlimitedDiscCache(cacheDir, reserveCacheDir, new Md5FileNameGenerator()))
              .diskCacheSize(1024 * 1024 * 1024)
              .diskCacheFileCount(1000)
              .build();

      IMImageLoadInstance = ImageLoader.getInstance();
      IMImageLoadInstance.init(IMImageLoaderConfig);
    } catch (Exception e) {
      logger.e(e.toString());
    }
  }
  @Override
  public void onCreate() {
    super.onCreate();

    // force AsyncTask to be initialized in the main thread due to the bug:
    // http://stackoverflow.com/questions/4280330/onpostexecute-not-being-called-in-asynctask-handler-runtime-exception
    try {
      Class.forName("android.os.AsyncTask");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    // init image caching
    File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
    cacheDir.mkdirs(); // requires android.permission.WRITE_EXTERNAL_STORAGE

    try {
      ImageLoaderConfiguration config =
          new ImageLoaderConfiguration.Builder(getApplicationContext())
              .threadPoolSize(3)
              .threadPriority(Thread.NORM_PRIORITY - 2)
              .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
              .diskCache(
                  new LruDiscCache(cacheDir, new HashCodeFileNameGenerator(), 32 * 1024 * 1024))
              .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
              .build();

      ImageLoader.getInstance().init(config);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 /**
  * Creates reserve disk cache folder which will be used if primary disk cache folder becomes
  * unavailable
  */
 private static File createReserveDiskCacheDir(Context context) {
   File cacheDir = StorageUtils.getCacheDirectory(context, false);
   File individualDir = new File(cacheDir, "uil-images");
   if (individualDir.exists() || individualDir.mkdir()) {
     cacheDir = individualDir;
   }
   return cacheDir;
 }
Пример #5
0
 /** 初始化ImageLoader */
 public static void initImageLoader(Context context) {
   File cacheDir = StorageUtils.getCacheDirectory(context);
   //    File cacheDir= new File(getCacheDir(), "ACache");
   ImageLoaderConfiguration config =
       new ImageLoaderConfiguration.Builder(context)
           .memoryCache(new LruMemoryCache(5 * 1024 * 1024))
           .memoryCacheSize(10 * 1024 * 1024)
           .discCache(new UnlimitedDiscCache(cacheDir))
           .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
           .build();
   ImageLoader.getInstance().init(config);
 }
Пример #6
0
 private void initImageLoader() {
   DisplayImageOptions defaultOptions =
       new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build();
   File cacheDir = StorageUtils.getCacheDirectory(this);
   File cacheImg = new File(cacheDir, "IMG");
   ImageLoaderConfiguration config =
       new ImageLoaderConfiguration.Builder(getApplicationContext())
           .defaultDisplayImageOptions(defaultOptions)
           .discCache(new UnlimitedDiscCache(cacheImg))
           .discCacheSize(30 * 1024 * 1024)
           // .writeDebugLogs()
           .build();
   mImageLoader = ImageLoader.getInstance();
   mImageLoader.init(config);
 }
Пример #7
0
 private void initImageLoader(Context context) {
   File cacheDir = StorageUtils.getCacheDirectory(context);
   ImageLoaderConfiguration config =
       new ImageLoaderConfiguration.Builder(context)
           .threadPoolSize(3)
           .threadPriority(Thread.NORM_PRIORITY - 2)
           .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
           .denyCacheImageMultipleSizesInMemory()
           .diskCacheFileNameGenerator(new Md5FileNameGenerator())
           .tasksProcessingOrder(QueueProcessingType.LIFO)
           .diskCache(new UnlimitedDiskCache(cacheDir))
           .writeDebugLogs()
           .build();
   ImageLoader.getInstance().init(config);
 }
Пример #8
0
  @Override
  public void onCreate() {
    super.onCreate();
    mGa = GoogleAnalytics.getInstance(this);
    mTracker = mGa.getTracker(GA_PROPERTY_ID);

    DisplayImageOptions options =
        new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build();
    File cacheDir = StorageUtils.getCacheDirectory(this);
    ImageLoaderConfiguration config =
        new ImageLoaderConfiguration.Builder(this)
            .memoryCache(new LruMemoryCache(8 * 1024 * 1024))
            .discCache(new TotalSizeLimitedDiscCache(cacheDir, 20 * 1024 * 1024))
            .defaultDisplayImageOptions(options)
            .build();
    ImageLoader.getInstance().init(config);
  }
 /** Creates default implementation of {@link DiskCache} depends on incoming parameters */
 public static DiskCache createDiskCache(
     Context context,
     FileNameGenerator diskCacheFileNameGenerator,
     long diskCacheSize,
     int diskCacheFileCount) {
   File reserveCacheDir = createReserveDiskCacheDir(context);
   if (diskCacheSize > 0 || diskCacheFileCount > 0) {
     File individualCacheDir = StorageUtils.getIndividualCacheDirectory(context);
     LruDiscCache diskCache =
         new LruDiscCache(
             individualCacheDir, diskCacheFileNameGenerator, diskCacheSize, diskCacheFileCount);
     diskCache.setReserveCacheDir(reserveCacheDir);
     return diskCache;
   } else {
     File cacheDir = StorageUtils.getCacheDirectory(context);
     return new UnlimitedDiscCache(cacheDir, reserveCacheDir, diskCacheFileNameGenerator);
   }
 }
  private void initSettings() {
    DisplayImageOptions options =
        new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).build();

    File cacheDir = StorageUtils.getCacheDirectory(this);
    ImageLoaderConfiguration configuration =
        new ImageLoaderConfiguration.Builder(this)
            .defaultDisplayImageOptions(options)
            .diskCache(new UnlimitedDiscCache(cacheDir))
            .threadPoolSize(5)
            .build();
    ImageLoader.getInstance().init(configuration);

    m_adView = (AdView) findViewById(R.id.adview);
    m_adView.loadAd(new AdRequest());

    m_dataSource = new DataSource(this);
    m_dataSource.open();
  }
Пример #11
0
  public static void initImageLoader(Context context) {
    // This configuration tuning is custom. You can tune every option, you may tune some of them,
    // or you can create default configuration by
    //  ImageLoaderConfiguration.createDefault(this);
    // method.
    DisplayImageOptions defaultOptions =
        new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build();

    File cacheDir = StorageUtils.getCacheDirectory(context);
    ImageLoaderConfiguration config =
        new ImageLoaderConfiguration.Builder(context)
            .threadPriority(Thread.NORM_PRIORITY - 2)
            .denyCacheImageMultipleSizesInMemory()
            .discCache(new UnlimitedDiscCache(cacheDir))
            .defaultDisplayImageOptions(defaultOptions)
            .discCacheFileNameGenerator(new Md5FileNameGenerator())
            .tasksProcessingOrder(QueueProcessingType.LIFO)
            // .writeDebugLogs() // Remove for release app
            .build();
    // Initialize ImageLoader with configuration.
    ImageLoader.getInstance().init(config);
  }
 /**
  * Creates default implementation of {@link
  * com.nostra13.universalimageloader.cache.disc.DiskCache} depends on incoming parameters
  */
 public static DiskCache createDiskCache(
     Context context,
     FileNameGenerator diskCacheFileNameGenerator,
     long diskCacheSize,
     int diskCacheFileCount) {
   File reserveCacheDir = createReserveDiskCacheDir(context);
   if (diskCacheSize > 0 || diskCacheFileCount > 0) {
     File individualCacheDir = StorageUtils.getIndividualCacheDirectory(context);
     try {
       return new LruDiskCache(
           individualCacheDir,
           reserveCacheDir,
           diskCacheFileNameGenerator,
           diskCacheSize,
           diskCacheFileCount);
     } catch (IOException e) {
       L.e(e);
       // continue and create unlimited cache
     }
   }
   File cacheDir = StorageUtils.getCacheDirectory(context);
   return new UnlimitedDiskCache(cacheDir, reserveCacheDir, diskCacheFileNameGenerator);
 }
 public static void checkImageLoaderConfiguration(Context context) {
   if (!UniversalImageLoadTool.checkImageLoader()) {
     // This configuration tuning is custom. You can tune every option,
     // you may tune some of them,
     // or you can create default configuration by
     // ImageLoaderConfiguration.createDefault(this);
     // method.
     ImageLoaderConfiguration config =
         new ImageLoaderConfiguration.Builder(context)
             .threadPriority(Thread.NORM_PRIORITY)
             .denyCacheImageMultipleSizesInMemory()
             .discCacheFileNameGenerator(new Md5FileNameGenerator())
             .discCache(
                 new LimitedAgeDiscCache(
                     StorageUtils.getCacheDirectory(context),
                     new Md5FileNameGenerator(),
                     discCacheLimitTime))
             .tasksProcessingOrder(QueueProcessingType.LIFO)
             .build();
     // Initialize ImageLoader with configuration.
     ImageLoader.getInstance().init(config);
   }
 }
Пример #14
0
  public void initializeIfNeeded() {
    if (!inited) {

      // init for image loader
      File cacheDir = StorageUtils.getCacheDirectory(this);
      ImageLoaderConfiguration config =
          (new ImageLoaderConfiguration.Builder(this))
              .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
              .memoryCacheSize(2 * 1024 * 1024)
              .diskCache(new UnlimitedDiscCache(cacheDir))
              .diskCacheSize(50 * 1024 * 1024)
              .diskCacheFileCount(100)
              .build();
      ImageLoader.getInstance().init(config);

      // If fetch image fails, show the white bird icon
      Utility.displayImageOptions =
          new DisplayImageOptions.Builder()
              .cacheInMemory(true)
              .cacheOnDisk(true)
              .showImageForEmptyUri(R.drawable.icon)
              .showImageOnFail(R.drawable.icon)
              .build();

      // If fetch image fails, show the default empty icon
      Utility.userIconOptions =
          new DisplayImageOptions.Builder()
              .cacheInMemory(true)
              .cacheOnDisk(true)
              .showImageForEmptyUri(R.drawable.icon)
              .showImageOnFail(R.drawable.icon)
              .build();

      inited = true;
    }
  }
Пример #15
0
 @Override
 public void onCreate() {
   super.onCreate();
   application = this;
   WindowManager wm = (WindowManager) this.getSystemService(WINDOW_SERVICE);
   screenHeight = wm.getDefaultDisplay().getHeight();
   screenWidth = wm.getDefaultDisplay().getWidth();
   ImageLoaderConfiguration configuration =
       new ImageLoaderConfiguration.Builder(this)
           .memoryCacheExtraOptions(screenWidth, screenHeight) // 设置解析图片的大小,一般以手机屏幕大小为准
           .diskCacheExtraOptions(screenWidth, screenHeight, null) // 保存到磁盘使用的大小以及压缩方法,默认原图保存
           .threadPoolSize(3) // 线程池大小,不能太大,会出现OOM
           .threadPriority(Thread.NORM_PRIORITY - 1) // 设置线程的优先程度 5-1
           .tasksProcessingOrder(
               QueueProcessingType.FIFO) // 设置图片加载和显示队列处理的类型 默认为QueueProcessingType.
           //  FIFO注:如果设置了taskExecutor或者taskExecutorForCachedImages 此设置无效
           .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // 设置内存缓存 默认为一个当前应用可用内存的1/8大小的
           .memoryCacheSize(2 * 1024 * 1014) // 设置内存缓存的最大大小 默认为一个当前应用可用内存的1/8
           .memoryCacheSizePercentage(13) // 设置内存缓存最大大小占当前应用可用内存的百分比 默认为一个当前应用可用内存的1/8
           .diskCache(
               new UnlimitedDiskCache(
                   StorageUtils.getCacheDirectory(
                       getApplicationContext()))) // 默认为StorageUtils.getCacheDirectory(getApplicationContext()),即/mnt/sdcard/android/data/包名/cache/
           .diskCacheSize(50 * 1024 * 1024) // 设置硬盘缓存的最大大小
           .diskCacheFileCount(100) // 设置硬盘缓存的文件的最多个数
           .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // 设置硬盘缓存文件名生成规范
           .imageDownloader(new BaseImageDownloader(this)) // 设置图片下载器
           .imageDecoder(DefaultConfigurationFactory.createImageDecoder(false)) // 设置图片的解析器
           .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // 设置默认的图片显示选项
           .denyCacheImageMultipleSizesInMemory() // 不缓存图片的多种尺寸在内存中
           .writeDebugLogs() // 打印调试Log,注意上线之前要去掉这句话
           .imageDownloader(
               new BaseImageDownloader(this, 5 * 1000, 30 * 1000)) // 图片下载器的设置  超时时间   读取时间
           .build();
   ImageLoader.getInstance().init(configuration); // 使用基本配置信息初始化ImageLoader
 }
Пример #16
0
  @TargetApi(9)
  @Override
  public void onCreate() {
    if (Build.VERSION.SDK_INT >= 9 && BuildConfig.DEBUG) {
      StrictMode.setThreadPolicy(
          new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
      StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    }
    updateLanguage();
    super.onCreate();
    ACRA.init(this);

    // Needs to be setup before anything else tries to access it.
    // Perhaps the constructor is a better place, but then again,
    // it is more deterministic as to when this gets called...
    Preferences.setup(this);

    // Apply the Google PRNG fixes to properly seed SecureRandom
    PRNGFixes.apply();

    // Check that the installed app cache hasn't gotten out of sync somehow.
    // e.g. if we crashed/ran out of battery half way through responding
    // to a package installed intent. It doesn't really matter where
    // we put this in the bootstrap process, because it runs on a different
    // thread, which will be delayed by some seconds to avoid an error where
    // the database is locked due to the database updater.
    InstalledAppCacheUpdater.updateInBackground(getApplicationContext());

    // If the user changes the preference to do with filtering rooted apps,
    // it is easier to just notify a change in the app provider,
    // so that the newly updated list will correctly filter relevant apps.
    Preferences.get()
        .registerAppsRequiringRootChangeListener(
            new Preferences.ChangeListener() {
              @Override
              public void onPreferenceChange() {
                getContentResolver().notifyChange(AppProvider.getContentUri(), null);
              }
            });

    // This is added so that the bluetooth:// scheme we use for URLs the BluetoothDownloader
    // understands is not treated as invalid by the java.net.URL class. The actual Handler does
    // nothing, but its presence is enough.
    URL.setURLStreamHandlerFactory(
        new URLStreamHandlerFactory() {
          @Override
          public URLStreamHandler createURLStreamHandler(String protocol) {
            return TextUtils.equals(protocol, "bluetooth") ? new Handler() : null;
          }
        });

    final Context context = this;
    Preferences.get()
        .registerUnstableUpdatesChangeListener(
            new Preferences.ChangeListener() {
              @Override
              public void onPreferenceChange() {
                AppProvider.Helper.calcDetailsFromIndex(context);
              }
            });

    // Clear cached apk files. We used to just remove them after they'd
    // been installed, but this causes problems for proprietary gapps
    // users since the introduction of verification (on pre-4.2 Android),
    // because the install intent says it's finished when it hasn't.
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    curTheme = Theme.valueOf(prefs.getString(Preferences.PREF_THEME, Preferences.DEFAULT_THEME));
    Utils.deleteFiles(Utils.getApkDownloadDir(this), null, ".apk");
    if (!Preferences.get().shouldCacheApks()) {
      Utils.deleteFiles(Utils.getApkCacheDir(this), null, ".apk");
    }

    // Index files which downloaded, but were not removed (e.g. due to F-Droid being force
    // closed during processing of the file, before getting a chance to delete). This may
    // include both "index-*-downloaded" and "index-*-extracted.xml" files. The first is from
    // either signed or unsigned repos, and the later is from signed repos.
    Utils.deleteFiles(getCacheDir(), "index-", null);

    // As above, but for legacy F-Droid clients that downloaded under a different name, and
    // extracted to the files directory rather than the cache directory.
    // TODO: This can be removed in a a few months or a year (e.g. 2016) because people will
    // have upgraded their clients, this code will have executed, and they will not have any
    // left over files any more. Even if they do hold off upgrading until this code is removed,
    // the only side effect is that they will have a few more MiB of storage taken up on their
    // device until they uninstall and re-install F-Droid.
    Utils.deleteFiles(getCacheDir(), "dl-", null);
    Utils.deleteFiles(getFilesDir(), "index-", null);

    UpdateService.schedule(getApplicationContext());
    bluetoothAdapter = getBluetoothAdapter();

    ImageLoaderConfiguration config =
        new ImageLoaderConfiguration.Builder(getApplicationContext())
            .imageDownloader(new IconDownloader(getApplicationContext()))
            .diskCache(
                new LimitedAgeDiskCache(
                    new File(
                        StorageUtils.getCacheDirectory(getApplicationContext(), true), "icons"),
                    null,
                    new FileNameGenerator() {
                      @Override
                      public String generate(String imageUri) {
                        return imageUri.substring(imageUri.lastIndexOf('/') + 1);
                      }
                    },
                    // 30 days in secs: 30*24*60*60 = 2592000
                    2592000))
            .threadPoolSize(4)
            .threadPriority(Thread.NORM_PRIORITY - 2) // Default is NORM_PRIORITY - 1
            .build();
    ImageLoader.getInstance().init(config);

    // TODO reintroduce PinningTrustManager and MemorizingTrustManager

    // initialized the local repo information
    FDroidApp.initWifiSettings();
    startService(new Intent(this, WifiStateChangeService.class));
    // if the HTTPS pref changes, then update all affected things
    Preferences.get()
        .registerLocalRepoHttpsListeners(
            new ChangeListener() {
              @Override
              public void onPreferenceChange() {
                startService(new Intent(FDroidApp.this, WifiStateChangeService.class));
              }
            });
  }