如何跟踪从耳机到扬声器的切换

时间:2014-05-28 08:24:14

标签: android media-player

播放音乐的时候有一个媒体播放器,如果音乐开始拉动播放的耳机,那么当移除耳机媒体播放器停止播放时,该动态是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用AudioManager来检测是否连接了耳机:

AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
Log.i("HEADPHONE", "Headphone is plugged in: " + am.isWiredHeadsetOn());

要使用它,您必须向AndroidManifest.xml添加以下权限:

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

观察耳机的状态已经描述为here或类似于here

public class MyActivity extends Activity {

   // ...

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
       HeadsetStateReceiver receiver = new HeadsetStateReceiver();
       registerReceiver( receiver, receiverFilter );
   }

   // ...

}