@Before public void setUp() { MockitoAnnotations.initMocks(this); MemoryCacheParams params = new MemoryCacheParams( 4 * ByteConstants.MB, 256, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); when(mMemoryCacheParamsSupplier.get()).thenReturn(params); CountingMemoryCache<CacheKey, CloseableImage> countingMemoryCache = BitmapCountingMemoryCacheFactory.get( mMemoryCacheParamsSupplier, mMemoryTrimmableRegistry, mPlatformBitmapFactory, true); mCacheKey = new SimpleCacheKey("key"); mAnimatedFrameCache = new AnimatedFrameCache(mCacheKey, countingMemoryCache); mFrame1 = CloseableReference.of(mock(CloseableImage.class)); mFrame2 = CloseableReference.of(mock(CloseableImage.class)); }
public static PoolParams get() { SparseIntArray DEFAULT_BUCKETS = new SparseIntArray(); DEFAULT_BUCKETS.put(1 * ByteConstants.KB, SMALL_BUCKET_LENGTH); DEFAULT_BUCKETS.put(2 * ByteConstants.KB, SMALL_BUCKET_LENGTH); DEFAULT_BUCKETS.put(4 * ByteConstants.KB, SMALL_BUCKET_LENGTH); DEFAULT_BUCKETS.put(8 * ByteConstants.KB, SMALL_BUCKET_LENGTH); DEFAULT_BUCKETS.put(16 * ByteConstants.KB, SMALL_BUCKET_LENGTH); DEFAULT_BUCKETS.put(32 * ByteConstants.KB, SMALL_BUCKET_LENGTH); DEFAULT_BUCKETS.put(64 * ByteConstants.KB, SMALL_BUCKET_LENGTH); DEFAULT_BUCKETS.put(128 * ByteConstants.KB, SMALL_BUCKET_LENGTH); DEFAULT_BUCKETS.put(256 * ByteConstants.KB, LARGE_BUCKET_LENGTH); DEFAULT_BUCKETS.put(512 * ByteConstants.KB, LARGE_BUCKET_LENGTH); DEFAULT_BUCKETS.put(1024 * ByteConstants.KB, LARGE_BUCKET_LENGTH); return new PoolParams( getMaxSizeSoftCap(), getMaxSizeHardCap(), DEFAULT_BUCKETS); }
private int getMaxCacheSize() { final int maxMemory = Math.min(mActivityManager.getMemoryClass() * ByteConstants.MB, Integer.MAX_VALUE); if (maxMemory < 32 * ByteConstants.MB) { return 4 * ByteConstants.MB; } else if (maxMemory < 64 * ByteConstants.MB) { return 6 * ByteConstants.MB; } else { // We don't want to use more ashmem on Gingerbread for now, since it doesn't respond well to // native memory pressure (doesn't throw exceptions, crashes app, crashes phone) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { return 8 * ByteConstants.MB; } else { return maxMemory / 4; } } }
private void FrescoInit() { DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(this) .setMaxCacheSize(40 * ByteConstants.MB) .setBaseDirectoryPathSupplier(new Supplier<File>() { @Override public File get() { return getCacheDir(); } }) .build(); final FrescoCacheParams bitmapCacheParams = new FrescoCacheParams(activityManager); //Set<RequestListener> listeners = new HashSet<>(); ImagePipelineConfig imagePipelineConfig = OkHttpImagePipelineConfigFactory.newBuilder(this, RetrofitClient.getInstance().getOkHttpClient()) .setMainDiskCacheConfig(diskCacheConfig) .setBitmapMemoryCacheParamsSupplier(bitmapCacheParams) .setDownsampleEnabled(true) .build(); Fresco.initialize(this, imagePipelineConfig); }
private void initUtil() { //初始化工具类 DBManager.initialInstance(new DBOpenHelper(mContext)); PermissionUtil.setContext(mContext); MediaStoreUtil.setContext(mContext); Util.setContext(mContext); ImageUriUtil.setContext(mContext); DiskCache.init(mContext); ColorUtil.setContext(mContext); PlayListUtil.setContext(mContext); final int cacheSize = (int)(Runtime.getRuntime().maxMemory() / 8); ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this) .setBitmapMemoryCacheParamsSupplier(() -> new MemoryCacheParams(cacheSize, Integer.MAX_VALUE,cacheSize,Integer.MAX_VALUE, 2 * ByteConstants.MB)) .setBitmapsConfig(Bitmap.Config.RGB_565) .setDownsampleEnabled(true) .build(); Fresco.initialize(this,config); }
/** * {@link NativeMemoryChunkPool} manages memory on the native heap, so we don't need as strict * caps as we would if we were on the Dalvik heap. However, since native memory OOMs are * significantly more problematic than Dalvik OOMs, we would like to stay conservative. */ private static int getMaxSizeSoftCap() { final int maxMemory = (int)Math.min(Runtime.getRuntime().maxMemory(), Integer.MAX_VALUE); if (maxMemory < 16 * ByteConstants.MB) { return 3 * ByteConstants.MB; } else if (maxMemory < 32 * ByteConstants.MB) { return 6 * ByteConstants.MB; } else { return 12 * ByteConstants.MB; } }
/** * We need a smaller cap for devices with less then 16 MB so that we don't run the risk of * evicting other processes from the native heap. */ private static int getMaxSizeHardCap() { final int maxMemory = (int) Math.min(Runtime.getRuntime().maxMemory(), Integer.MAX_VALUE); if (maxMemory < 16 * ByteConstants.MB) { return maxMemory / 2; } else { return maxMemory / 4 * 3; } }
/** * Our Bitmaps live in ashmem, meaning that they are pinned in androids' shared native memory. * Therefore, we are not constrained by the max heap size of the dalvik heap, but we want to make * sure we don't use too much memory on low end devices, so that we don't force other background * process to be evicted. */ private static int getMaxSizeHardCap() { final int maxMemory = (int)Math.min(Runtime.getRuntime().maxMemory(), Integer.MAX_VALUE); if (maxMemory > 16 * ByteConstants.MB) { return maxMemory / 4 * 3; } else { return maxMemory / 2; } }
private int getMaxCacheSize() { final int maxMemory = (int) Math.min(Runtime.getRuntime().maxMemory(), Integer.MAX_VALUE); if (maxMemory < 16 * ByteConstants.MB) { return 1 * ByteConstants.MB; } else if (maxMemory < 32 * ByteConstants.MB) { return 2 * ByteConstants.MB; } else { return 4 * ByteConstants.MB; } }
private int getMaxCacheSize() { final int maxMemory = Math.min(mActivityManager.getMemoryClass() * ByteConstants.MB, Integer.MAX_VALUE); if (maxMemory < 32 * ByteConstants.MB) { return 4 * ByteConstants.MB; } else if (maxMemory < 64 * ByteConstants.MB) { return 6 * ByteConstants.MB; } else { return maxMemory / 5; } }
public void initFresco(){ String sign = PreferencesHelper.getCookie(); DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(mContext) .setBaseDirectoryPath(mContext.getFilesDir()) .setBaseDirectoryName("image_cache") .setMaxCacheSize(50 * ByteConstants.MB) .setMaxCacheSizeOnLowDiskSpace(10 * ByteConstants.MB) .setMaxCacheSizeOnVeryLowDiskSpace(2 * ByteConstants.MB) .build(); ImagePipelineConfig config = ImagePipelineConfig.newBuilder(mContext) .setNetworkFetcher(new ElnImageDownloaderFetcher(sign,mContext)) .setMainDiskCacheConfig(diskCacheConfig).build(); Fresco.initialize(mContext, config); }
public void init(final Context context) { final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); final int MAX_DISK_CACHE_SIZE = 300 * ByteConstants.MB; final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 3; final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams( MAX_MEMORY_CACHE_SIZE, Integer.MAX_VALUE, MAX_MEMORY_CACHE_SIZE, Integer.MAX_VALUE, Integer.MAX_VALUE); DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(context) .setMaxCacheSize(MAX_DISK_CACHE_SIZE)//最大缓存 .setBaseDirectoryName("udesk")//子目录 .setBaseDirectoryPathSupplier(new Supplier<File>() { @Override public File get() { return UdeskUtil.getExternalCacheDir(context); } }) .build(); ImagePipelineConfig config = ImagePipelineConfig.newBuilder(context) .setBitmapMemoryCacheParamsSupplier( new Supplier<MemoryCacheParams>() { public MemoryCacheParams get() { return bitmapCacheParams; } }) .setMainDiskCacheConfig(diskCacheConfig) .setDownsampleEnabled(true) .setBitmapsConfig(Bitmap.Config.RGB_565) .build(); Fresco.initialize(context, config); }
private int getMaxCacheSize(){ final int maxMemory = Math.min(activityManager.getMemoryClass() * ByteConstants.MB, Integer.MAX_VALUE); if(maxMemory < 32 *ByteConstants.MB){ return 4 * ByteConstants.MB; }else if(maxMemory < 64* ByteConstants.MB){ return 6 * ByteConstants.MB; }else { return maxMemory/4; } }
public static void init(Context context, File baseDirectoryPath) { ImagePipelineConfig.Builder imagePipelineConfigBuilder = ImagePipelineConfig.newBuilder(context) .setMainDiskCacheConfig(DiskCacheConfig.newBuilder(context) .setBaseDirectoryPath(baseDirectoryPath) .setBaseDirectoryName("original") .build()) .setDownsampleEnabled(true); ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); Supplier<MemoryCacheParams> memoryCacheParamsSupplier = new DefaultBitmapMemoryCacheParamsSupplier(activityManager) { @Override public MemoryCacheParams get() { int maxCacheEntries = 256; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { maxCacheEntries = 64; } return new MemoryCacheParams( getMaxCacheSize(), maxCacheEntries, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); } private int getMaxCacheSize() { final int maxMemory = Math.min(activityManager.getMemoryClass() * ByteConstants.MB, Integer.MAX_VALUE); if (maxMemory < 32 * ByteConstants.MB) { return 4 * ByteConstants.MB; } else if (maxMemory < 64 * ByteConstants.MB) { return 6 * ByteConstants.MB; } else { return maxMemory / 4; } } }; imagePipelineConfigBuilder.setBitmapMemoryCacheParamsSupplier(memoryCacheParamsSupplier); Fresco.initialize(context, imagePipelineConfigBuilder.build()); }
public static void init(Context context){ try { File lrcCacheDir = getDiskCacheDir(context, "lyric"); if (!lrcCacheDir.exists()) lrcCacheDir.mkdir(); mLrcCache = DiskLruCache.open(lrcCacheDir, getAppVersion(context), 1, 10 * ByteConstants.MB); } catch (IOException e) { e.printStackTrace(); } }
public static List<Song> getAllSong(){ ArrayList<Song> songs = new ArrayList<>(); Cursor cursor = null; //默认过滤文件大小500K Constants.SCAN_SIZE = SPUtil.getValue(mContext,"Setting","ScanSize",-1); if( Constants.SCAN_SIZE < 0) { Constants.SCAN_SIZE = 500 * ByteConstants.KB; SPUtil.putValue(mContext,"Setting","ScanSize",500 * ByteConstants.KB); } try { cursor = mContext.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Audio.Media.SIZE + ">" + Constants.SCAN_SIZE + getBaseSelection(), null, SongAdapter.SORT + SongAdapter.ASCDESC); if(cursor != null) { while (cursor.moveToNext()) { songs.add(getMP3Info(cursor)); } } }catch (Exception e){ e.printStackTrace(); } finally { if(cursor != null && !cursor.isClosed()) cursor.close(); } return songs; }
/** * 获得所有歌曲id * @return */ public static ArrayList<Integer> getAllSongsId() { ArrayList<Integer> allSongList = new ArrayList<>(); ContentResolver resolver = mContext.getContentResolver(); Cursor cursor = null; //默认过滤文件大小500K Constants.SCAN_SIZE = SPUtil.getValue(mContext,"Setting","ScanSize",-1); if( Constants.SCAN_SIZE < 0) { Constants.SCAN_SIZE = 500 * ByteConstants.KB; SPUtil.putValue(mContext,"Setting","ScanSize",500 * ByteConstants.KB); } try{ cursor = resolver.query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Audio.Media.SIZE + ">" + Constants.SCAN_SIZE + MediaStoreUtil.getBaseSelection(), null, SPUtil.getValue(mContext,"Setting","Sort",MediaStore.Audio.Media.DEFAULT_SORT_ORDER) + SPUtil.getValue(mContext,"Setting","AscDesc"," asc")); if(cursor != null) { while (cursor.moveToNext()) { allSongList.add(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID))); } } } catch (Exception e){ e.printStackTrace(); } finally { if(cursor != null && !cursor.isClosed()) cursor.close(); } return allSongList; }
/** * 获得文件夹信息 * @return */ public static Map<String,List<Integer>> getFolder(){ ContentResolver resolver = mContext.getContentResolver(); Cursor cursor = null; Map<String,List<Integer>> folder = new TreeMap<>(String::compareToIgnoreCase); //默认过滤文件大小500K Constants.SCAN_SIZE = SPUtil.getValue(mContext,"Setting","ScanSize",-1); if( Constants.SCAN_SIZE < 0) { Constants.SCAN_SIZE = 500 * ByteConstants.KB; SPUtil.putValue(mContext,"Setting","ScanSize",500 * ByteConstants.KB); } try{ cursor = resolver.query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media._ID,MediaStore.Audio.Media.DATA}, MediaStore.Audio.Media.SIZE + ">" + Constants.SCAN_SIZE + MediaStoreUtil.getBaseSelection(), null, null); if(cursor != null) { while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)); //根据歌曲路径对歌曲按文件夹分类 String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); sortFolder(folder,id,path); } } } catch (Exception e){ e.printStackTrace(); } finally { if(cursor != null && !cursor.isClosed()) cursor.close(); } return folder; }
/** * 获得所有歌曲id 并按文件夹分类 * @return */ public static ArrayList<Integer> getAllSongsIdWithFolder() { ArrayList<Integer> allSongList = new ArrayList<>(); ContentResolver resolver = mContext.getContentResolver(); Cursor cursor = null; //默认过滤文件大小500K Constants.SCAN_SIZE = SPUtil.getValue(mContext,"Setting","ScanSize",-1); if( Constants.SCAN_SIZE < 0) { Constants.SCAN_SIZE = 500 * ByteConstants.KB; SPUtil.putValue(mContext,"Setting","ScanSize",500 * ByteConstants.KB); } try{ cursor = resolver.query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media._ID,MediaStore.Audio.Media.DATA}, MediaStore.Audio.Media.SIZE + ">" + Constants.SCAN_SIZE + MediaStoreUtil.getBaseSelection(), null, SPUtil.getValue(mContext,"Setting","Sort",MediaStore.Audio.Media.DEFAULT_SORT_ORDER) + SPUtil.getValue(mContext,"Setting","AscDesc"," asc")); if(cursor != null) { Global.FolderMap.clear(); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)); allSongList.add(id); //根据歌曲路径对歌曲按文件夹分类 String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); sortFolder(Global.FolderMap,id,path); } } } catch (Exception e){ e.printStackTrace(); } finally { if(cursor != null && !cursor.isClosed()) cursor.close(); } return allSongList; }
protected ImagePipelineConfig getFrescoConfig(Context context, String imgCachePath) { DiskCacheConfig diskCache = DiskCacheConfig .newBuilder(context) .setBaseDirectoryPath(new File(imgCachePath)) .setBaseDirectoryName("imgcache") .setMaxCacheSize(64 * ByteConstants.MB) .setMaxCacheSizeOnLowDiskSpace(10 * ByteConstants.MB) .setMaxCacheSizeOnVeryLowDiskSpace(2 * ByteConstants.MB) .build(); return ImagePipelineConfig.newBuilder(context) .setMainDiskCacheConfig(diskCache) .setDownsampleEnabled(true) .build(); }
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preference_screen); colsDetail = (int) SPUtils.get(getActivity(), AppConfig.cols_detail, 0); RadioPreference cols = (RadioPreference) findPreference(AppConfig.cols_detail); cols.setSummary("当前显示列数: " + (colsDetail + 1) + "\n图册页加载图片一般较大,同时显示多列对设备性能要求较高,请酌情选择"); EditTextPreference downloadPath = (EditTextPreference) findPreference(getResources().getString(R.string.download_path)); downloadPath.setSummary((String) SPUtils.get(getActivity(), AppConfig.download_path, AppConfig.DOWNLOAD_PATH)); noMedia = new File((String) SPUtils.get(getActivity(), AppConfig.download_path, AppConfig.DOWNLOAD_PATH) + File.separatorChar + ".nomedia"); SwitchPreference noMediaSwitch = (SwitchPreference) findPreference(AppConfig.hide_pic); if (noMedia.exists()) noMediaSwitch.setChecked(true); else noMediaSwitch.setChecked(false); Fresco.getImagePipelineFactory().getMainFileCache().trimToMinimum(); float size = (float) Fresco.getImagePipelineFactory().getMainFileCache().getSize() / ByteConstants.MB; cacheSize = (EditTextPreference) findPreference(getResources().getString(R.string.cache_size)); cacheSize.setSummary(String.format("已使用 %.2f MB", size)); }
public static ImagePipelineConfig getDefaultImagePipelineConfig(Context context) { final int cacheSize = (int) SharedPreferencesUtil.getData(HViewerApplication.mContext, SettingFragment.KEY_PREF_CACHE_SIZE, 300); MAX_DISK_CACHE_VERYLOW_SIZE = cacheSize / 5 * ByteConstants.MB; MAX_DISK_CACHE_LOW_SIZE = cacheSize * 3 / 5 * ByteConstants.MB; MAX_DISK_CACHE_SIZE = cacheSize * ByteConstants.MB; //内存配置 final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams( MAX_MEMORY_CACHE_SIZE, // 内存缓存中总图片的最大大小,以字节为单位。 Integer.MAX_VALUE, // 内存缓存中图片的最大数量。 MAX_MEMORY_CACHE_SIZE, // 内存缓存中准备清除但尚未被删除的总图片的最大大小,以字节为单位。 Integer.MAX_VALUE, // 内存缓存中准备清除的总图片的最大数量。 Integer.MAX_VALUE); // 内存缓存中单个图片的最大大小。 //修改内存图片缓存数量,空间策略(这个方式有点恶心) Supplier<MemoryCacheParams> mSupplierMemoryCacheParams = new Supplier<MemoryCacheParams>() { @Override public MemoryCacheParams get() { return bitmapCacheParams; } }; //小图片的磁盘配置 DiskCacheConfig diskSmallCacheConfig = DiskCacheConfig.newBuilder(context) .setBaseDirectoryPath(getDiskCacheDir(context)) //缓存图片基路径 .setBaseDirectoryName(IMAGE_PIPELINE_SMALL_CACHE_DIR) //文件夹名 .setMaxCacheSize(MAX_DISK_CACHE_SIZE) //默认缓存的最大大小。 .setMaxCacheSizeOnLowDiskSpace(MAX_SMALL_DISK_LOW_CACHE_SIZE) //缓存的最大大小,使用设备时低磁盘空间。 .setMaxCacheSizeOnVeryLowDiskSpace(MAX_SMALL_DISK_VERYLOW_CACHE_SIZE) //缓存的最大大小,当设备极低磁盘空间 .setDiskTrimmableRegistry(NoOpDiskTrimmableRegistry.getInstance()) .build(); //默认图片的磁盘配置 DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(context) .setBaseDirectoryPath(getDiskCacheDir(context))//缓存图片基路径 .setBaseDirectoryName(IMAGE_PIPELINE_CACHE_DIR) //文件夹名 .setMaxCacheSize(MAX_DISK_CACHE_SIZE) //默认缓存的最大大小。 .setMaxCacheSizeOnLowDiskSpace(MAX_DISK_CACHE_LOW_SIZE) //缓存的最大大小,使用设备时低磁盘空间。 .setMaxCacheSizeOnVeryLowDiskSpace(MAX_DISK_CACHE_VERYLOW_SIZE) //缓存的最大大小,当设备极低磁盘空间 .setDiskTrimmableRegistry(NoOpDiskTrimmableRegistry.getInstance()) .build(); // 自定义使用okhttp进行请求 OkHttpClient okHttpClient = new OkHttpClient.Builder() .addNetworkInterceptor(new StethoInterceptor()) .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .dns(new HttpDns()) .build(); //缓存图片配置 ImagePipelineConfig.Builder configBuilder = ImagePipelineConfig.newBuilder(context) .setBitmapsConfig(Bitmap.Config.RGB_565) .setBitmapMemoryCacheParamsSupplier(mSupplierMemoryCacheParams) .setSmallImageDiskCacheConfig(diskSmallCacheConfig) .setMainDiskCacheConfig(diskCacheConfig) .setMemoryTrimmableRegistry(NoOpMemoryTrimmableRegistry.getInstance()) .setResizeAndRotateEnabledForNetwork(true) .setNetworkFetcher(new MyOkHttpNetworkFetcher(okHttpClient)); // 这段代码用于清理缓存 NoOpMemoryTrimmableRegistry.getInstance().registerMemoryTrimmable(new MemoryTrimmable() { @Override public void trim(MemoryTrimType trimType) { final double suggestedTrimRatio = trimType.getSuggestedTrimRatio(); Logger.d("ImagePipeline", String.format("onCreate suggestedTrimRatio : %d", suggestedTrimRatio)); if (MemoryTrimType.OnCloseToDalvikHeapLimit.getSuggestedTrimRatio() == suggestedTrimRatio || MemoryTrimType.OnSystemLowMemoryWhileAppInBackground.getSuggestedTrimRatio() == suggestedTrimRatio || MemoryTrimType.OnSystemLowMemoryWhileAppInForeground.getSuggestedTrimRatio() == suggestedTrimRatio ) { ImagePipelineFactory.getInstance().getImagePipeline().clearMemoryCaches(); } } }); return configBuilder.build(); }
@Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceManager().setSharedPreferencesName(SharedPreferencesUtil.FILE_NAME); addPreferencesFromResource(R.xml.preferences); String downloadPath = DownloadManager.getDownloadPath(); if (downloadPath != null) { String displayPath = Uri.decode(downloadPath); getPreferenceManager().findPreference(KEY_PREF_DOWNLOAD_PATH).setSummary(displayPath); } ListPreference listPreference = (ListPreference) getPreferenceManager().findPreference(KEY_PREF_VIEW_DIRECTION); CharSequence[] entries = listPreference.getEntries(); int i = listPreference.findIndexOfValue(listPreference.getValue()); i = (i <= 0) ? 0 : i; listPreference.setSummary(entries[i]); listPreference.setOnPreferenceChangeListener(this); listPreference = (ListPreference) getPreferenceManager().findPreference(KEY_PREF_VIEW_VIDEO_PLAYER); entries = listPreference.getEntries(); i = listPreference.findIndexOfValue(listPreference.getValue()); i = (i <= 0) ? 0 : i; listPreference.setSummary(entries[i]); listPreference.setOnPreferenceChangeListener(this); getPreferenceScreen().setOnPreferenceChangeListener(this); final DirectoryChooserConfig config = DirectoryChooserConfig.builder() .initialDirectory((downloadPath.startsWith("/")) ? downloadPath : DownloadManager.DEFAULT_PATH) .newDirectoryName("download") .allowNewDirectoryNameModification(true) .build(); mDialog = DirectoryChooserFragment.newInstance(config); mDialog.setTargetFragment(this, 0); float size = (float) Fresco.getImagePipelineFactory().getMainFileCache().getSize() / ByteConstants.MB; Preference cacheCleanPreference = getPreferenceManager().findPreference(KEY_PREF_CACHE_CLEAN); cacheCleanPreference.setSummary(String.format("已使用 %.2f MB", size)); LongClickPreference prefDownloadPath = (LongClickPreference) getPreferenceManager().findPreference(KEY_PREF_DOWNLOAD_PATH); prefDownloadPath.setOnLongClickListener(v -> { new AlertDialog.Builder(activity) .setTitle("选择路径方式") .setItems(new String[]{"系统文档(新)", "路径选择框(旧)"}, (dialogInterface, pos) -> { if (pos == 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); try { startActivityForResult(intent, RESULT_CHOOSE_DIRECTORY); } catch (ActivityNotFoundException e) { e.printStackTrace(); mDialog.show(getFragmentManager(), null); } new Handler().postDelayed(() -> { if (!opened) activity.showSnackBar("如无法开启系统文档,长按使用旧工具"); }, 1000); } else if (pos == 1) { mDialog.show(getFragmentManager(), null); } else activity.showSnackBar("当前系统版本不支持"); }) .setNegativeButton(getString(R.string.cancel), null) .show(); return true; }); }