- Android how to browse files
- About
- Saving Files
- This lesson teaches you to
- You should also read
- Choose Internal or External Storage
- Obtain Permissions for External Storage
- Save a File on Internal Storage
- Save a File on External Storage
- Query Free Space
- Delete a File
- AndroidDev #1. Создаем файловый менеджер
- Готовимся
- Создаем проект
- О нашем проекте
- Начинаем писать код
Android how to browse files
A FileBrowser / FileChooser for Android that you can integrate to your app to browse/select files from internal/external storage.
Or Using Gradle
It easily integrates with your app’s color scheme. You can change the color scheme using the following in your styles.xml
There are 3 main classes to use the library.
- FileBrowser — Used to just Browse files in storage (has all file IO features)
- FileChooser — Used to select single/multiple files in storage (has some IO features)
- FolderChooser — Used to select single/multiple folders in storage (has some IO features)
- FileBrowserWithCustomHandler — Used to run custom code when files are selected (has all IO features)
Use following Intent to start the FileBrowser
Use following Intent to start the FileChooser
To get the selected file, In your calling activity’s onActivityResult method, use the following
To get the selected file, In your calling activity’s onActivityResult method, use the following
Use following Intent to start the FolderChooser
To get the selected folder, In your calling activity’s onActivityResult method, use the following
To get the selected file, In your calling activity’s onActivityResult method, use the following
Register a Broadcast receiver and handle the onReceive method like below
Register the receiver like the following snippet
If you also need some other parameters to be sent with the broadcast use the following when creating the activity
and in the broadcast receiver use the following to get the extras
To load a particular directory instead of the normal root directory
Add the following in the intent
To list only the files with a particular extension
Add the following in the intent
Use file extensions delimited by semicolon
Currently folder size is calculated using Java’s Api getTotalSpace() which gives the size of the partition of the path which may not always give the desired result. To get the exact size, properties can be used which gives the exact result. If Exact size is to be known, then UI would lag as it would take some time to calculate size — Fix for this is postponed
If you have any questions/queries/Bugs/Hugs please mail @ adityak368@gmail.com
About
A FileBrowser / FileChooser / FolderChooser for Android that you can integrate to your app to browse/select files from internal/external storage
Источник
Saving Files
This lesson teaches you to
You should also read
Android uses a file system that’s similar to disk-based file systems on other platforms. This lesson describes how to work with the Android file system to read and write files with the File APIs.
A File object is suited to reading or writing large amounts of data in start-to-finish order without skipping around. For example, it’s good for image files or anything exchanged over a network.
This lesson shows how to perform basic file-related tasks in your app. The lesson assumes that you are familiar with the basics of the Linux file system and the standard file input/output APIs in java.io .
Choose Internal or External Storage
All Android devices have two file storage areas: «internal» and «external» storage. These names come from the early days of Android, when most devices offered built-in non-volatile memory (internal storage), plus a removable storage medium such as a micro SD card (external storage). Some devices divide the permanent storage space into «internal» and «external» partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not. The following lists summarize the facts about each storage space.
- It’s always available.
- Files saved here are accessible by only your app by default.
- When the user uninstalls your app, the system removes all your app’s files from internal storage.
Internal storage is best when you want to be sure that neither the user nor other apps can access your files.
- It’s not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device.
- It’s world-readable, so files saved here may be read outside of your control.
- When the user uninstalls your app, the system removes your app’s files from here only if you save them in the directory from getExternalFilesDir() .
External storage is the best place for files that don’t require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.
Tip: Although apps are installed onto the internal storage by default, you can specify the android:installLocation attribute in your manifest so your app may be installed on external storage. Users appreciate this option when the APK size is very large and they have an external storage space that’s larger than the internal storage. For more information, see App Install Location.
Obtain Permissions for External Storage
To write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:
Caution: Currently, all apps have the ability to read the external storage without a special permission. However, this will change in a future release. If your app needs to read the external storage (but not write to it), then you will need to declare the READ_EXTERNAL_STORAGE permission. To ensure that your app continues to work as expected, you should declare this permission now, before the change takes effect.
However, if your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.
You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory.
Save a File on Internal Storage
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:
getFilesDir() Returns a File representing an internal directory for your app. getCacheDir() Returns a File representing an internal directory for your app’s temporary cache files. Be sure to delete each file once it is no longer needed and implement a reasonable size limit for the amount of memory you use at any given time, such as 1MB. If the system begins running low on storage, it may delete your cache files without warning.
To create a new file in one of these directories, you can use the File() constructor, passing the File provided by one of the above methods that specifies your internal storage directory. For example:
Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here’s how to write some text to a file:
Or, if you need to cache some files, you should instead use createTempFile() . For example, the following method extracts the file name from a URL and creates a file with that name in your app’s internal cache directory:
Note: Your app’s internal storage directory is specified by your app’s package name in a special location of the Android file system. Technically, another app can read your internal files if you set the file mode to be readable. However, the other app would also need to know your app package name and file names. Other apps cannot browse your internal directories and do not have read or write access unless you explicitly set the files to be readable or writable. So as long as you use MODE_PRIVATE for your files on the internal storage, they are never accessible to other apps.
Save a File on External Storage
Because the external storage may be unavailable—such as when the user has mounted the storage to a PC or has removed the SD card that provides the external storage—you should always verify that the volume is available before accessing it. You can query the external storage state by calling getExternalStorageState() . If the returned state is equal to MEDIA_MOUNTED , then you can read and write your files. For example, the following methods are useful to determine the storage availability:
Although the external storage is modifiable by the user and other apps, there are two categories of files you might save here:
Public files Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user.
For example, photos captured by your app or other downloaded files.
Private files Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they are files that realistically don’t provide value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app’s external private directory.
For example, additional resources downloaded by your app or temporary media files.
If you want to save public files on the external storage, use the getExternalStoragePublicDirectory() method to get a File representing the appropriate directory on the external storage. The method takes an argument specifying the type of file you want to save so that they can be logically organized with other public files, such as DIRECTORY_MUSIC or DIRECTORY_PICTURES . For example:
If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() and passing it a name indicating the type of directory you’d like. Each directory created this way is added to a parent directory that encapsulates all your app’s external storage files, which the system deletes when the user uninstalls your app.
For example, here’s a method you can use to create a directory for an individual photo album:
If none of the pre-defined sub-directory names suit your files, you can instead call getExternalFilesDir() and pass null . This returns the root directory for your app’s private directory on the external storage.
Remember that getExternalFilesDir() creates a directory inside a directory that is deleted when the user uninstalls your app. If the files you’re saving should remain available after the user uninstalls your app—such as when your app is a camera and the user will want to keep the photos—you should instead use getExternalStoragePublicDirectory() .
Regardless of whether you use getExternalStoragePublicDirectory() for files that are shared or getExternalFilesDir() for files that are private to your app, it’s important that you use directory names provided by API constants like DIRECTORY_PICTURES . These directory names ensure that the files are treated properly by the system. For instance, files saved in DIRECTORY_RINGTONES are categorized by the system media scanner as ringtones instead of music.
Query Free Space
If you know ahead of time how much data you’re saving, you can find out whether sufficient space is available without causing an IOException by calling getFreeSpace() or getTotalSpace() . These methods provide the current available space and the total space in the storage volume, respectively. This information is also useful to avoid filling the storage volume above a certain threshold.
However, the system does not guarantee that you can write as many bytes as are indicated by getFreeSpace() . If the number returned is a few MB more than the size of the data you want to save, or if the file system is less than 90% full, then it’s probably safe to proceed. Otherwise, you probably shouldn’t write to storage.
Note: You aren’t required to check the amount of available space before you save your file. You can instead try writing the file right away, then catch an IOException if one occurs. You may need to do this if you don’t know exactly how much space you need. For example, if you change the file’s encoding before you save it by converting a PNG image to JPEG, you won’t know the file’s size beforehand.
Delete a File
You should always delete files that you no longer need. The most straightforward way to delete a file is to have the opened file reference call delete() on itself.
If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile() :
Note: When the user uninstalls your app, the Android system deletes the following:
- All files you saved on internal storage
- All files you saved on external storage using getExternalFilesDir() .
However, you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.
Источник
AndroidDev #1. Создаем файловый менеджер
Android — перспективная и динамично развивающаяся операционная система. И многие программисты хотят научиться программировать приложения для OS Android, но беглый поиск структурированных материалов в сети Интернет и, в частности, Рунете, приводит их в ступор. Действительно, до сих пор существует проблема поиска обучающих статей (особенно на русском языке) по разработке приложений для этой весьма популярной операционной системы.
Ну, что ж, будем потихоньку улучшать данную ситуацию при помощи Хабра.
Сразу предупрежу, что материалы предназначены для тех, кто не имеет опыта разработки приложений для Android, но очень-очень хочет этот опыт приобрести.
Готовимся
Первое, что нам потребуется — установить и настроить IDE. Мы будем использовать Eclipse, однако важно отметить, что существует возможность использовать любую среду разработки.
Подробная инструкция по установке и настройке IDE Eclipse содержится в документации на сайте Android. Если вкратце:
- Устанавливаем Eclipse Classic отсюда
- Устанавливаем SDK Starter Package отсюда
- Устанавливаем ADT Plugin при помощи данной инструкции, по той же инструкции выполняем действия, описанные в разделе Configuring the ADT Plugin
- Запускаем Eclipse, нажимаем Window > Android SDK and AVD Manager и выбираем необходимые компоненты для установки. Самый простой вариант — выбрать всё, но необходимый минимум — SDK Platform Android 2.1 (или 2.2), Android SDK Tools, Android SDK Platform-tools
После всего этого мы имеем рабочую среду для разработки приложений для ОС Android. Но нам нужно где-то проверять наши приложения, верно? И тут мы стоим перед выбором — либо осуществлять эти действия в эмуляторе, либо на реальном устройстве.
Эмулятор можно добавить в уже знакомом нам окне Android SDK and AVD Manager, нажав кнопку New. во вкладке Virtual Devices. Заполняем поле Name, указываем версию API и добавляем наше виртуальное устройство.
Если же вы хотите тестировать свои приложения на реальном устройстве, смотрите сюда. Важно отметить, что в конечном счёте вам всё равно придётся проверять своё приложение на реальном устройстве, ведь немного странно выпускать приложение, допустим, в Android Market, как следует его не протестировав на действующих образцах телефонов/планшетов.
Создаем проект
Пришло время создать новый проект. Для этого жмём File > New > Project, выбираем в появившемся окне Android > Android Project и жмем Next. Появляется следующее окно, которое мы заполняем примерно так:
Теперь немного объяснений.
Project Name — имя проекта в среде Eclipse.
Application Name — название приложение, то самое, которое будут видеть пользователи на конечном Android-устройстве.
Package Name — название пакета. Тут всё аналогично любому Java-проекту. Важно знать, что данное имя должно быть уникальным среди всех пакетов, имеющихся на конечном устройстве. Посему достаточно эффективна классическая логика давать название, соответствующего веб-домену, записанному наоборот (как тут — ru.alwake), а далее — название самого проекта. Данный шаг в какой-то мере обеспечит уникальность названия.
Create Activity — имя класса, который в будущем будет являться подклассом класса Activity.
Min SDK Version — минимальная версия SDK. Если посмотреть выше на список Build Target в данном окне, то можно прийти к выводу, что наше приложение запускается только для устройств с Android >= 2.1 (Android 2.1 соответствует версия SDK 7). В данном случае это не очень принципиально, но пусть будет так.
Теперь можно смело нажать Finish и лицезреть свой проект в панели Package Exploper. Проект создан и неплохо бы ознакомиться с некоторой теоретической основой по устройству Android-приложений, которая неплохо изложена тут.
О нашем проекте
Для начала определимся, что мы хотим от нашего файлового менеджера. В идеале — полную замену ASTRO и eStrongs. Ну, а пока нам требуется обеспечить базовую навигацию по каталогам, причем под «базовой» мы понимаем, что нам не нужно заходить в те папки, в которые имеет доступ только root. Помимо этого, в поле сверху у нас будет отображаться наше текущее расположение в структуре каталогов.
Ну, а сначала поговорим о структуре проекта:
/res/drawable-*dpi — в этих трёх папках у нас содержатся ресурсы, предназначенные для разных расширений экрана. На данный момент там имеется всего-навсего файл icon.png, то есть иконка нашего приложения.
/res/layout — в данной папке содержатся xml-файлы, описывающие внешний вид форм и различных элементов форм. После создания проекта там уже имеется файл main.xml, также там нужно создать файл row.xml, который будет описывать внешний вид каждого отдельно взятого ряда (то есть элемента списка нашего файлового древа).
/res/values — тут у нас располагаются какие-либо константы, которые мы можем использовать в нашем проекте.
Стоит отметить, что данные XML-файлы можно редактировать как в визуальном режиме, так и в текстовом (меняя непосредственно xml-код). Мы будем действовать по второму способу. Для редактирования кода необходимо нажать правой кнопкой по xml-файлу в панели Package Explorer и выбрать Open with > Text Editor. Это так, на будущее 😉
Файл FileManager.java — в данном файле, собственно, содержится наш основной класс для главной и единственной формы приложения. Весь наш код в данном проекте будет размещаться тут.
Файл AndroidManifest.xml — файл с основными свойствами нашего проекта, в частности, заданными при создании проекта (такими как, например, название). Соответственно, чтобы поменять, предположим, название, нам нужно ковырять данный файл.
Остальные файлы нас пока мало интересуют.
Начинаем писать код
В общем-то, всё что было выше — базовые сведения, которые каждый Android-программист обязан знать. А теперь пришла пора разбираться непосредственно с нашим кодом.
xml version =»1.0″ encoding =»utf-8″ ? >
TableLayout xmlns:android =»http://schemas.android.com/apk/res/android»
android:orientation =»vertical»
android:layout_width =»fill_parent»
android:layout_height =»fill_parent» >
TableRow >
TextView android:id =»@+id/titleManager»
android:layout_width =»fill_parent»
android:layout_height =»fill_parent»
android:padding =»5dip»
/>
TableRow >
TableRow >
ListView android:id =»@id/android:list»
android:layout_width =»fill_parent»
android:layout_height =»fill_parent»
android:layout_weight =»2″
android:drawSelectorOnTop =»false»/>
TableRow >
TableLayout >
* This source code was highlighted with Source Code Highlighter .
Здесь у нас задается разметка для нашего основного Layout’а формы. TableLayout здесь значит, что элементы у нас выстроены в виде таблицы. Далее в верхней ячейке таблицы размещается элемент TextView (текстовое поле), а в нижней ячейке — ListView (список). Оба элемента имеют id, используя который, мы можем изменять содержимое элементов. Например, используя R.id.titleManager для нашего текстового поля TextView.
xml version =»1.0″ encoding =»utf-8″ ? >
TextView
xmlns:android =»http://schemas.android.com/apk/res/android»
android:layout_width =»fill_parent»
android:layout_height =»40sp»
android:padding =»5dip»
android:gravity =»center_vertical»
/>
* This source code was highlighted with Source Code Highlighter .
Здесь мы задаем разметку для каждого элемента нашего ListView, то есть непосредственно для каждой отдельно взятой папки или каждого файла. В данном коде у нас задается ширина каждого элемента, высота, отступ (padding) и выравнивание center_vertical — то есть центрование по вертикали.
- package ru.alwake.filemanager;
- import java.io. File ;
- import java.util. ArrayList ;
- import java.util. List ;
- import android.app.AlertDialog;
- import android.app.ListActivity;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.DialogInterface.OnClickListener;
- import android.net. Uri ;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
- import android.widget.TextView;
- public class FileManager extends ListActivity <
- private List String > directoryEntries = new ArrayList String >();
- private File currentDirectory = new File ( «/» );
- //when application started
- @Override
- public void onCreate(Bundle icicle) <
- super.onCreate(icicle);
- //set main layout
- setContentView(R.layout.main);
- //browse to root directory
- browseTo( new File ( «/» ));
- >
- //browse to parent directory
- private void upOneLevel() <
- if ( this .currentDirectory.getParent() != null ) <
- this .browseTo( this .currentDirectory.getParentFile());
- >
- >
- //browse to file or directory
- private void browseTo(final File aDirectory) <
- //if we want to browse directory
- if (aDirectory.isDirectory()) <
- //fill list with files from this directory
- this .currentDirectory = aDirectory;
- fill(aDirectory.listFiles());
- //set titleManager text
- TextView titleManager = (TextView) findViewById(R.id.titleManager);
- titleManager.setText(aDirectory.getAbsolutePath());
- > else <
- //if we want to open file, show this dialog:
- //listener when YES button clicked
- OnClickListener okButtonListener = new OnClickListener() <
- public void onClick(DialogInterface arg0, int arg1) <
- //intent to navigate file
- Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri .parse( «file://» + aDirectory.getAbsolutePath()));
- //start this activity
- startActivity(i);
- >
- >;
- //listener when NO button clicked
- OnClickListener cancelButtonListener = new OnClickListener() <
- public void onClick(DialogInterface arg0, int arg1) <
- //do nothing
- //or add something you want
- >
- >;
- //create dialog
- new AlertDialog.Builder( this )
- .setTitle( «Подтверждение» ) //title
- .setMessage( «Хотите открыть файл » + aDirectory.getName() + «?» ) //message
- .setPositiveButton( «Да» , okButtonListener) //positive button
- .setNegativeButton( «Нет» , cancelButtonListener) //negative button
- .show(); //show dialog
- >
- >
- //fill list
- private void fill( File [] files) <
- //clear list
- this .directoryEntries.clear();
- if ( this .currentDirectory.getParent() != null )
- this .directoryEntries.add( «..» );
- //add every file into list
- for ( File file : files) <
- this .directoryEntries.add(file.getAbsolutePath());
- >
- //create array adapter to show everything
- ArrayAdapter String > directoryList = new ArrayAdapter String >( this , R.layout.row, this .directoryEntries);
- this .setListAdapter(directoryList);
- >
- //when you clicked onto item
- @Override
- protected void onListItemClick(ListView l, View v, int position, long id) <
- //get selected file name
- int selectionRowID = position;
- String selectedFileString = this .directoryEntries. get (selectionRowID);
- //if we select «..» then go upper
- if (selectedFileString.equals( «..» )) <
- this .upOneLevel();
- > else <
- //browse to clicked file or directory using browseTo()
- File clickedFile = null ;
- clickedFile = new File (selectedFileString);
- if (clickedFile != null )
- this .browseTo(clickedFile);
- >
- >
- >
* This source code was highlighted with Source Code Highlighter .
В начале указывается название пакета (package name).
Строки 2-18 отвечают за импорт нужных нам библиотек. Важно отметить, что импорт библиотек Eclipse может производить автоматически, как только встретит что-нибудь неизвестное.
В данном коде у нас всего 5 достаточно очевидных функций, в которых несложно разобраться. И это — скелет приложения, обеспечивающий основную навигацию по файловой структуре. Однако у данного приложения существует одна проблема — при попытке зайти в директорию, доступ к которой разрешен только суперпользователю, мы получаем ошибку и приложение завершает работу.
Соответственно, в следующий раз мы подумаем как избавиться от этой ошибки, а также о том, как сделать отображение иконок, соответствующих типу файла. Кроме того, мы подумаем о реализации функции Copy-Paste в нашем файловом менеджере.
В конечном счёте предполагается получить большое и грамотное приложение, которое должно дать основную информацию об аспектах программирования под Android.
Источник