1、在一般的程序中检测手机是否已插入耳机的情况:
<pre name="code" class="java"> AudioManager localAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); boolean hasHeadset = localAudioManager.isWiredHeadsetOn();
<span style="font-size:18px;"><uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /></span>
耳机的插拔事件,android系统都会发出广播告知用户。我们在程序中需要去接收这个广播,在AndroidManifest.xml文件中写死是无效的,具体原因有待研究,网上查了一下说是“sticky” event。
走到这里就只能手动的在代码里面动态注册了啊!创建一个子类,继承自BroadcastReceiver,用于监听耳机的插拔情况。
public class HeadsetReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.hasExtra("state")){ if (intent.getIntExtra("state", 0) == 0){ //耳机插入 Toast.makeText(context, "headset is not plug", Toast.LENGTH_LONG).show(); } else if (intent.getIntExtra("state", 0) == 1){ //耳机拔出 Toast.makeText(context, "headset is plug", Toast.LENGTH_LONG).show(); } } } }<pre name="code" class="java">然后在要监听这个动作的Activity 的onCreate()方法中注册广播。在onDestory()方法中将注册了的广播注销。
public class TestHeadSetPlugActivity extends Activity { private HeadsetReceiver headsetReceiver; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* register receiver */ registerHeadsetPlugReceiver(); } private void registerHeadsetPlugReceiver() { headsetReceiver = new HeadsetReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.intent.action.HEADSET_PLUG"); registerReceiver(HeadsetReceiver, intentFilter); } @Override public void onDestroy() { unregisterReceiver(HeadsetReceiver); super.onDestroy(); } }
原文:http://blog.csdn.net/lisineng/article/details/44654137