检测Android耳机 [英] Detect headphones Android

查看:93
本文介绍了检测Android耳机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近几年使用Android编程,我想知道一些事情:

如何检测耳机的存在?
有一种方法: isWiredHeadsetOn(),但是不起作用.

我已经尝试过了,但是不起作用:

  AudioManager am =(AudioManager)getSystemService(AUDIO_SERVICE);Log.i("am.isWiredHeadsetOn()",am.isWiredHeadsetOn()+");如果(am.isWiredHeadsetOn()){//代码} 

谢谢(抱歉,如果我犯了拼写错误,我是法国人)

解决方案

@Phil的回答 https://stackoverflow.com/a/19102661/4758255 是检测耳机的好方法.

在这里,我引用他的回答.请不要为此回答他的答案!

投票答案: https://stackoverflow.com/a/19102661/4758255


我已经在商店中使用了一个应用程序三年,该应用程序可以同时监视有线耳机和蓝牙状态,而且从来没有人抱怨电池耗尽.但这是因为我成功地使用了单个服务和广播接收器来检测来自两者的事件.这是两个关键类:

 公共类HeadsetStateBroadcastReceiver扩展了BroadcastReceiver {公共静态最终String [] HEADPHONE_ACTIONS = {Intent.ACTION_HEADSET_PLUG,"android.bluetooth.headset.action.STATE_CHANGED","android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED"};@Overridepublic void onReceive(最终上下文上下文,最终Intent意图){布尔广播=假;//有线耳机监听如果(intent.getAction().equals(HEADPHONE_ACTIONS [0]){最终int状态= intent.getIntExtra("state",0);AudioPreferences.setWiredHeadphoneState(context,state> 0);广播=真;}//蓝牙监控//达到并包括Honeycomb如果(intent.getAction().equals(HEADPHONE_ACTIONS [1])){int状态= intent.getIntExtra("android.bluetooth.headset.extra.STATE",0);AudioPreferences.setBluetoothHeadsetState(context,state == 2);广播=真;}//适用于冰淇淋三明治如果(intent.getAction().equals(HEADPHONE_ACTIONS [2])){int状态= intent.getIntExtra("android.bluetooth.profile.extra.STATE",0);AudioPreferences.setBluetoothHeadsetState(context,state == 2);广播=真;}//用于通知感兴趣的活动耳机状态已更改如果(广播){LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("headsetStateChange"));}}} 

这是我用来注册广播接收器的服务:

 公共类HeadsetMonitoringService扩展了Service {HeadsetStateBroadcastReceiver耳机状态接收器;@Override公共无效onCreate(){HeaderStateReceiver =新的HeadsetStateBroadcastReceiver();最后的IntentFilter filter = new IntentFilter();对于(字符串操作:HeadsetStateBroadcastReceiver.HEADPHONE_ACTIONS){filter.addAction(action);}registerReceiver(headsetStateReceiver,filter);}@Overridepublic int onStartCommand(final Intent intent,final int flags,final int startId){返回START_STICKY;}@Override公共无效onDestroy(){unregisterReceiver(headsetStateReceiver);}@Override公开IBinder onBind(最终意图){返回null;}} 

这是我的清单条目:

 <服务android:name =.services.HeadsetMonitoringService"android:enabled ="true"android:exported ="false"><意图过滤器>< action android:name ="initialiseHeadsetService"/></intent-filter></service> 

工作原理如下:

我使用启动广播接收器将启动服务消息发送到HeadsetMonitoringService(您不必这样做,您可以在应用程序启动时执行此操作).HeadsetMonitoringService依次注册一个广播侦听器的实例,该实例侦听我感兴趣的所有耳机​​事件-它们保存在HEADPHONE_ACTIONS数组中.因为服务是粘性的,所以它挂了-广播侦听器也挂了.但是,由于服务和广播侦听器都是事件驱动的,因此在耳机状态发生更改之前,它们不会消耗任何功率.此外,由于该服务是粘性的,因此如果操作系统意外终止,它将由OS重新启动.
每当收到耳机状态更改事件时,我也会触发本地广播,以便感兴趣的活动可以检查新状态并在需要时采取措施.

为完整性起见,我应该指出,我使用另一个类(此处未显示)AudioPreferences将蓝牙和有线耳机状态都存储为首选项,然后在我需要知道耳机状态时都可以访问它们./p>

如果您对蓝牙耳机的状态感兴趣,则您的应用程序将需要android.permission.BLUETOOTH权限.如果没有,只需从HEADPHONE_ACTIONS数组中删除与蓝牙相关的操作,然后从onReceive方法中删除关联的if块.

I program in recent years to Android and I wonder something:

How to detect the presence of headphones?
There is a method: isWiredHeadsetOn() but it doesn't work.

I've tried that but it doesn't work:

AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
Log.i("am.isWiredHeadsetOn()", am.isWiredHeadsetOn() + "");

if (am.isWiredHeadsetOn()) {
   //code
}

Thank you (and sorry if I made spelling mistakes, I am French)

解决方案

@Phil answer at https://stackoverflow.com/a/19102661/4758255 is a good implementation to detect the headphone.

Here I'm quoting from his answer. Please upvoted his answer not this!

Upvote the answer: https://stackoverflow.com/a/19102661/4758255


I've had an app in the store for three years that monitors both the wired headset and bluetooth state and nobody has ever complained about battery drain. But that is because I am successfully using a single service and broadcast receiver for detecting events from both. Here's the two key classes:

public class HeadsetStateBroadcastReceiver extends BroadcastReceiver {

    public static final String[] HEADPHONE_ACTIONS = {
        Intent.ACTION_HEADSET_PLUG,
        "android.bluetooth.headset.action.STATE_CHANGED",
        "android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED"
    };

    @Override
    public void onReceive(final Context context, final Intent intent) {

        boolean broadcast = false;

        // Wired headset monitoring
        if (intent.getAction().equals(HEADPHONE_ACTIONS[0]) {
            final int state = intent.getIntExtra("state", 0);
            AudioPreferences.setWiredHeadphoneState(context, state > 0);
            broadcast = true;
        }

        // Bluetooth monitoring
        // Works up to and including Honeycomb
        if (intent.getAction().equals(HEADPHONE_ACTIONS[1])) {
            int state = intent.getIntExtra("android.bluetooth.headset.extra.STATE", 0);
            AudioPreferences.setBluetoothHeadsetState(context, state == 2);
            broadcast = true;
        }

        // Works for Ice Cream Sandwich
        if (intent.getAction().equals(HEADPHONE_ACTIONS[2])) {
            int state = intent.getIntExtra("android.bluetooth.profile.extra.STATE", 0);
            AudioPreferences.setBluetoothHeadsetState(context, state == 2);
            broadcast = true;
        }

        // Used to inform interested activities that the headset state has changed
        if (broadcast) {
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("headsetStateChange"));
        }

    }

}

Here is the service I use to register the broadcast receiver:

public class HeadsetMonitoringService extends Service {

    HeadsetStateBroadcastReceiver headsetStateReceiver;

    @Override
    public void onCreate() {

        headsetStateReceiver = new HeadsetStateBroadcastReceiver();
        final IntentFilter filter = new IntentFilter();
        for (String action: HeadsetStateBroadcastReceiver.HEADPHONE_ACTIONS) {
            filter.addAction(action);
        }

        registerReceiver(headsetStateReceiver, filter);

    }

    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(headsetStateReceiver);
    }

    @Override
    public IBinder onBind(final Intent intent) {
        return null;
    }

}

And here is my manifest entry:

    <service
        android:name=".services.HeadsetMonitoringService"
        android:enabled="true"
        android:exported="false" >
        <intent-filter>
            <action android:name="initialiseHeadsetService" />
        </intent-filter>
    </service>

How it works is as follows:

I use an on boot broadcast receiver to send a start service message to the HeadsetMonitoringService (you don't have to do it this way, you could just do this when your application starts instead). The HeadsetMonitoringService in turn registers an instance of a broadcast listener that listens to all the headset events I am interested in - they are held in the HEADPHONE_ACTIONS array. Because the service is sticky it hangs around - and therefore so does the broadcast listener. But because both the service and the broadcast listener are event driven they do not consume any power until a headset state change occurs. Additionally, because the service is sticky, it will be restarted by the OS if it dies unexpectedly.
Whenever I receive a headset state change event I also fire a local broadcast so that interested activities can check the new state and take action if required.

For completeness, I should point out that I use another class (not shown here), AudioPreferences, to store as preferences both the Bluetooth and wired headset state, which can then be accessed whenever I need to know the headset state.

Your application will need the android.permission.BLUETOOTH permission if you are interested in the state of a Bluetooth headset. If not, just take out the Bluetooth related actions from the HEADPHONE_ACTIONS array and delete the associated if blocks from the onReceive method.

这篇关于检测Android耳机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆