Android-蓝牙

#准备

权限

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

Android6.0版本需要加

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

#获取蓝牙管理者和蓝牙适配器

/**
     * 获取蓝牙管理者
     * 获取蓝牙Adapter
     */
    private void initBluetooth() {
        btManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        btAdapter = btManager.getAdapter();
        if (btAdapter == null) {
            Toast.makeText(this, "蓝牙设备故障", Toast.LENGTH_SHORT).show();
            return;
        }
    }
	/**
     * 用回传的值判断蓝牙是否正常启动
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 100) {
            if (btAdapter.isEnabled()) {
                Toast.makeText(this, "蓝牙启动", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "蓝牙未启动", Toast.LENGTH_SHORT).show();
            }
        }
    }

#打开蓝牙、关闭蓝牙、扫描

	 /**
     * 打开蓝牙
     */
private void openBluetooth() {
        Intent intent = new Intent();
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//discoverable
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 60);
        startActivityForResult(intent, 100);
    }
    
    //关闭蓝牙的方法
    btAdapter.disable();
    
    /**
     * 扫描
     */
    public void scanning(View view) {
        if (btAdapter == null) {
            Toast.makeText(this, "蓝牙未开启", Toast.LENGTH_SHORT).show();
        }
        btAdapter.startDiscovery();
    }

#注册广播

/**
     * 注册广播
     */
    private void registerReceiver() {
        receive = new BluetoothReceive();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//接收发现蓝牙的广播
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//扫描结束的广播
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//配对状态的广播
        registerReceiver(receive, intentFilter);
    }

#自定义BroadcastReceiver

class BluetoothReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            	
            } else if (intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                Toast.makeText(context, "扫描完成", Toast.LENGTH_SHORT).show();
            } else if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//获取正在进行配对操作的device
                int bondState = device.getBondState();
                if (bondState == BluetoothDevice.BOND_BONDED) {//配对成功
                    Toast.makeText(context, "与" + device.getName() + "配对成功", Toast.LENGTH_SHORT).show();
                    new Thread(new ClientThread(device)).start();
                } else if (bondState == BluetoothDevice.BOND_BONDING) {//配对中
                    Toast.makeText(context, "正在与 " + device.getName() + " 配对", Toast.LENGTH_SHORT).show();
                } else if (bondState == BluetoothDevice.BOND_NONE) {//配对失败
                    Toast.makeText(context, "与 " + device.getName() + " 配对失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

#蓝牙发送文件

			
			private BluetoothDevice device;
     		private UUID uuid = UUID.fromString("您的uuid");
    		private String path = xxx;文件
    		
 			BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
            socket.connect();
            FileInputStream inputStream = new FileInputStream(path);
            OutputStream outputStream = socket.getOutputStream();
            byte[] bys = new byte[1024];
            int len = 0;
            while((len = inputStream.read(bys))!=-1){
                outputStream.write(bys,0,len);
            }

            outputStream.close();
            outputStream.flush();
            inputStream.close();

#蓝牙接收文件

 			BluetoothAdapter adapter;//本机蓝牙适配器
    		UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");//系统随机产生string字符串35年内不重复->连接蓝牙时秘钥

 			BluetoothServerSocket serverSocket = adapter.listenUsingRfcommWithServiceRecord(adapter.getName(),uuid);
            //侦听连接过来的socket
            BluetoothSocket socket = serverSocket.accept();
            Log.e("ZXY","蓝牙连接成功");
            InputStream in = socket.getInputStream();
            //向本地sd卡保存文件的输出流
            FileOutputStream out = new FileOutputStream(path);
            byte[]buff = new byte[1024];
            int leng = 0;
            while ((leng=in.read(buff))!=-1){
                out.write(buff,0,leng);
                Log.e("ZXY","服务器边读边保存");
            }
            out.flush();
            out.close();
            in.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值