Search code examples
androidserviceaudio-streamingandroid-pendingintent

How to unregister MediaButtonReceiver onDestroy?


iam using MediaButtonReciever in my Streaming service to listen handle head sets and different devices action i'm declaring it in Manifest like this

   <receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>

The actions works just fine as long as the app in the background once the app is terminated if i clicked on any MediaButton it crashes as the media button with the following crash

Fatal Exception: java.lang.RuntimeException: Unable to start receiver android.support.v4.media.session.MediaButtonReceiver: java.lang.IllegalStateException: Could not find any Service that handles android.intent.action.MEDIA_BUTTON or a media browser service implementation

the problem is the receiver keeps receiving even if the app is destroyed, now how can i unregister the receiver once the app close ? i have tried audioManager.unregister(MediaButtonReciever) but its depreciated


Solution

  • the problem was that i was using the default class in my manifest like this

     <receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>
    

    which was wrong the the receiver automatically unregister after onReceive() is finished

    Once you return from onReceive(), the BroadcastReceiver is no longer active, source

    so all idid was i extened MediaRecieverButton in my custom class MyMediaButtonReceiver and edited my manifest like this

    <receiver android:name=".MyMediaButtonReceiver">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
    

    and it worked just fine