Глаз вверх. Я построил простое музыкальное приложение, которое читает файлы WAV с SDCard и воспроизводит их.
Как я могу получить доступ к каталогу мультимедиа по умолчанию?
вот как я получаю SDCard
public void LoadSounds() throws IOException
{
String extState = Environment.getExternalStorageState();
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
File sd = new File(Environment.getExternalStorageDirectory ()); //this needs to be a folder the user can access, like media
как обычно, документы не дают фактического примера использования, но говорят это: если вы используете API уровня 8 или выше, используйте getExternalFilesDir (), чтобы открыть файл, представляющий каталог внешнего хранилища, где вы должны сохранить свои файлы , Этот метод принимает параметр типа, который указывает требуемый тип подкаталога, например DIRECTORY_MUSIC ...
как мне это использовать?
спасибо
редактирование:
это приводит к сбою, если я пытаюсь заполнить массив счетчика строками пути к файлу.
File path = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
File sd = new File(path, "/myFolder");
File[] sdDirList = sd.listFiles(new WavFilter());
if (sdDirList != null)
{
//sort the spinner
amountofiles = sdDirList.length;
array_spinner=new String[amountofiles];
......
final Spinner s = (Spinner) findViewById(R.id.spinner1); //crashes here
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(this,
android.R.layout.select_dialog_item, array_spinner);
EDIT2:
Итак, я сделал этот тест, который должен записать текстовый файл в каталог музыки.
я запускаю приложение, нигде на устройстве я не могу найти текстовый файл.
// Path to write files to
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
String fname = "mytest.txt";
// Current state of the external media
String extState = Environment.getExternalStorageState();
// External media can be written onto
if (extState.equals(Environment.MEDIA_MOUNTED))
{
try {
// Make sure the path exists
boolean exists = (new File(path)).exists();
if (!exists){ new File(path).mkdirs(); }
// Open output stream
FileOutputStream fOut = new FileOutputStream(path + fname);
fOut.write("Test".getBytes());
// Close output stream
fOut.flush();
fOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
еще одно редактирование: я получу это работает !!
поэтому, если я использую эту строку, она создает папку на SD-карте под названием «Musictest». не понимаю ??
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "test").getAbsolutePath();
/////////////////////////////////////////////// /////////////////////
Окончательное редактирование:
прямо так, это будет искать папку с именем test в каталоге музыкальных устройств.
если он не существует, он будет создан.
(некоторые исправления должны быть сделаны здесь, ошибка, если пустая), затем перечисляет файлы в каталоге и добавляет их в массив.
public void LoadSounds() throws IOException
{
String extState = Environment.getExternalStorageState();
// Path to write files to
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/test").getAbsolutePath();
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
//do your file work here
// Make sure the path exists
boolean exists = (new File(path)).exists();
//if not create it
if (!exists){ new File(path).mkdirs(); }
File sd = new File(path);
//This will return an array with all the Files (directories and files)
//in the external storage folder
File[] sdDirList = sd.listFiles();
if (sdDirList != null)
{
//add the files to the spinner array
array_spinnerLoad=new String[sdDirList.length];
files = new String[sdDirList.length];
for(int i=0;i<sdDirList.length;i++){
array_spinnerLoad[i] = sdDirList[i].getName();
files[i] = sdDirList[i].getAbsolutePath();
}
}
}
}