Skip to content

Instantly share code, notes, and snippets.

@masaibar
Created May 7, 2018 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masaibar/44ad68d4f7360df48f9e1c4a4c4a1072 to your computer and use it in GitHub Desktop.
Save masaibar/44ad68d4f7360df48f9e1c4a4c4a1072 to your computer and use it in GitHub Desktop.
Androidのイヤホンの抜き差しを検知する ref: https://qiita.com/masaibar/items/649c85a86e3ad4ef7c97
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.media.AudioManager
class HeadsetEventReceiver :BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent == null || intent.action != Intent.ACTION_HEADSET_PLUG) {
return
}
val state = intent.getIntExtra("state", AudioManager.SCO_AUDIO_STATE_ERROR)
when(state) {
AudioManager.SCO_AUDIO_STATE_DISCONNECTED -> {
// 切断された時の処理
}
AudioManager.SCO_AUDIO_STATE_CONNECTED -> {
// 接続された時の処理
}
else -> {
// その他の場合の処理
}
}
}
}
import android.content.Intent
import android.content.IntentFilter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
private lateinit var receiver: HeadsetEventReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
receiver = HeadsetEventReceiver()
registerReceiver(receiver, IntentFilter(Intent.ACTION_HEADSET_PLUG))
}
override fun onDestroy() {
unregisterReceiver(receiver)
super.onDestroy()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment