如何实现android蓝牙开发 qt蓝牙自动配对对连接,并不弹出提示框

Android实现蓝牙的搜索,配对(不需要输入PIN,自动匹配),连接,通信
实现蓝牙的搜索,配对(不需要输入PIN,自动匹配),连接,通信
一、蓝牙设置权限
需要在AndroidManifest.xml配置获得蓝牙权限。
按照SDK说明需要下面两个权限就可以进行蓝牙的开发。
在android6.0之后为了更好的保护用户的数据安全,所有需要访问硬件唯一标识符的地方都需要申请位置权限,也就是需要申请以下权限
二、蓝牙搜索
1.首先需要获得蓝牙适配器。
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
2.判断蓝牙是否打开,然后请求打开蓝牙
private void openBlueTooth() {
if (!mBluetoothAdapter.isEnabled()) {
//通过这个方法来请求打开我们的蓝牙设备
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,BLUETOOTH_RESPONSE);
通过这个方法可以判断是否允许打开蓝牙,然后进行下面相应的操作
case BLUETOOTH_RESPONSE:
if(resultCode == RESULT_OK){
//获得蓝牙权限成功
//需要再写一次,oncreate里的下面的方法无法执行
duringDialog(&正在连接蓝牙!&);
//搜索蓝牙
searchBlueTooth();
}else if(resultCode == RESULT_CANCELED){
//获得蓝牙权限失败
toast(ControlParkingActivity.this,&蓝牙权限获取失败,请打开蓝牙!&);
3.搜索蓝牙
如果已经打开蓝牙上面的搜索蓝牙不会执行,所以还需在onCreate方法中写搜索方法
//请求判断蓝牙是否提前打开
//如果没有提前打开则不会执行这句,执行openBluetooth的响应结果
//如果提前打开则执行下面
if(mBluetoothAdapter.isEnabled()){
duringDialog(&正在连接蓝牙!&);
searchBlueTooth();
搜索蓝牙方法如下:
//搜索蓝牙设备
private void searchBlueTooth() {
//判断蓝牙是否已经绑定
if(isBond()){
Log.d(TAG,&蓝牙已经绑定&);
//已经绑定,直接连接蓝牙
Log.d(TAG,device.getName() + &1&);
Log.d(TAG,&搜索蓝牙中&);
//搜索蓝牙设备
mBluetoothAdapter.startDiscovery();
三、蓝牙配对
蓝牙配对是通过广播接收器,搜索附近蓝牙设备,通过判断设备的address和name来判断是否为目标设备。之后利用ClsUtils工具类实现自动匹配蓝牙设备的功能。
1.动态注册广播接收器
mBluetoothReceiver = new BluetoothReceiver();
// 动态注册注册广播接收器。接收蓝牙发现讯息
IntentFilter btFilter = new IntentFilter();
btFilter.setPriority(1000);
btFilter.addAction(BluetoothDevice.ACTION_FOUND);
btFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
this.registerReceiver(mBluetoothReceiver,btFilter);
//设置广播信息接口监听器
mBluetoothReceiver.setReceiverMessageListener(this);
setPriority(1000):设置优先级,如果优先级比较低可能仍然会弹出输入pin的对话框
BluetoothDevice.ACTION_FOUND:发现设备时的action
BluetoothDevice.ACTION_PAIRING_REQUEST:当调用createBond()后就会发起BluetoothDevice.ACTION_PAIRING_REQUEST的广播
2.判断蓝牙设备是否为目标设备,并且创建绑定
//获得action
String action=intent.getAction();
//获取设备
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//获取搜索到的设备的名称和地址
String name = device.getName();
String address = device.getAddress();
if(action.equals(BluetoothDevice.ACTION_FOUND))
Log.d(TAG, &发现设备:& + name);
if ((name != null && btName.equals(name)) || btAddress.equals(address)) {
//判断远程设备是否已经被绑定
if(device.getBondState() != BluetoothDevice.BOND_BONDED){
Log.d(TAG, &发现目标设备,开始配对!&);
// 调用配对的方法,此方法是异步的,会触发BluetoothDevice.ACTION_PAIRING_REQUEST的广播
// 收到此广播后,设置配对的密码
ClsUtils.createBond(BluetoothDevice.class, device);
} catch (Exception e) {
e.printStackTrace();
//远程设备已经被绑定,取消搜索,返回信息
3.利用ClsUtils和事先获得的pin进行配对
else if(action.equals(&android.bluetooth.device.action.PAIRING_REQUEST&)){
//createBond后再次得到action,就会等于PAIRING_REQUEST
Log.d(TAG,&action2 = & + action);
Log.d(TAG, &发现设备:& + device.getAddress() + & & + device.getName());
if ((name != null && name.equals(btName)) || address.equals(btAddress)) {
Log.d(TAG, &发现目标设备,开始配对!&);
//1.确认配对
ClsUtils.setPairingConfirmation(device.getClass(), device, true);
//2.终止有序广播
Log.i(&order...&, &isOrderedBroadcast:&+isOrderedBroadcast()+&,isInitialStickyBroadcast:&+isInitialStickyBroadcast());
abortBroadcast();//如果没有将广播终止,则会出现一个一闪而过的配对框。
//3.调用setPin方法进行配对...
boolean ret = ClsUtils.setPin(device.getClass(), device, pin);
mReceiverMessage.setMessage(device);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG,&action2 = 配对失败!&);
//提示不是目标设备
Log.d(TAG,&action2 = 不是目标设备!&);
4.将绑定状态返回给activity,通知其绑定成功,可以进行蓝牙连接
广播中无法直接调用蓝牙连接的方法,在试了很多种方法后,最后通过接口实现了广播向activity传值的功能。
在BluetoothReceiver中写接口和接口监听器
public interface BluetoothReceiverMessage{
public void setMessage(BluetoothDevice device);
public void setReceiverMessageListener(BluetoothReceiverMessage bluetoothReceiverMessage){
this.mReceiverMessage = bluetoothReceiverM
绑定成功后,向activity发送消息(绑定设备)
mReceiverMessage.setMessage(device);
首先activity中要设置广播信息接口监听器
//设置广播信息接口监听器
mBluetoothReceiver.setReceiverMessageListener(this);
在activity中需要实现BluetoothReceiverMessage接口,重写对应的方法,进行蓝牙连接操作。
public class ControlParkingActivity extends AppCompatActivity implements BluetoothReceiver.BluetoothReceiverMessage
public void setMessage(BluetoothDevice device) {
if(device != null){
Log.d(TAG,&蓝牙绑定成功,开始连接!&);
this.device =
mChatService.connect(device,true);
四、蓝牙连接和通信
利用Google官方的BluetoothService进行蓝牙的连接和通信。
1.初始化BluetoothService
mChatService = new BluetoothChatService(this, mHandler);
2.通过Handle获取BluetoothService返回的信息和接收的数据
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
//蓝牙已连接
case BluetoothChatService.STATE_CONNECTING:
//蓝牙正在连接
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
//蓝牙未连接
case MESSAGE_WRITE:
//发送数据返回的结果
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
//读取数据
case MESSAGE_DEVICE_NAME:
// 保存已连接的设备名称
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), &Connected to &
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
case MESSAGE_TOAST:
3.向蓝牙设备发送数据
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
// Check that there's actually something to send
if (message.length() & 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
五、结束连接、通信
动态注册广播需要在活动结束时解除注册,如果有需要也可以调用ClsUtils.removeBond解除绑定。
protected void onDestroy() {
super.onDestroy();
mBluetoothAdapter.cancelDiscovery();
unregisterReceiver(mBluetoothReceiver);
Log.d(TAG,device + &
& + device.getBondState());
ClsUtils.removeBond(device.getClass(), device);
} catch (Exception e) {
Log.d(TAG,&解除绑定失败!&);
e.printStackTrace();
六、另附BluetoothChatService代码
* Copyright (C) 2009 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the &License&);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an &AS IS& BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
package com.example.sharingparking.
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.bluetooth.BluetoothServerS
import android.bluetooth.BluetoothS
import android.content.C
import android.os.B
import android.os.H
import android.os.M
import android.util.L
import com.example.sharingparking.activity.ControlParkingA
import java.io.IOE
import java.io.InputS
import java.io.OutputS
import java.util.UUID;
* This class does all the work for setting up and managing Bluetooth
* connections with other devices. It has a thread that listens for
* incoming connections, a thread for connecting with a device, and a
* thread for performing data transmissions when connected.
public class BluetoothChatService{
// Debugging
private static final String TAG = &BluetoothChatService&;
private static final boolean D =
// Name for the SDP record when creating server socket
private static final String NAME_SECURE = &BluetoothChatSecure&;
private static final String NAME_INSECURE = &BluetoothChatInsecure&;
// Unique UUID for this application
private static final UUID MY_UUID_SECURE =
UUID.fromString(&0-805F9B34FB&);
private static final UUID MY_UUID_INSECURE =
UUID.fromString(&0-805F9B34FB&);
// Member fields
private final BluetoothAdapter mA
private final Handler mH
private AcceptThread mSecureAcceptT
private AcceptThread mInsecureAcceptT
private ConnectThread mConnectT
private ConnectedThread mConnectedT
private int mS
// Constants that indicate the current connection state
public static final int STATE_NONE = 0;
// 蓝牙未连接
public static final int STATE_LISTEN = 1;
// 正在监听来的连接
public static final int STATE_CONNECTING = 2; // 正在连接
public static final int STATE_CONNECTED = 3;
// 已经连接
* Constructor. Prepares a new MainActivity session.
* @param context
The UI Activity Context
* @param handler
A Handler to send messages back to the UI Activity
public BluetoothChatService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler =
* Set the current state of the chat connection
* @param state
An integer defining the current connection state
private synchronized void setState(int state) {
if (D) Log.d(TAG, &setState() & + mState + & -& & + state);
//通过Handle返回给主活动连接状态
mHandler.obtainMessage(ControlParkingActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
* Return the current connection state. */
public synchronized int getState() {
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
if (D) Log.d(TAG, &start&);
// Cancel any thread attempting to make a connection
if (mConnectThread != null)
mConnectThread.cancel();
mConnectThread =
// Cancel any thread currently running a connection
if (mConnectedThread != null)
mConnectedThread.cancel();
mConnectedThread =
setState(STATE_LISTEN);
// Start the thread to listen on a BluetoothServerSocket
if (mSecureAcceptThread == null)
mSecureAcceptThread = new AcceptThread(true);
mSecureAcceptThread.start();
if (mInsecureAcceptThread == null)
mInsecureAcceptThread = new AcceptThread(false);
mInsecureAcceptThread.start();
* Start the ConnectThread to initiate a connection to a remote device.
* @param device
The BluetoothDevice to connect
* @param secure Socket Security type - Secure (true) , Insecure (false)
public synchronized void connect(BluetoothDevice device, boolean secure) {
if (D) Log.d(TAG, &connect to: & + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread =}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread =}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
setState(STATE_CONNECTING);
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket
The BluetoothSocket on which the connection was made
* @param device
The BluetoothDevice that has been connected
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
device, final String socketType) {
if (D) Log.d(TAG, &connected, Socket Type:& + socketType);
// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread =}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread =}
// Cancel the accept thread because we only want to connect to one device
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread =
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread =
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket, socketType);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(ControlParkingActivity.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(ControlParkingActivity.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
* Stop all threads
public synchronized void stop() {
if (D) Log.d(TAG, &stop&);
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread =
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread =
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread =
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread =
setState(STATE_NONE);
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
public void write(byte[] out) {
// Create temporary object
ConnectedT
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED)
r = mConnectedT
// Perform the write unsynchronized
r.write(out);
* Indicate that the connection attempt failed and notify the UI Activity.
private void connectionFailed() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(ControlParkingActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(ControlParkingActivity.TOAST, &Unable to connect device&);
msg.setData(bundle);
mHandler.sendMessage(msg);
// Start the service over to restart listening mode
BluetoothChatService.this.start();
* Indicate that the connection was lost and notify the UI Activity.
private void connectionLost() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(ControlParkingActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(ControlParkingActivity.TOAST, &Device connection was lost&);
msg.setData(bundle);
mHandler.sendMessage(msg);
// Start the service over to restart listening mode
BluetoothChatService.this.start();
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerS
private String mSocketT
public AcceptThread(boolean secure) {
BluetoothServerSocket tmp =
mSocketType = secure ? &Secure&:&Insecure&;
// Create a new listening server socket
if (secure) {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
MY_UUID_SECURE);
tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
NAME_INSECURE, MY_UUID_INSECURE);
} catch (IOException e) {
Log.e(TAG, &Socket Type: & + mSocketType + &listen() failed&, e);
mmServerSocket =
public void run() {
if (D) Log.d(TAG, &Socket Type: & + mSocketType +
&BEGIN mAcceptThread& + this);
setName(&AcceptThread& + mSocketType);
BluetoothSocket socket =
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, &Socket Type: & + mSocketType + &accept() failed&, e);
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothChatService.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice(),
mSocketType);
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
socket.close();
} catch (IOException e) {
Log.e(TAG, &Could not close unwanted socket&, e);
if (D) Log.i(TAG, &END mAcceptThread, socket Type: & + mSocketType);
public void cancel() {
if (D) Log.d(TAG, &Socket Type& + mSocketType + &cancel & + this);
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, &Socket Type& + mSocketType + &close() of server failed&, e);
* This thread runs while attempting to make an outgoing connection
* with a device. It r the connection either
* succeeds or fails.
private class ConnectThread extends Thread {
private final BluetoothSocket mmS
private final BluetoothDevice mmD
private String mSocketT
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice =
BluetoothSocket tmp =
mSocketType = secure ? &Secure& : &Insecure&;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
MY_UUID_SECURE);
tmp = device.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE);
} catch (IOException e) {
Log.e(TAG, &Socket Type: & + mSocketType + &create() failed&, e);
mmSocket =
public void run() {
Log.i(TAG, &BEGIN mConnectThread SocketType:& + mSocketType);
setName(&ConnectThread& + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, &unable to close() & + mSocketType +
& socket during connection failure&, e2);
connectionFailed();
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread =
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
public void cancel() {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, &close() of connect & + mSocketType + & socket failed&, e);
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
private class ConnectedThread extends Thread {
private final BluetoothSocket mmS
private final InputStream mmInS
private final OutputStream mmOutS
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, &create ConnectedThread: & + socketType);
mmSocket =
InputStream tmpIn =
OutputStream tmpOut =
// Get the BluetoothSocket input and output streams
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, &temp sockets not created&, e);
mmInStream = tmpIn;
mmOutStream = tmpO
public void run() {
Log.i(TAG, &BEGIN mConnectedThread&);
byte[] buffer = new byte[1024];
// Keep listening to the InputStream while connected
while (true) {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(ControlParkingActivity.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, &disconnected&, e);
connectionLost();
// Start the service over to restart listening mode
BluetoothChatService.this.start();
* Write to the connected OutStream.
* @param buffer
The bytes to write
public void write(byte[] buffer) {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(ControlParkingActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, &Exception during write&, e);
public void cancel() {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, &close() of connect socket failed&, e);}

我要回帖

更多关于 android弹出对话框 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信