Android的蓝牙耳机连接 [英] Android Bluetooth headset connection

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

问题描述

我是新来的Andr​​oid平台。我与一个应用程序的工作,需要蓝牙的整合。要求是手动连接和断开蓝牙耳机(HSP配置文件),连接和断开应application.Is可能范围内可以连接和断开该设备在Android设备运行OS 4.2,4.3和4.4.If任何一个代替已针对此问题的解决方案,请告诉我的是一样的。

I am new to Android Platform. I am working with an application requires integration of Bluetooth. The requirement is instead of manually connecting and disconnecting a Bluetooth headset(HSP profile),Connection and disconnection should be possible within the application.Is it possible to connect and disconnect the device in Android devices running OS 4.2 ,4.3 and 4.4.If any one has a solution for this issue,Please advise me for the same.

推荐答案

这是可能的,但有时并非如此简单。

It is possible, but sometimes not that simple.

要通过检查你正在运行的设备是否有BT支持在所有连接,启动:

To connect, start by checking whether or not the device you are running on has BT support at all:

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter==null) {
   // device not support BT
}

如果没有 - 优雅地关闭您的应用程序的BT部分和移动

If not - gracefully disable the BT portion of your app and move on.

如果支持,查询天气或不是当前是启用(记住 - 用户可以
打开BT ON&安培;关闭与其他沟通渠道):

If supported, check weather or not it is currently enabled (remember - the user can turn BT on & off as with other communication channels):

boolean isEnabled = bluetoothAdapter.isEnabled(); // Equivalent to: getBluetoothState() == STATE_ON

而且,如果不启用,允许用户通过激发ACTION_REQUEST_ENABLE意图将其打开:

And, if not enable, allow the user to turn it on by firing an ACTION_REQUEST_ENABLE intent:

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, ENABLE_BT_CODE);

一旦你在可用性方面明确,你的目标是针对特定设备进行查找。
它始终是开始使用Android维护的保税设备列表是一个好主意:

Once you are clear in terms of availability, perform lookup for the specific device you aim for. It is always a good idea to start with the bonded device list maintained by Android:

Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();

for (BluetoothDevice device: pairedDevices) {
    if (device is the one we look for) {
       return device;
    }
}

如果没有 - 你将需要发出BT发现命令

If not - you will need to issue a BT discovery command.

愉所以请生成一个线程(使用AsyncTask的,执行者...)
做的工作。

Discovery must never be performed on the UI thread so please spawn a thread (use AsyncTask, Executer...) to do the work.

发现。该
对设备资源的影响将会太高。

Discovery should not be performed when a BT connection operation is still taking place. The impact on the device resources will be too high.

通过设置你的发现接收器启动:

Start by setting your discovery receiver:

discoveryReceiver = new BroadcastReceiver() {
    private boolean wasFound = false;
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        System.out.println(action);
        if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            discoveryStatus = STARTED;
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            discoveryStatus = FINISHED;
        }
        else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device is what we look for) {
                stopDiscovery(context);
            }
        }
    }
};
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(discoveryReceiver, filter);

和遵循一个开始命令:

boolean started = bluetoothAdapter.startDiscovery(); //async call!
if (!started) {
   // log error
}

一旦您找到您的设备,您将需要创建一个专门的BT插座:

Once you find your device, you will then need to create a dedicated BT socket:

BluetoothSocket clientSocket = null;
try {
    if (secureMode == SECURE) {
        clientSocket = device.createRfcommSocketToServiceRecord(serviceUuid);
    }
    else { // INSECURE
        clientSocket = device.createInsecureRfcommSocketToServiceRecord(serviceUuid);
    }
    if (clientSocket == null) {
       throw new IOException();
    }

} catch (IOException e) {
    // log error
}

其次是连接命令:

Followed by connect command:

   clientSocket.connect(context);

一旦连接的回报,你可将数据传输回&安培;提出你套接字和做的方式,
完成时:

once connect returns you can transmit data back & forth the way you do with sockets and, when done:

  clientSocket.close(context);

上面描述的一般流程。在很多情况下,你的工作将变得更加困难:

The above depicts the general flow. In many cases your work will be harder:

您将使用为安全与不安全的BT模式,不同的套接字生成方法。您将使用不同的
方法来查询设备支持的UUID。您也可以有时不得不求助于反射来激活隐藏的服务,例如, getUuids()为Android&LT; 15版本而这样的例子不胜枚举。

You will use different socket generation methods for secure vs. insecure BT modes. You will use different methods to interrogate the device for supported UUIDs. You may also sometimes have to resort to reflection to activate hidden services e.g. getUuids() for Android < ver 15. And the list goes on.

这是有道理的,尤其是对于初学者,使用工具这项工作。

It makes sense, especially for a beginner, to use a tool for this job.

我最喜欢的(我有偏见,我写的..)是 BTWiz 这将封装以上
从你流,也将为你提供一个简单的界面,异步IO。随意尝试一下。

My favorite (I am biased, I wrote it..) is BTWiz which will encapsulate the above flow from you and will also provide you with a simple interface for async IO. Feel free to try it out.

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

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