android 이어폰(헤드셋) 끼었을때 이벤트 받기


You can see if AudioManager gives you the status information you're looking for:

http://developer.android.com/reference/android/media/AudioManager.html

Also look here:

http://developer.android.com/reference/android/content/Intent.html#ACTION_HEADSET_PLUG


// Register receiver
   
this.registerReceiver(new BroadcastsHandler(), new IntentFilter(Intent.ACTION_HEADSET_PLUG));


Now the code of BroadcastReceiver:

public class BroadcastsHandler extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
   
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_HEADSET_PLUG)) {
       
String data = intent.getDataString();
       
Bundle extraData = intent.getExtras();

       
String st = intent.getStringExtra("state");
       
String nm = intent.getStringExtra("name");
       
String mic = intent.getStringExtra("microphone");
       
String all = String.format("st=%s, nm=%s, mic=%s", st, nm, mic);


       
AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder
.setTitle("Headset broadcast");
        builder
.setMessage(all);
        builder
.setPositiveButton("Okey-dokey", new DialogInterface.OnClickListener() {

           
public void onClick(DialogInterface dialog, int which) {
                dialog
.dismiss();
           
}
       
});
        builder
.create().show();
   
}
}


The code is wrong!

"state" and "microphone" is integer, not string. So the code should be modified as following:

    int st = intent.getIntExtra("state" , -1);
   
String nm = intent.getStringExtra("name");
   
int mic = intent.getIntExtra("microphone", -1);
   
String all = "st="+Integer.toString(st)+" nm="+nm+" mic="+Integer.toString(mic);

매니페스트 추가

<receiver

android:name="dingdong.util.vc.BroadcastsHandler"

android:enabled="true"

android:exported="false"

android:label="EarphonesEvent"

>

<intent-filter>

<action android:name="android.intent.action.HEADSET_PLUG"/>

</intent-filter>

</receiver>    


android manifest에 사용되는 receiver, intent-filter

http://mrsohn.tistory.com/archive/20110519



출처 : 

http://android.bigresource.com/Android-ACTION_HEADSET_PLUG-broadcast--hyL9eZIvE.html

http://stackoverflow.com/questions/2524923/issues-with-action-headset-plug-broadcast-in-android

https://groups.google.com/forum/?fromgroups#!topic/android-developers/bQ3ambT0LI8

http://code.google.com/p/android/issues/detail?id=4963#c3

https://github.com/jakebasile/hearing-saver  (소스)


+ Recent posts