700 Software
700 Software

Reputation: 87783

Dynamically created receiver for Media Mounted/Removed events on Android

While the activity is visible, I would like for it to be notified when media is mounted or removed from the device. Unfortunately, I have not been able to get these notifications. The only one I can get is foo! which I created as a simple test.

public class MyActivity extends AppCompatActivity {

  private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(ActivityFamily.class.getName(), intent.getAction());
    }
  };

  @Override
  protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter();
    filter.addAction("foo!");
    filter.addAction(Intent.ACTION_MEDIA_EJECT);
    filter.addAction(Intent.ACTION_MEDIA_REMOVED);
    filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
    registerReceiver(receiver, filter);

    // just added this as a test for "foo!" action
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    manager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, PendingIntent.getBroadcast(this, 0, new Intent().setAction("foo!"), 0));
  }

  @Override
  protected void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
  }
}

Why is onReceive not being called when I remove media from the device?

I even tried creating a brand new MyReceiver.java and defining it in AndroidManifest.xml, but that didn't work either.

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

Upvotes: 1

Views: 1929

Answers (1)

700 Software
700 Software

Reputation: 87783

I found the answer here. I needed to add the file: scheme to the intent filter.

Before using registerReceiver add filter.addDataScheme("file");

For static broadcast receivers registered in the manifest, add <data android:scheme="file" /> within the <intent-filter>.

Upvotes: 4

Related Questions