Jak sprawdzić, czy karta SD jest zamontowana w systemie Android?

Pracuję nad aplikacją na Androida, która musi sprawdzić, jakie obrazy zapisał użytkownik. Problem polega na tym, że jeśli użytkownik ma sdcard zamontowany za pomocą kabla USB, nie mogę odczytać listy obrazów na dysku.

Czy ktoś zna sposób, aby stwierdzić, czy usb jest zamontowane tak, że mogę po prostu wyskakiwać komunikat informujący użytkownika, że nie będzie działać?

Author: KFB, 2009-05-23

8 answers

Jeśli próbujesz uzyskać dostęp do obrazów na urządzeniu, najlepszą metodą jest użycie dostawcy treści MediaStore . Dostęp do niego jako dostawcy zawartości pozwoli Ci odpytywać obrazy, które są obecne, i mapować adresy URL content:// do ścieżek plików na urządzeniu, gdzie jest to właściwe.

Jeśli nadal potrzebujesz dostępu do karty SD, Aplikacja aparatu zawiera klasę ImageUtils , która sprawdza, czy karta SD jest zamontowana w następujący sposób:

static public boolean hasStorage(boolean requireWriteAccess) {
    //TODO: After fix the bug,  add "if (VERBOSE)" before logging errors.
    String state = Environment.getExternalStorageState();
    Log.v(TAG, "storage state is " + state);

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        if (requireWriteAccess) {
            boolean writable = checkFsWritable();
            Log.v(TAG, "storage writable is " + writable);
            return writable;
        } else {
            return true;
        }
    } else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}
 38
Author: jargonjustin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-23 22:50:47

Oto brakująca funkcja checkFsWritable w jargonjustin post

private static boolean checkFsWritable() {
        // Create a temporary file to see whether a volume is really writeable.
        // It's important not to put it in the root directory which may have a
        // limit on the number of files.
        String directoryName = Environment.getExternalStorageDirectory().toString() + "/DCIM";
        File directory = new File(directoryName);
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                return false;
            }
        }
        return directory.canWrite();
    }
 9
Author: kakopappa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-20 03:33:05

Przepraszam za zamieszczanie Nie Android sposób na to, mam nadzieję, że ktoś może dostarczyć odpowiedź za pomocą Android API.

Możesz wyświetlić listę plików w katalogu głównym karty SD. Jeśli nie ma, sdcard jest albo całkowicie puste (nietypowe, ale możliwe) lub jest odmontowany. Jeśli próbujesz utworzyć pusty plik na sdcard i nie powiedzie się, oznacza to, że próbowałeś utworzyć plik w punkcie montowania sdcard, który zostanie odrzucony z powodu problemu z uprawnieniami, więc wiesz karta SD nie została zamontowana.

Tak, Wiem, że to brzydkie....

 1
Author: Neil Trodden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-23 20:38:43
public static boolean isSdPresent() {

return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

}
 1
Author: Harinder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-23 09:27:06

Używałem kursora do pobierania obrazów z karty sd i gdy żadna karta sd nie została włożona do urządzenia, kursor był zerowy. W rzeczywistości dzieje się tak, gdy wolumin sdcard został odmontowany przez fizyczne usunięcie karty z urządzenia. To jest kod, którego użyłem:

  Cursor mCursor = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
    if (mCursor == null || !mCursor .moveToFirst()) {
                /**
                 *mCursor == null:
                 * - query failed; the app don't have access to sdCard; example: no sdCard 
                 *
                 *!mCursor.moveToFirst():
                 *     - there is no media on the device
                 */
            } else {
                 // process the images...
                 mCursor.close(); 
    }

Więcej informacji: http://developer.android.com/guide/topics/media/mediaplayer.html#viacontentresolver

 0
Author: Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-17 14:40:53

Przed wykonaniem jakiejkolwiek pracy z zewnętrzną pamięcią masową, należy zawsze wywołać getExternalStorageState (), aby sprawdzić, czy nośnik jest dostępny. Nośnik może być zamontowany na komputerze, zaginiony, tylko do odczytu lub w innym stanie. Na przykład, oto kilka metod, których możesz użyć, aby sprawdzić dostępność:

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

Źródło: http://developer.android.com/guide/topics/data/data-storage.html

 0
Author: Mahmoud Shahoud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-04 06:39:18

On jargonjustin ' s post:

Plik ImageManager.java

Metoda hasStorage -->

public static boolean hasStorage(boolean requireWriteAccess) {
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            if (requireWriteAccess) {
                boolean writable = checkFsWritable();
                return writable;
            } else {
                return true;
            }
        } else if (!requireWriteAccess
                && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

Metoda checkFsWritable -->

 private static boolean checkFsWritable() {
        // Create a temporary file to see whether a volume is really writeable.
        // It's important not to put it in the root directory which may have a
        // limit on the number of files.
        String directoryName =
                Environment.getExternalStorageDirectory().toString() + "/DCIM";
        File directory = new File(directoryName);
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                return false;
            }
        }
        File f = new File(directoryName, ".probe");
        try {
            // Remove stale file if any
            if (f.exists()) {
                f.delete();
            }
            if (!f.createNewFile()) {
                return false;
            }
            f.delete();
            return true;
        } catch (IOException ex) {
            return false;
        }
    }
 0
Author: KitKat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-07 11:11:09
Cool....Check it out...
try {
            File mountFile = new File("/proc/mounts");
            usbFoundCount=0;
            sdcardFoundCount=0;
            if(mountFile.exists())
             {
                Scanner usbscanner = new Scanner(mountFile);
                while (usbscanner.hasNext()) {
                    String line = usbscanner.nextLine();
                    if (line.startsWith("/dev/fuse /storage/usbcard1")) {
                        usbFoundCount=1;
                        Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/usbcard1" );
                    }
            }
         }
            if(mountFile.exists()){
                Scanner sdcardscanner = new Scanner(mountFile);
                while (sdcardscanner.hasNext()) {
                    String line = sdcardscanner.nextLine();
                    if (line.startsWith("/dev/fuse /storage/sdcard1")) {
                        sdcardFoundCount=1;
                        Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/sdcard1" );
                    }
            }
         }
            if(usbFoundCount==1)
            {
                Toast.makeText(context,"USB Connected and properly mounted", 7000).show();
                Log.i("-----USB--------","USB Connected and properly mounted" );
            }
            else
            {
                Toast.makeText(context,"USB not found!!!!", 7000).show();
                Log.i("-----USB--------","USB not found!!!!" );

            }
            if(sdcardFoundCount==1)
            {
                Toast.makeText(context,"SDCard Connected and properly mounted", 7000).show();
                Log.i("-----SDCard--------","SDCard Connected and properly mounted" );
            }
            else
            {
                Toast.makeText(context,"SDCard not found!!!!", 7000).show();
                Log.i("-----SDCard--------","SDCard not found!!!!" );

            }
        }catch (Exception e) {
            e.printStackTrace();
        } 
 -1
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-09 07:15:26