Skip to content Skip to sidebar Skip to footer

App Crash On Headset Button Click

I have build an audioplayer which is deployed in android google playstore. I'm using crashlytics to monitor crashes and ANRs. Recently I have been getting a lot of crashes MediaBut

Solution 1:

You have to create your own media button receiver class, say MyMediaButtonReceiver.java, that extends MediaButtonReceiver, and it will be empty except for the onReceive method that you have to override, calling super.onReceive(...) between a try-catch that captures the IllegalStateException:

publicclassMyMediaButtonReceiverextendsMediaButtonReceiver {

    @OverridepublicvoidonReceive(Context context, Intent intent) {
        try {
            super.onReceive(context, intent);
        } catch (IllegalStateException e) {
            Log.d(this.getClass().getName(), e.getMessage());
        }
    }
}

Then you have to declare that receiver class in your Manifest (or replace your previous MediaButtonReceiver class declaration, if you had one), like:

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

Solution 2:

classMyMediaButtonReceiver : MediaButtonReceiver() {

    overridefunonReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_MEDIA_BUTTON) {
            val event = intent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)
            if (event.action == KeyEvent.ACTION_UP || event.action == 
KeyEvent.ACTION_DOWN) {
            when (event.keyCode) {
                // handle cancel button
                KeyEvent.KEYCODE_MEDIA_STOP -> context.sendIntent(ACTION_FINISH)
               // handle play button
                KeyEvent.KEYCODE_MEDIA_PLAY, KeyEvent.KEYCODE_MEDIA_PAUSE -> context.sendIntent(ACTION_PLAY_PAUSE)
                }
            }
        }
    }
}

kotlin extension for send event to media service

fun Context.sendIntent(action: String) {
    Intent(this, MediaPlayerService::class.java).apply {
        this.action = action
        try {
            if (isOreoPlus()) {
                startForegroundService(this)
            } else {
                startService(this)
            }
        } catch (ignored: Exception) {
        }
    }
}

add Receiver in manifest

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

Post a Comment for "App Crash On Headset Button Click"