socket蓝牙连接代码-android 蓝牙 求帮助

android蓝牙主动发起配对实例 - wiley - ITeye技术网站
博客分类:
package cn.madfinger.
import java.io.IOE
import java.lang.reflect.M
import java.util.ArrayL
import java.util.L
import java.util.UUID;
import android.app.A
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.bluetooth.BluetoothS
import android.content.BroadcastR
import android.content.C
import android.content.I
import android.content.IntentF
import android.os.B
import android.util.L
import android.view.V
import android.widget.AdapterV
import android.widget.ArrayA
import android.widget.B
import android.widget.ListV
import android.widget.T
import android.widget.ToggleB
public class BlueToothTestActivity extends Activity {
//该UUID表示串口服务
//请参考文章
static final String SPP_UUID = "0-805F9B34FB";
Button btnSearch, btnDis, btnE
ToggleButton tbtnS
ListView lvBTD
ArrayAdapter&String& adtD
List&String& lstDevices = new ArrayList&String&();
BluetoothAdapter btA
public static BluetoothSocket btS
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Button 设置
btnSearch = (Button) this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new ClickEvent());
btnExit = (Button) this.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new ClickEvent());
btnDis = (Button) this.findViewById(R.id.btnDis);
btnDis.setOnClickListener(new ClickEvent());
// ToogleButton设置
tbtnSwitch = (ToggleButton) this.findViewById(R.id.tbtnSwitch);
tbtnSwitch.setOnClickListener(new ClickEvent());
// ListView及其数据源 适配器
lvBTDevices = (ListView) this.findViewById(R.id.lvDevices);
adtDevices = new ArrayAdapter&String&(this,
android.R.layout.simple_list_item_1, lstDevices);
lvBTDevices.setAdapter(adtDevices);
lvBTDevices.setOnItemClickListener(new ItemClickEvent());
btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
// ========================================================
// modified by wiley
* if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)// 读取蓝牙状态并显示
* tbtnSwitch.setChecked(false); else if (btAdapt.getState() ==
* BluetoothAdapter.STATE_ON) tbtnSwitch.setChecked(true);
if (btAdapt.isEnabled()) {
tbtnSwitch.setChecked(false);
tbtnSwitch.setChecked(true);
// ============================================================
// 注册Receiver来获取蓝牙设备相关的结果
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(searchDevices, intent);
private BroadcastReceiver searchDevices = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
Object[] lstName = b.keySet().toArray();
// 显示所有收到的消息及其细节
for (int i = 0; i & lstName. i++) {
String keyName = lstName[i].toString();
Log.e(keyName, String.valueOf(b.get(keyName)));
BluetoothDevice device =
// 搜索设备时,取得设备的MAC地址
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() == BluetoothDevice.BOND_NONE) {
String str = "未配对|" + device.getName() + "|"
+ device.getAddress();
if (lstDevices.indexOf(str) == -1)// 防止重复添加
lstDevices.add(str); // 获取设备名称和mac地址
adtDevices.notifyDataSetChanged();
}else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
switch (device.getBondState()) {
case BluetoothDevice.BOND_BONDING:
Log.d("BlueToothTestActivity", "正在配对......");
case BluetoothDevice.BOND_BONDED:
Log.d("BlueToothTestActivity", "完成配对");
connect(device);//连接设备
case BluetoothDevice.BOND_NONE:
Log.d("BlueToothTestActivity", "取消配对");
protected void onDestroy() {
this.unregisterReceiver(searchDevices);
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
class ItemClickEvent implements AdapterView.OnItemClickListener {
public void onItemClick(AdapterView&?& arg0, View arg1, int arg2,
long arg3) {
if(btAdapt.isDiscovering())btAdapt.cancelDiscovery();
String str = lstDevices.get(arg2);
String[] values = str.split("\\|");
String address = values[2];
Log.e("address", values[2]);
BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
Boolean returnValue =
if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
//利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
Method createBondMethod = BluetoothDevice.class
.getMethod("createBond");
Log.d("BlueToothTestActivity", "开始配对");
returnValue = (Boolean) createBondMethod.invoke(btDev);
}else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
connect(btDev);
} catch (Exception e) {
e.printStackTrace();
private void connect(BluetoothDevice btDev) {
UUID uuid = UUID.fromString(SPP_UUID);
btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
Log.d("BlueToothTestActivity", "开始连接...");
btSocket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch)// 搜索蓝牙设备,在BroadcastReceiver显示结果
if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
Toast.makeText(BlueToothTestActivity.this, "请先打开蓝牙", 1000)
if (btAdapt.isDiscovering())
btAdapt.cancelDiscovery();
lstDevices.clear();
Object[] lstDevice = btAdapt.getBondedDevices().toArray();
for (int i = 0; i & lstDevice. i++) {
BluetoothDevice device = (BluetoothDevice) lstDevice[i];
String str = "已配对|" + device.getName() + "|"
+ device.getAddress();
lstDevices.add(str); // 获取设备名称和mac地址
adtDevices.notifyDataSetChanged();
setTitle("本机蓝牙地址:" + btAdapt.getAddress());
btAdapt.startDiscovery();
} else if (v == tbtnSwitch) {// 本机蓝牙启动/关闭
if (tbtnSwitch.isChecked() == false)
btAdapt.enable();
else if (tbtnSwitch.isChecked() == true)
btAdapt.disable();
} else if (v == btnDis)// 本机可以被搜索
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
} else if (v == btnExit) {
if (btSocket != null)
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
BlueToothTestActivity.this.finish();
浏览 19143
浏览: 220449 次
来自: 上海
多谢楼主配对那一段,解决了我的大问题啊
这个反射的createBond用法很有意思这个代码能像非and ...
例子还是短小看着一目了然。不错
在WEB中,是使用WebApplicationContext的 ...
请问一下楼主,这个UUID是不是和设备有关啊,我使用你的 co ...Android Developers
&&&↳
android.bluetooth.BluetoothSocket
Class Overview
A connected or connecting Bluetooth socket.
The interface for Bluetooth Sockets is similar to that of TCP sockets:
and . On the server
side, use a
to create a listening server
socket. When a connection is accepted by the ,
it will return a new
to manage the connection.
On the client side, use a single
to both initiate
an outgoing connection and to manage the connection.
The most common type of Bluetooth socket is RFCOMM, which is the type
supported by the Android APIs. RFCOMM is a connection-oriented, streaming
transport over Bluetooth. It is also known as the Serial Port Profile (SPP).
To create a
for connecting to a known device, use
to attempt a connection to the remote device.
This call will block until a connection is established or the connection
To create a
as a server (or "host"), see the
documentation.
Once the socket is connected, whether initiated as a client or accepted
as a server, open the IO streams by calling
in order to retrieve
objects, respectively, which are
automatically connected to the socket.
safe. In particular,
will always immediately abort ongoing
operations and close the socket.
Requires the
permission.
Developer Guides
For more information about using Bluetooth, read the
developer guide.
Public Methods
Closes the object and release any system resources it holds.
Attempt to connect to a remote device.
Get the input stream associated with this socket.
Get the output stream associated with this socket.
Get the remote device this socket is connecting, or connected, to.
Get the connection status of this socket, ie, whether there is an active connection with
remote device.
Inherited Methods
From class
Creates and returns a copy of this Object.
Compares this instance with the specified object and indicates if they
are equal.
Invoked when the garbage collector has detected that this instance is no longer reachable.
Returns the unique instance of
that represents this
object's class.
Returns an integer hash code for this object.
Causes a thread which is waiting on this object's monitor (by means of
calling one of the wait() methods) to be woken up.
Causes all threads which are waiting on this object's monitor (by means
of calling one of the wait() methods) to be woken up.
Returns a string containing a concise, human-readable description of this
Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.
(long millis, int nanos)
Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
specified timeout expires.
(long millis)
Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
specified timeout expires.
From interface
Closes the object and release any system resources it holds.
From interface
Closes the object and release any system resources it holds.
Public Methods
getInputStream
getOutputStream
getRemoteDevice
isConnected求大神解答 Android 蓝牙Socket连接多设备问题_android开发吧_百度贴吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&签到排名:今日本吧第个签到,本吧因你更精彩,明天继续来努力!
本吧签到人数:0成为超级会员,使用一键签到本月漏签0次!成为超级会员,赠送8张补签卡连续签到:天&&累计签到:天超级会员单次开通12个月以上,赠送连续签到卡3张
关注:113,026贴子:
求大神解答 Android 蓝牙Socket连接多设备问题收藏
Android 蓝牙Socket连接多设备问题,连接一台后,断开连接第二台就始终报异常
登录百度帐号推荐应用
为兴趣而生,贴吧更懂你。或BluetoothSocket
BluetoothSocket
public static class Gallery.LayoutParams extends ViewGroup.LayoutParams
java.lang.Object
android.view. ViewGroup.LayoutParams
android.widget.Gallery.LayoutParams
&&&&&&&& 已连接或连接到蓝牙套接字(socket)。
&&&&&&&& 蓝牙端口监听接口和TCP端口类似:Socket和ServerSocket类。在服务器端,使用BluetoothServerSocket类来创建一个 监听服务端口。当一个连接被BluetoothServerSocket所接受,它会返回一个新的BluetoothSocket来管理该连接。在客户
端,使用一个单独的BluetoothSocket类去初始化一个外接连接和管理该连接。
最通常使用的蓝牙端口是RFCOMM,它是被Android API支持的类型。RFCOMM是一个面向连接,通过蓝牙模块进行的数据流传输方式,它也被称为串行端口规范(Serial Port Profile,SPP)。
为了创建一个BluetoothSocket去连接到一个已知设备,使用方法 BluetoothDevice.createRfcommSocketToServiceRecord()。然后调用connect()方法去尝试一个 面向远程设备的连接。这个调用将被阻塞指导一个连接已经建立或者该链接失效。
为了创建一个BluetoothSocket作为服务端(或者“主机”),查看BluetoothServerSocket文档。
每当该端口连接成功,无论它初始化为客户端,或者被接受作为服务器端,通过getInputStream()和getOutputStream()来打开IO流,从而获得各自的InputStream和OutputStream对象
BluetoothSocket类线程安全。特别的,close()方法总会马上放弃外界操作并关闭服务器端口。
注意:需要BLUETOOTH权限。
&&&&&&&& BluetoothServerSocket
&&& InputStream
&&& OutputStream
&&& public void close ()
马上关闭该端口并且释放所有相关的资源。
在其它线程的该端口中引起阻塞,从而使系统马上抛出一个IO异常。
IOException
&&& public void connect ()
尝试连接到远程设备。
该方法将阻塞,指导一个连接建立或者失效。如果该方法没有返回异常值,则该端口现在已经建立。
当设备查找正在进行的时候,创建对远程蓝牙设备的新连接不可被尝试。在蓝牙适配器上,设备查找是一个重量级过程,并且肯定会降低一个设备的连接。使用cancelDiscovery()方法去取消一个外界的查询。查询并不由活动所管理,而作为一个系统服务来运行,所以即使它不能直接请求一个查询,应用 程序也总会调用cancelDiscovery()方法。
close()方法可以用来放弃从另一线程而来的调用。
IOException&&&& 一个错误,例如连接失败。
&&& public InputStream getInputStream ()
通过连接的端口获得输入数据流
即使该端口未连接,该输入数据流也会返回。不过在该数据流上的操作将抛出异常,直到相关的连接已经建立。
IOException
&&& public OutputStream getOutputStream ()
通过连接的端口获得输出数据流
即使该端口未连接,该输出数据流也会返回。不过在该数据流上的操作将抛出异常,直到相关的连接已经建立。
IOException
&&& public BluetoothDevice getRemoteDevice ()
获得该端口正在连接或者已经连接的远程设备。
更新: 20:16&&&&&&分享给朋友:
android.accessibilityservice
android.bluetooth
android.view
android.view.inputmethod
android.widget
2017&Copyright该学网()本站部分资源来自网友上传,如有侵权请邮件通知,我们将在3个工作日内删除。

我要回帖

更多关于 android蓝牙socket 的文章

 

随机推荐