Created
May 7, 2018 08:36
-
-
Save masaibar/44ad68d4f7360df48f9e1c4a4c4a1072 to your computer and use it in GitHub Desktop.
Androidのイヤホンの抜き差しを検知する ref: https://qiita.com/masaibar/items/649c85a86e3ad4ef7c97
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 -> { | |
// その他の場合の処理 | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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