標籤:android開發 耳機
在Android下實現檢測耳機插入和拔出,需要建立一個BroadcastReceiver,用來監聽"android.intent.action.HEADSET_PLUG"廣播。
實現步驟:
1.建立一個BroadcastReceiver的子類,並重寫onReceive()方法,在該方法中編寫接收到廣播後的處理邏輯;
2.建立一個Activity類,在onCreate()方法中使用registerReceiver()方法進行註冊監聽廣播;
3.在Activity中重寫onDestory()方法,使用unregisterReceiver()登出監聽廣播。
具體實現代碼如下:
廣播接收器類
package com.leigo.demo.receiver;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;/** * Created by Administrator on 2014/8/27. */public class HeadsetDetectReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_HEADSET_PLUG.equals(action)) { if (intent.hasExtra("state")) { int state = intent.getIntExtra("state", 0); if (state == 1) { Toast.makeText(context, "插入耳機", Toast.LENGTH_SHORT).show(); } else if(state == 0){ Toast.makeText(context, "拔出耳機", Toast.LENGTH_SHORT).show(); } } } }}
package com.leigo.demo;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import com.leigo.demo.receiver.HeadsetDetectReceiver;public class MainActivity extends Activity { private BroadcastReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * Broadcast Action: Wired Headset plugged in or unplugged * The intent will have the following extra values: * state - 0 for unplugged, 1 for plugged. * name - Headset type, human readable string * microphone - 1 if headset has a microphone, 0 otherwise */ receiver = new HeadsetDetectReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); registerReceiver(receiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }}
android實現耳機插入和拔出狀態檢測