Search code examples
androidbroadcastreceiver

How to avoid/cancel application self run due to BroadcastReceiver?


I have application with BroadcastReceiver which listens to SD card mount/unmount, like:

public class ExternalDatabaseRemovingBroadcastReceiver extends BroadcastReceiver
{
    private static final String TAG= ExternalDatabaseRemovingBroadcastReceiver.class.getName();

    public ExternalDatabaseRemovingBroadcastReceiver()
    {
        super();
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        if(Me.DEBUG)
            Log.d(TAG, "SD card mount/unmount broadcast=" + intent.getAction());
        if(intent.getAction()==null)
            return;
        if(Intent.ACTION_MEDIA_UNMOUNTED.equalsIgnoreCase(intent.getAction()) ||
                Intent.ACTION_MEDIA_EJECT.equalsIgnoreCase(intent.getAction()) ||
                Intent.ACTION_MEDIA_SHARED.equalsIgnoreCase(intent.getAction()))
        {
              //blah-blah
        }
    }
}

Broadcast is declared in AndroidManifest as:

<receiver android:enabled="true"
          android:exported="true"
          android:name=".ExternalDatabaseRemovingBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_MOUNTED"/>
        <action android:name="android.intent.action.MEDIA_UNMOUNTED"/>
        <action android:name="android.intent.action.MEDIA_SHARED"/>
        <data android:scheme="file"/>
    </intent-filter>
</receiver>

And now my problem. During device launch (either real or emulator) - my application unintentionally runs. I mean ActivityManager self runs it reporting:

11-22 08:56:52.239: INFO/ActivityManager(61): Start proc ru.ivanovpv.cellbox.android for broadcast ru.ivanovpv.cellbox.android/.ExternalDatabaseRemovingBroadcastReceiver: pid=288 uid=10034 gids={1015}

Please explain what's goin on? And how to avoid application self running?


Solution

  • It seems to me that upon booting the device, the SD card is mounted as well, which triggers your intent filter. If you don't want this 'initial' mount to be registered by your app, you can perhaps ignore mounts that happen during the first x seconds of uptime. That may not be the most elegant solution, though...


    Edit: Now that I understand barmaley's original intent, the solution is much simpler. Intent-filters in the Android manifest are meant to start your application when something external happens. If you only want to react to (un)mounts while your application is already running, just register your broadcastreceiver programmatically in Application.create and unregister it in Application.destroy using Context.registerReceiver and Context.unregisterReceiver respectively.