1. 程式人生 > >android耳機插拔的監聽

android耳機插拔的監聽

必須動態註冊,否則無效監聽
一、主要監聽事件
1.監聽有線耳機
Intent.ACTION_HEADSET_PLUG
android.intent.action.HEADSET_PLUG
2,監聽藍芽耳機
BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED
二、程式碼實現

/**
註冊receiver
*/
public class HeadSetActivity extends AppCompatActivity {

    private HeadSetReceiver mReceiver;

    @Override
    protected
void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_head_set); mReceiver = new HeadSetReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); registerReceiver(mReceiver, intentFilter); } @Override
protected void onDestroy() { super.onDestroy(); /** 銷燬receiver */ if (mReceiver != null) { unregisterReceiver(mReceiver); } }
/**
receiver監聽
*/
public class HeadSetReceiver extends BroadcastReceiver {
    @Override
    public void onReceive
(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (BluetoothProfile.STATE_DISCONNECTED == adapter.getProfileConnectionState(BluetoothProfile.HEADSET)) { //Bluetooth headset is now disconnected } } else if ("android.intent.action.HEADSET_PLUG".equals(action)) { if (intent.hasExtra("state")){ if (intent.getIntExtra("state", 0) == 0){ Toast.makeText(context, "headset not connected", Toast.LENGTH_LONG).show(); } else if (intent.getIntExtra("state", 0) == 1){ Toast.makeText(context, "headset connected", Toast.LENGTH_LONG).show(); } } } }