text: /*
   * Copyright (c) 2019 Naman Dwivedi.
   *
   * Licensed under the GNU General Public License v3
   *
   * This is free software: you can redistribute it and/or modify it
   * under the terms of the GNU General Public License as published by
   * the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
   *
   * This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
   * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
   * See the GNU General Public License for more details.
   *
   */
  package com.naman14.timberx.playback
  
  import android.content.BroadcastReceiver
  import android.content.Context
  import android.content.Intent
  import android.content.IntentFilter
  import android.media.AudioManager
  import android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY
  import android.support.v4.media.session.MediaControllerCompat
  import android.support.v4.media.session.MediaSessionCompat
  
  /**
   * Helper class for listening for when headphones are unplugged (or the audio
   * will otherwise cause playback to become "noisy").
   */
  class BecomingNoisyReceiver(
      private val context: Context,
      sessionToken: MediaSessionCompat.Token
  ) : BroadcastReceiver() {
  
      private val noisyIntentFilter = IntentFilter(ACTION_AUDIO_BECOMING_NOISY)
      private val controller = MediaControllerCompat(context, sessionToken)
  
      private var registered = false
  
      fun register() {
          if (!registered) {
              context.registerReceiver(this, noisyIntentFilter)
              registered = true
          }
      }
  
      fun unregister() {
          if (registered) {
              context.unregisterReceiver(this)
              registered = false
          }
      }
  
      override fun onReceive(context: Context, intent: Intent) {
          if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) {
              controller.transportControls.pause()
          }
      }
  }
  