Android使用蓝牙与PC端进行通信

目前Android只支持BluetoothSocket连接,而要对PC进行通信,直接使用BluetoothSocket是无法通信的,因为PC端使用java开发没有BluetoohSocket,所以PC端开发的时候必须采用J2ME的jar包进行开发
PC端作为服务端,Android作为客户端,目前只 能做到这一种方法连接,并且要有相同的UUID进行连接
开发代码:PC端(服务端核心代码)     
myPCConnNotifier = (StreamConnectionNotifier) Connector
.open("btspp://localhost:0000110100001000800000805F9B34FB");
        	System.out.println("等待读取消息.....");
// 获取流连接
streamConn = myPCConnNotifier.acceptAndOpen();
// 获取流通道
inputStream = streamConn.openInputStream();
// 读取字节流
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(inputStream));
System.out.println("得到的消息"+br.readLine());

Android代码(客户端核心代码)

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();// 获取蓝牙适配器
			if (bluetoothAdapter != null) {
				System.out.println("手机包含蓝牙。。。。。。。。。。。。。");
				if (!bluetoothAdapter.isEnabled()) {
					Intent intent = new Intent(
							BluetoothAdapter.ACTION_REQUEST_ENABLE);
					startActivity(intent);
				}
				bluetoothAdapter.enable();
				 Intent discoverableIntent = new Intent(
			                BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
				 discoverableIntent.putExtra(
			                BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
						try {
							UUID uuid=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
						
							mserverSocket = bluetoothAdapter
									.listenUsingInsecureRfcommWithServiceRecord(
											PROTOCOL_SCHEME_RFCOMM,uuid);
						
							Set<BluetoothDevice> devices=bluetoothAdapter.getBondedDevices();
							BluetoothDevice device=null;
							System.out.println(".......................");
							for(Iterator<BluetoothDevice> iterator=devices.iterator();iterator.hasNext();){
								device=iterator.next();
								System.out.println(device.getName());
								if("LIUYC-PC".equals(device.getName())){
									
									socket= device.createRfcommSocketToServiceRecord(uuid);
									socket.connect();
									
								}
							}
							socket=mserverSocket.accept();
							BufferedReader br = null;
							PrintWriter pw=null;
							br = new BufferedReader(new InputStreamReader(
									socket.getInputStream()));
							pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),false);
							pw.write("android开始返回消息啦");
							pw.flush();
							pw.close();
				
							System.out.println("收到的消息"+br.readLine());
							socket.close();
							
						} catch (IOException e) {
							System.out.println("错误");
							e.printStackTrace();
						}

PC客户端完整代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

import com.intel.bluetooth.BluetoothServerConnection;



/**
 * 实现蓝牙客户端,搜索蓝牙设备
 * 
 * @author Administrator
 * 
 */
public class BluetoothClientService implements DiscoveryListener, Runnable {
	private final static UUID TARGET_UUID = new UUID(
			"0000110100001000800000805F9B34FB", false);
	private StreamConnectionNotifier myPCConnNotifier = null;
	private Map<RemoteDevice, String> devicesMap = new HashMap<RemoteDevice, String>();
	private Vector<ServiceRecord> records = new Vector<ServiceRecord>();
	private DiscoveryAgent discoveryAgent = null;// 发现蓝牙设备
	private UUID[] uuidSet ;
	
	// 流连接
	private StreamConnection streamConn = null;
	// 接受数据字节流
	private byte[] acceptedByteArray = new byte[12];
	// 读取(输入)流
	private InputStream inputStream = null;
	
    private int activeIndex=-1; //存活的服务索引

	private int transIDs[]; // 服务搜索的事务id集合

	/**
	 * 发现设备,搜索设备时候每发现一个设备时回调,(包含上次蓝牙模块自动记录的设备以及新发现的设备)
	 */
	@Override
	public void deviceDiscovered(RemoteDevice btDevice, DeviceClass code) {
		String deviceName = null;
		try {
			deviceName = btDevice.getFriendlyName(false);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (devicesMap.get(btDevice) == null) {
			devicesMap.put(btDevice, deviceName);
		}
	}

	/**
	 * 搜索完毕,搜索设备结束时回调
	 */
	@Override
	public void inquiryCompleted(int arg0) {
		synchronized (this) {
			notify();
		}
	}

	/**
	 * 搜索完毕,服务搜索完毕的时候回调
	 */
	@Override
	public void serviceSearchCompleted(int transID, int respCode) {
		
		for (int i = 0; i < transIDs.length; i++) {
		
			if (transIDs[i] == transID) {
				transIDs[i] = -1;
			}
		}

		// 如果对所有的设备的服务都搜索完毕
		boolean finished = false;
		for (int i = 0; i < transIDs.length; i++) {
			if (transIDs[i] == -1) {
				finished = true;
				break;
			}
		}

		if (finished) {
			synchronized (this) {
				notify();
			}
		}

	}

	/**
	 * 服务发现,搜索服务时候回调
	 */
	@Override
	public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
		System.out.println("servRecord==="+servRecord);
		for (int i = 0; i < servRecord.length; i++) {
			records.addElement(servRecord[i]);
		}
		System.out.println("records="+records.size());

	}

	/**
	 * 启动线程,初始化设备
	 */
	@Override
	public synchronized void run() {

		if (initLocalDevice()) {
			try {
				  uuidSet=new UUID[2];
			        uuidSet[0]=new UUID(0x1101);    //0x1101表示 采用btspp协议
			        uuidSet[1]=new UUID(0x1103);         //目标服务标示
			        System.out.println(uuidSet[0]);
				discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);// 启动发现附近设备
				
				wait();
				//生成服务和属性的全球唯一标示符
				
				
				transIDs = new int[devicesMap.size()];
				
				int i = 0;
				for (Map.Entry<RemoteDevice, String> entry : devicesMap
						.entrySet()) {
					System.out.println("设备名称:" + entry.getValue());
					System.out.println("设备mac:" + entry.getKey());
					RemoteDevice rd = (RemoteDevice) entry.getKey();
					transIDs[i] = discoveryAgent.searchServices(null, uuidSet,
							rd, this);
			
					i++;
					
//					LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(transIDs, uuidSet, rd, this);
				}
				wait();
				activeIndex=getActiveService();
			} catch (BluetoothStateException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 查询本地蓝牙设备
	 * 
	 * @return 是否有蓝牙设备
	 */
	public boolean initLocalDevice() {
		boolean isReady = false;
		try {
			LocalDevice localDevice = LocalDevice.getLocalDevice();// 搜索本地设备
			discoveryAgent = localDevice.getDiscoveryAgent();// 获取本地蓝牙设备
			localDevice.setDiscoverable(DiscoveryAgent.GIAC);// 设置自身为不可发现状态,也就是搜索不到自己(状态待确定)
			isReady = true;
		} catch (BluetoothStateException e) {
			System.out.println("没有探测到蓝牙设备");
			e.printStackTrace();// 没有探测到本地蓝牙设备
		}
		return isReady;
	}

	/**
	 * 
	 * @return
	 */
	private int getActiveService() {
		accessService("message.............");
	
//		for(int i=0;i<records.size();i++){
//			ServiceRecord sr = (ServiceRecord) records.elementAt(i);
//			if(accessService(sr,"connect...")){
//				System.out.println("connet\\\\\\\\\\\\\\");
//              return i;                
//          }
//		}
		return -1;
	}

	//ServiceRecord sr,
    private boolean accessService(String msg){
        boolean result=false;
        String inSTR = null;
        
   
       try {
//        	System.out.println("连接蓝牙.....");
        	// 流连接通知 用于创建流连接
        	myPCConnNotifier = (StreamConnectionNotifier) Connector
			.open("btspp://localhost:0000110100001000800000805F9B34FB");
//        	System.out.println( "service="+ServiceRecord.NOAUTHENTICATE_NOENCRYPT);
//            String url = sr.getConnectionURL(
//                    ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
//            StreamConnection conn = (StreamConnection) Connector.open(url);
//            DataOutputStream dos=conn.openDataOutputStream();
//            dos.writeUTF(msg);
//            dos.close();
//            DataInputStream dis=conn.openDataInputStream();
//            String echo=dis.readUTF();
//            System.out.println(echo);
//            dis.close();

 
//        	StreamConnection con=(StreamConnection) Connector.open("btspp://localhost:0000110100001000800000805F9B34FB");
//        	RemoteDevice.getRemoteDevice(con);
//        	while (true) {
//        		
        		System.out.println("等待读取消息.....");
				// 获取流连接
				streamConn = myPCConnNotifier.acceptAndOpen();
				// 获取流通道
				inputStream = streamConn.openInputStream();
				// 读取字节流
				BufferedReader br = null;
			
				br = new BufferedReader(new InputStreamReader(inputStream));
			
				System.out.println("得到的消息"+br.readLine());
//				while (inputStream.read(acceptedByteArray) != -1) {
//					inSTR = new String(acceptedByteArray);
//					System.out.println(inSTR);
//					if (inSTR.contains("EXIT")) {
//						// 手机客户端退出则关闭连接通道。
//						inputStream.close();
//						if (streamConn != null) {
//							streamConn.close();
//						} 
//						break;
//					}  
//				}
//           
//        }
//        	
        } catch (IOException e) {
            System.out.println("exception here");
        }
        return result;
    }
	public static void main(String arg[]) {
		BluetoothClientService b = new BluetoothClientService();
		new Thread(b).start();

	}

}

Android客户端完整代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BluetoothActivity extends Activity implements OnClickListener {
	public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";

	private Button button = null;
	private BluetoothAdapter bluetoothAdapter = null;
	private BluetoothServerSocket mserverSocket = null;
	private BluetoothSocket socket =null;
	private InputStream inputStream = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		button = (Button) findViewById(R.id.button);
		button.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (button.getId() == id) {
			bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();// 获取蓝牙适配器
			if (bluetoothAdapter != null) {
				System.out.println("手机包含蓝牙。。。。。。。。。。。。。");
				if (!bluetoothAdapter.isEnabled()) {
					Intent intent = new Intent(
							BluetoothAdapter.ACTION_REQUEST_ENABLE);
					startActivity(intent);
				}
				bluetoothAdapter.enable();
				 Intent discoverableIntent = new Intent(
			                BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
				 discoverableIntent.putExtra(
			                BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
						try {
							UUID uuid=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
						
							mserverSocket = bluetoothAdapter
									.listenUsingInsecureRfcommWithServiceRecord(
											PROTOCOL_SCHEME_RFCOMM,uuid);
						
//							Set<BluetoothDevice> devices=bluetoothAdapter.getBondedDevices();
//							BluetoothDevice device=null;
//							System.out.println(".......................");
//							for(Iterator<BluetoothDevice> iterator=devices.iterator();iterator.hasNext();){
//								device=iterator.next();
//								System.out.println(device.getName());
//								if("LIUYC-PC".equals(device.getName())){
//									
//									socket= device.createRfcommSocketToServiceRecord(uuid);
//									socket.connect();
//									
//								}
//							}
							socket=mserverSocket.accept();
							BufferedReader br = null;
							PrintWriter pw=null;
							br = new BufferedReader(new InputStreamReader(
									socket.getInputStream()));
							pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),false);
							pw.write("android开始返回消息啦");
							pw.flush();
							pw.close();
				
							System.out.println("收到的消息"+br.readLine());
							socket.close();
							
						} catch (IOException e) {
							System.out.println("错误");
							e.printStackTrace();
						}
			

		

				// Set<BluetoothDevice>
				// devices=bluetoothAdapter.getBondedDevices();
				// if(devices.size()>0){
				// for(Iterator<BluetoothDevice>
				// iterator=devices.iterator();iterator.hasNext();){
				// BluetoothDevice device=iterator.next();
				// System.out.println("蓝牙名称"+device.getName());
				// System.out.println("蓝牙地址"+device.getAddress());
				// }
				// }else{
				// System.out.println("没有发现蓝牙设备");
				// }
			} else {
				System.out.println("不存在蓝牙");
			}

		}

	}

}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值