четверг, 12 июля 2012 г.

BroadcastReceiver событие при монтирование USB флешки в Android


Как узнать что USB флешка подключена?



Можно подписаться на события.

Способ 1. Ручками.


В activity в методе onCreate() например.

IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);

//filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);

//filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);

filter.addDataScheme("file"); //В документации не написано, но без нее не работает

registerReceiver(myMountReceiver, filter);


В onDestroy()
unregisterReceiver(myMountReceiver);

ну и 

private MountBroadcastReceiver myMountReceiver;

Способ 2. В манифесте


В файл AndroidManifest.xml необходимо добавить

        <receiver
            android:name=".MountBroadcastReceiver"
            android:enabled="true"
            android:label="MountBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.content.Intent.MEDIA_MOUNTED" />
                <data android:scheme="file" />
            </intent-filter>
        </receiver>

Класс MountBroadcastReceiver

public class MountBroadcastReceiver extends BroadcastReceiver { public MountBroadcastReceiver(){ super(); }
@Override public void onReceive(Context context, Intent intent) { String mountDir = intent.getDataString(); if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) { Toast.makeText(context,"Media mounted to"+mountDir, Toast.LENGTH_LONG).show(); }}

Права доступа

 <uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Ссылки


http://developer.android.com/reference/android/content/Intent.html#ACTION_MEDIA_MOUNTED
http://developer.android.com/reference/android/content/Intent.html#ACTION_UMS_CONNECTED


http://stackoverflow.com/questions/994746/android-broadcastreceiver-cant-receive-any-broadcast-events

http://stackoverflow.com/questions/8791282/android-how-to-detect-turn-on-usb-storage-broadcast
http://stackoverflow.com/questions/9340332/how-can-i-get-the-list-of-mounted-external-storage-of-android-device

http://stackoverflow.com/questions/5522963/usb-connection-notification

http://stackoverflow.com/questions/11281010/how-can-i-get-external-sd-card-path-for-android-4-0
http://stackoverflow.com/questions/7142987/media-mounted-broadcast-not-being-recieved
http://stackoverflow.com/questions/994746/android-broadcastreceiver-cant-receive-any-broadcast-events

Комментариев нет:

Отправить комментарий