Определение того, подключена ли гарнитура к устройству Android или нет.

Как я могу определить, подключена ли гарнитура к устройству Android?

28
задан gonzobrains 23 May 2013 в 01:57
поделиться

1 ответ

Во-первых, создайте получатель в своей декларации:

    <receiver android:name="com.yourapplication.BroadcastReceiver">
        <intent-filter>
            <action android:name="android.intent.action.HEADSET_PLUG"/>
        </intent-filter>
    </receiver>

не забывают изменяться, com.yourapplication согласно Вашему названию проекта

Создают две переменные в главе Вашего действия:

private  BroadcastReceiver mReceiver  ;
boolean Microphone_Plugged_in = false;

Определяют Ваш получатель внутри onCreate Вашего действия:

        mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            int iii=2;
            if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
                iii=intent.getIntExtra("state", -1);
                if(Integer.valueOf(iii)==0){
                    Microphone_Plugged_in = false;
                    Toast.makeText(getApplicationContext(),"microphone not plugged in",Toast.LENGTH_LONG).show();
                }if(Integer.valueOf(iii)==1){
                    Microphone_Plugged_in = true;
                    Toast.makeText(getApplicationContext(),"microphone plugged in",Toast.LENGTH_LONG).show();
                }
            }
        }};
        IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        registerReceiver( mReceiver, receiverFilter );

добавляют onResume и onStope:

@Override
  protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    getApplicationContext().registerReceiver(mReceiver, filter);
}

@Override
protected void onStop() {
    super.onStop();
    getApplicationContext().unregisterReceiver(mReceiver);
}
0
ответ дан 28 November 2019 в 02:22
поделиться
Другие вопросы по тегам:

Похожие вопросы: