2011-06-06 15 views

Respuesta

25

Cuando dices "auricular", ¿te refieres a "auricular con cable"? Si es así, hay una intención de detectar si uno está enchufado o desenchufado: ACTION_HEADSET_PLUG.

Para verificar el estado, puede usar AudioManager.isWiredHeadsetOn(), aunque eso puede devolver falso si también hay un auricular bluetooth, y el audio se enruta a eso en su lugar.

+3

Hola Mike, ¿Qué debo hacer si alguien usa un auricular Blutooth? –

+0

AudioManager.isWiredHeadsetOn() siempre parece devolver falso (probado en varios dispositivos Gingerbread), con o sin un auricular conectado. Si puede proporcionar un ejemplo de código de trabajo, sería genial. –

+4

@ChadSchultz Necesita agregar el permiso MODIFY_AUDIO_SETTINGS en manifiesto ... y solo devolverá el estado correcto. –

41

Puede utilizar el receptor de radiodifusión.

así, es posible escribir este código en "AndroidManifest.xml"

<receiver android:name="com.juno.brheadset.HeadsetStateReceiver"> 
    <intent-filter> 
     <action android:name="android.intent.action.HEADSET_PLUG"/> 
    </intent-filter> 
</receiver>--> 

embargo, esto no funciona. Cuando OS envía este intento de "HEADSET_PLUG", el sistema operativo establece el indicador "Intent.FLAG_RECEIVER_REGISTERED_ONLY". Por lo tanto, debe escribir el siguiente código en la clase Activity o Service en lugar de "AndroidManifest".

public class BRHeadsetActivity extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG); 
    HeadsetStateReceiver receiver = new HeadsetStateReceiver(); 
    registerReceiver(receiver, receiverFilter); 


} 

Espero que este artículo te ayude. ¡Adiós!

Esta es la parte de "HeadsetObserver.java", Android SDK Source.

private final void sendIntent(int headset, int headsetState, int prevHeadsetState, String headsetName) { 
    if ((headsetState & headset) != (prevHeadsetState & headset)) { 
     // Pack up the values and broadcast them to everyone 
     Intent intent = new Intent(Intent.ACTION_HEADSET_PLUG); 

     **intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);** 

     int state = 0; 
     int microphone = 0; 

     if ((headset & HEADSETS_WITH_MIC) != 0) { 
      microphone = 1; 
     } 
     if ((headsetState & headset) != 0) { 
      state = 1; 
     } 
     intent.putExtra("state", state); 
     intent.putExtra("name", headsetName); 
     intent.putExtra("microphone", microphone); 

     if (LOG) Slog.v(TAG, "Intent.ACTION_HEADSET_PLUG: state: "+state+" name: "+headsetName+" mic: "+microphone); 
     // TODO: Should we require a permission? 
     ActivityManagerNative.broadcastStickyIntent(intent, null); 
    } 
} 
+1

-ccromance ¿me puede explicar su código? – Sumit

+0

@Sumit Lo siento. Vi tu repetición ahora. ¿Qué pasa con mi código puedo explicar por ti? :) – cmcromance

+0

@Sumit Ok. Creo que no entiendes esto. Si agrega "FLAG_RECEIVER_REGISTERED_ONLY" al intento de transmisión, puedo recibir su transmisión cuando solo hago "registerReceiver (...)" en el código que no está en 'AndroidManifest.xml'. – cmcromance

14

AudioManager.isWiredHeadsetOn() siempre volver false, ya que requiere el permiso del usuario-MODIFY_AUDIO_SETTINGS.

Pasé varios días mientras encontraba respuesta. No hay información sobre esto en la documentación oficial. Y este bug ya registrado en BugTracker.

Cuestiones relacionadas