Android Bluetooth

本文深入解析了Android中蓝牙协议的应用,包括如何打开蓝牙服务、寻找设备以及如何打开蓝牙Socket进行数据传输。通过示例代码,详细阐述了Android蓝牙功能的关键类和使用方法,帮助开发者更好地理解和实现蓝牙功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ALFA DeV工作室原创文章如转载,请注明:转载自博客原文地址:http://blog.youkuaiyun.com/kongre/article/details/6737288

蓝牙是一种在邻近的设备之间进行数据传输的开放无线协议。如果想使用蓝牙协议在手机上进行数据传输的话,首先需要开启手机的蓝牙服务,然后去寻找邻近的开启蓝牙服务的设备进行配对,配对成功之后,即可进行数据传输。如果在我们的Android应用程序需要使用Smart Phone的蓝牙服务,需要在我们的项目清单文件AndroidManifest.xml声明使用相应的权限。

<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>

android framework将有关蓝牙功能的API放在android.bluetooth包中。其中有五个比较关键的类,分别是

1.BluetoothAdapter: 主要用来寻找设备和初始化蓝牙服务的

2.BluetoothClass:主要用来描述蓝牙设备

3.BluetoothDevice:代表一个邻近的蓝牙设备

4.BluetoothSocket:代表的是与其他蓝牙设备进行数据传输的连接点

5.BluetoothServerSokcet:代表一个对配对请求进行监听的服务端套接字

接下来会对这些关键类进行分析和使用。

秘籍一、如何打开蓝牙服务(先关闭测试真机蓝牙服务)

	public class BluetoothActivity extends Activity {
		@SuppressWarnings("unused")
		private Button mTurnOnBluetooth, mDiscoverDevices, mPairWithBondedDevices, mOpenSocket;
		
		private BluetoothAdapter myBluetooth = null;//寻找蓝牙设备和初始化蓝牙连接
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        
	        mTurnOnBluetooth = (Button)findViewById(R.id.turnOnBluetooth);
	        mDiscoverDevices = (Button)findViewById(R.id.discoverBluetoothDevices);
	        mPairWithBondedDevices = (Button)findViewById(R.id.pairWithBondedDevices);
	        mOpenSocket = (Button)findViewById(R.id.openSocket);
	        
	        mTurnOnBluetooth.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					myBluetooth = BluetoothAdapter.getDefaultAdapter();
					if( !myBluetooth.isEnabled()){//如果没有开启蓝牙服务,启动内置Activity请求用户打开蓝牙服务
						Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
						startActivity(enableBluetoothIntent);
					}
				}
			});
	    }
	}
程序说明:BluetoothAdapter用来初始化蓝牙服务, 静态方法getDefaultAdapter()方法获取蓝牙服务的相关信息.如果方法返回null值,说明此手机不支持蓝牙服务。如果此时蓝牙服务没有被激活,那么可以使用内置Activity:BluetoothAdapter.ACTION_REQUEST_ENABLE来请求用户是否对应用程序进行授权,从而决定是否打开蓝牙服务。真机运行效果图如下:

秘籍二、寻找设备

public class BluetoothActivity extends Activity {
		
		private static String TAG = "BluetoothActivity";
		
		@SuppressWarnings("unused")
		private Button mTurnOnBluetooth, mDiscoverDevices, mPairWithBondedDevices, mOpenSocket;
		
		private BluetoothAdapter myBluetooth = null;//寻找蓝牙设备和初始化蓝牙连接
		
		 //定义广播接收者接受寻找到蓝牙设备或者曾经配对设备之后的系统广播
        private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if(BluetoothDevice.ACTION_FOUND.equals(action)){
					BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
					Log.d(TAG, "name:" + device.getName() + "\t address:" + device.getAddress());
				}
			}
		};
		
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        
	        mTurnOnBluetooth = (Button)findViewById(R.id.turnOnBluetooth);
	        mDiscoverDevices = (Button)findViewById(R.id.discoverBluetoothDevices);
	        mPairWithBondedDevices = (Button)findViewById(R.id.pairWithBondedDevices);
	        mOpenSocket = (Button)findViewById(R.id.openSocket);
	        
	        //打开蓝牙服务
	        mTurnOnBluetooth.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					myBluetooth = BluetoothAdapter.getDefaultAdapter();
					if( !myBluetooth.isEnabled()){//如果没有开启蓝牙服务,启动内置Activity请求用户打开蓝牙服务
						Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
						startActivity(enableBluetoothIntent);
					}
				}
			});
	        
	       
	        //寻找设备
	        mDiscoverDevices.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
					registerReceiver(mReceiver, filter);
					myBluetooth.startDiscovery();
				}
			});
	    }
	}
程序说明:在蓝牙服务被激活之后,用BluetoothAdapter的实例对象可以用来寻找附近的蓝牙设备,通过调用startDiscovery()方法。注意,这是一个异步调用方法。所以需要注册相应的广播接收者对BluetoothDevice.ACTION_FOUND系统广播进行接受,无论在何时只要一寻找到邻近的蓝牙设备就发送此系统广播。当然你也可以对ACTION_DISCOVERY_STARTED和ACTION_DISCOVERY_FINISHED系统广播进行接受,从而告诉应用程序什么时候寻找开始,什么时候寻找结束了。测试真机LOG日志如下:


秘籍三、打开一个蓝牙的Socket

跟JAVA的TCP编程其实是一个道理。

服务端线程:

private class AcceptThread extends Thread {
		private final BluetoothServerSocket mmServerSocket;

		public AcceptThread() {
			BluetoothServerSocket tmp = null;
			try {
				tmp = myBluetooth.listenUsingRfcommWithServiceRecord("test",
						randomUUID);
			} catch (IOException e) {
			}
			mmServerSocket = tmp;
		}

		@Override
		public void run() {
			super.run();
			BluetoothSocket socket = null;
			while (true) {
				try {
					socket = mmServerSocket.accept();
				} catch (IOException e) {
					break;
				}
				if (socket != null) {
					// do some work to communication
					try {
						mmServerSocket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					break;
				}

			}
		}
	}

客户端线程:

 @SuppressWarnings("unused")
		private class ConnectThread extends Thread{
	    	private final BluetoothSocket mmSocket;
	    	private final BluetoothDevice mmDevice;
	    	
	    	public ConnectThread(BluetoothDevice device){
	    		BluetoothSocket tmp = null;
	    		mmDevice = device;
	    		//get a BluetoothSocket to connect with the given BluetoothDevice
	    		//randomUUID is the app's UUID String, also used by the server code
	    		try{
	    			tmp = device.createRfcommSocketToServiceRecord(randomUUID);
	    		}catch(IOException e){
	    			
	    		}
	    		mmSocket = tmp;
	    	}
	    	
	    	@Override
	    	public void run() {
	    		super.run();
	    		myBluetooth.cancelDiscovery();//cancel the discovery because it will slow down the connection
	    		try{
	    			mmSocket.connect();//connect the device through the socket . This will block until it succeeds or throws an exception
	    		}catch(IOException connectionException){
	    			try {
						mmSocket.close();//unable to connect ;close the socket and get out
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return;
	    		}
	    		
	    		//do some work to communication
	    	}
	    }


上述大致介绍了有关Android Bluetooth使用的相关内容和细节,相信大家都已经掌握了相关知识。

最后如果你还是觉得我写的不够详细 看的不够爽 不要紧我把源代码的下载地址贴出来 欢迎大家一起讨论学习ALFA DeV工作室希望可以和大家一起进步。

下载地址:
http://download.youkuaiyun.com/source/3565226

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值