Created
December 25, 2017 18:52
-
-
Save nkuznetsow/05129619f414d053f6f2df31c520ee3e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DirectoryManager { | |
static final ArrayList<File> directories = new ArrayList<>(); | |
static Context context; | |
/** | |
* Инициализирует класс | |
* @param context только Application Context | |
*/ | |
public static void init(Context context) { | |
DirectoryManager.context = context; | |
IntentFilter intentFilter = new IntentFilter(); | |
intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); | |
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); | |
context.registerReceiver(mediaReceiver, intentFilter); | |
updateDirectories(); | |
} | |
static BroadcastReceiver mediaReceiver = new BroadcastReceiver() { | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
updateDirectories(); | |
} | |
}; | |
static void updateDirectories() { | |
synchronized(directories) { | |
directories.clear(); | |
File[] dirs = ContextCompat.getExternalFilesDirs(context, null); | |
if (dirs != null && dirs.length > 0) { | |
for (File dir : dirs) { | |
if (dir.isDirectory() && dir.canWrite()) { | |
directories.add(dir); | |
} | |
} | |
} | |
} | |
} | |
static File findFile(String fileName) { | |
synchronized(directories) { | |
for (File dir : directories) { | |
File file = new File(dir, fileName); | |
if (file.exists() && file.canWrite()) return file; | |
} | |
return null; | |
} | |
} | |
static File createFile(String fileName) { | |
synchronized(directories) { | |
File dir = findWorkingDirectory(); | |
if (dir != null) return new File(dir, fileName); | |
return null; | |
} | |
} | |
static File findWorkingDirectory() { | |
synchronized(directories) { | |
// TODO: механизм выбора нужной папки для хранения (где есть место или из настроек) | |
if (directories.size() > 0) return directories.get(0); | |
return null; | |
} | |
} | |
public static ArrayList<File> getDirectories() { | |
synchronized(directories) { | |
return directories; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
В onCreate у application инициализируем класс
DirectoryManager.init(this);
Когда нужно найти файле вызываем: DirectoryManager.findFile("UUID-файла"); в ответ получаем File из которого можно читать зашифрованные данные или null, если файл не найден (например SD-карта с файлом была извлечена)
Когда нужно найти место, куда будет записан файл, вызываем: DirectoryManager. createFile("UUID-файла"); в ответ получаем File в который можно писать, или null, если нет папок куда можно было бы сохранить этот файл.