Android: как слушать "SD-карта неожиданно удалена" - PullRequest
6 голосов
/ 07 августа 2011

У меня есть программа, которая использует контент с SD-карты. Я хочу слушать различные состояния, такие как sd-карта установлена ​​или sd-карта неожиданно удалена. Как я могу это сделать. Пример был бы очень полезен.

Спасибо всем

Ответы [ 4 ]

12 голосов
/ 07 августа 2011

Вам необходимо прослушать ACTION_MEDIA_REMOVED и ACTION_MEDIA_MOUNTED . Создайте получателя и прослушайте это действие.

EDIT:

В вашем файле манифеста добавьте

<receiver android:name=".MyReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_REMOVED" />
        <action android:name="android.intent.action.MEDIA_MOUNTED" />
        <data android:scheme="file" />
    </intent-filter>
</receiver>

затем создайте класс MyReceiver, который будет расширять BroadcastReceiver, а затем перехватывать эти действия и выполнять то, что вы хотите сделать.

2 голосов
/ 09 февраля 2016

Создать получателя в манифесте:

    <receiver android:name=".ExternalSDcardRemoved">
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_EJECT" />
            <data android:scheme="file" />
        </intent-filter>
    </receiver>

и соответствующий файл класса:

public class ExternalSDcardRemoved extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        // SD card removed
    }
}
1 голос
/ 07 августа 2011

Вы можете использовать что-то вроде этого:

    static boolean checkSdCardStatus(final Activity activity) {

    String status = Environment.getExternalStorageState();
    //the SD Card is mounted as read-only, but we require it to be writable.
    if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
        UIMethods.showFinalAlert(activity, R.string.sdcard_readonly);
        return false;
    }
    //your handset is mounted as a USB device
    if (status.equals(Environment.MEDIA_SHARED)) {
        UIMethods.showFinalAlert(activity, R.string.sdcard_shared);
        return false;
    }
    //no SD Card inserted
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        UIMethods.showFinalAlert(activity, R.string.no_sdcard);
        return false;
    }

    return true;
}

И вызовите этот метод в Activity.onStart() или в Activity.onResume().

0 голосов
/ 21 марта 2017

Благодаря @ PravinCG

Вот полный код.

SDCardBroadcastReceiver.java код

public class SDCardBroadcastReceiver extends BroadcastReceiver {


    private static final String ACTION_MEDIA_REMOVED = "android.intent.action.MEDIA_REMOVED";
    private static final String ACTION_MEDIA_MOUNTED = "android.intent.action.MEDIA_MOUNTED";
    private static final String MEDIA_BAD_REMOVAL = "android.intent.action.MEDIA_BAD_REMOVAL";
    private static final String MEDIA_EJECT = "android.intent.action.MEDIA_EJECT";
    private static final String TAG = "SDCardBroadcastReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {



        Log.i(TAG, "Intent recieved: " + intent.getAction());

        if (intent.getAction() == ACTION_MEDIA_REMOVED) {

            Log.e(TAG, "ACTION_MEDIA_REMOVED called");

            // For bundle Extras do like below
//            Bundle bundle = intent.getExtras();
//            if (bundle != null) {
//
//            }
        }else if (intent.getAction() == ACTION_MEDIA_MOUNTED){

            Log.e(TAG, "ACTION_MEDIA_MOUNTED called");

        }else if(intent.getAction() == MEDIA_BAD_REMOVAL){

            Log.e(TAG, "MEDIA_BAD_REMOVAL called");

        }else if (intent.getAction() == MEDIA_EJECT){

            Log.e(TAG, "MEDIA_EJECT called");

        }
    }
}

и вот мой manifest.xml файл

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="genetechsolutions.sdcardmountlistner">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <receiver android:name=".SDCardBroadcastReceiver" >
            <intent-filter>
                <data android:scheme="file" />
                <action android:name="android.intent.action.MEDIA_REMOVED" />
                <action android:name="android.intent.action.MEDIA_MOUNTED" />
                <action android:name="android.intent.action.MEDIA_EJECT" />
                <action android:name="android.intent.action.MEDIA_BAD_REMOVAL" />
            </intent-filter>
        </receiver>

    </application>

</manifest>
...