原理:
其实android系统在耳机插入和拔出的时候都会发送广播,所以我们要想检测耳机的状态只需要注册响应的BroadCastReceiver,对状态进行响应的判断就ok了。
这个广播的名字叫做:android.intent.action.HEADSET_PLUG
注意,在manifest.xml里面要添加响应的权限:
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
注意,广播要在java文件中动态注册。
package com.example.headphone;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//给广播绑定相应的过滤器
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.intent.action.HEADSET_PLUG");
HeadsetReceiver headsetReceiver = new HeadsetReceiver();
registerReceiver(headsetReceiver, intentFilter); //注册广播接收器
}
//自己定义的广播接收器
public class HeadsetReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.hasExtra("state")) {
if (0 == intent.getIntExtra("state", 0)) {
Toast.makeText(context, "耳机未插入", Toast.LENGTH_SHORT).show();
}else if (1 == intent.getIntExtra("state", 0)) {
Toast.makeText(context, "耳机已插入", Toast.LENGTH_SHORT).show();
}
}
}
}
}