Android 监听耳机的插拔事件
一般采用的是动态监听的方式来实现的:
package com.renhui.ej; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; public class MainActivity extends AppCompatActivity { HeadsetPlugReceiver headsetPlugReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); registerHeadsetPlugReceiver(); // 注册监听 } private void registerHeadsetPlugReceiver() { headsetPlugReceiver = new HeadsetPlugReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("android.intent.action.HEADSET_PLUG"); registerReceiver(headsetPlugReceiver, filter); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); unregisterReceiver(headsetPlugReceiver); //注销监听 } class HeadsetPlugReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub 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(); } } } } }