I am writing an application that needs to be detected when the SD card is mounted as a disk to the computer via USB or when it was manually removed. I tried using a broadcast receiver for this purpose, but onReceive was not called. My code is as follows.
IntentFilter filter2 = new IntentFilter(); //filter2.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED); filter2.addAction(Intent.ACTION_MEDIA_UNMOUNTED); filter2.addAction(Intent.ACTION_MEDIA_SHARED); filter2.addAction(Intent.ACTION_MEDIA_REMOVED); filter2.addAction(Intent.ACTION_MEDIA_MOUNTED); registerReceiver(new CustomBroadcastReceiver(), filter2);
My broadcast receiver is as follows:
public class CustomBroadcastReceiver extends BroadcastReceiver{ public CustomBroadcastReceiver(){ } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_SHARED) || action.equals(Intent.ACTION_MEDIA_REMOVED)){ HardwareManager.IS_MEDIA_MOUNTED = false; }else if(action.equals(Intent.ACTION_MEDIA_MOUNTED)){ HardwareManager.IS_MEDIA_MOUNTED = true; }else if(action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)){ HardwareManager.IN_AIRPLANE_MODE = intent.getBooleanExtra("state", false); } } }
The onReceive method does not work when I connect to the drive via USB.
What am I doing wrong?
android broadcastreceiver android-sdcard
Heshan perera
source share