其他分享
首页 > 其他分享> > day22蓝牙

day22蓝牙

作者:互联网

蓝牙简介

蓝牙是一种支持设备短距离通信(一般是10m之内)的无线电技术。能在包括移动电话、PDA、无线耳机、笔记本电脑、相关外设等众多设备之间进行无线信息交换。蓝牙的标准是IEEE802.15,工作在2.4GHz 频带,带宽为1Mb/s。

添加权限
<!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
字段

(1)使用隐士意图打开蓝牙
BluetoothAdapter.ACTION_REQUEST_ENABLE:请求打开本设备蓝牙
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE:允许本设备蓝牙被扫描
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION:允许本设备蓝牙被扫描时长
(2)广播接收者的Action频道
BluetoothDevice.ACTION_FOUND:扫描到远程设备
BluetoothAdapter.ACTION_DISCOVERY_FINISHED:本设备扫描完成
BluetoothDevice.ACTION_BOND_STATE_CHANGED:远程设备状态发生改变
(3)获得扫描到的远程设备
BluetoothDevice.EXTRA_DEVICE:获得远程设备
(4)配对状态
BluetoothDevice.BOND_BONDED:远程设备绑定成功
BluetoothDevice.BOND_BONDING:远程设备绑定中
BluetoothDevice.BOND_NONE:远程设备绑定失败

BluetoothManager 蓝牙管理类,管理BluetoothAdapter。主要负责管理蓝牙的本地连接。
BluetoothAdapter 蓝牙适配器类:代表本蓝牙设备
BluetoothDevice 蓝牙设备,配对后的远程蓝牙设备.
BluetoothServiceSocket 服务端连接类
BluetoothSocket:客户端连接类
UUID(universal unique identifier , 全局唯一标识符)
格式如下:UUID格式一般是”xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,可到http://www.uuidgenerator.com 申请。UUID分为5段,是一个8-4-4-4-12的字符串,这个字符串要求永不重复。蓝牙建立连接时双方必须使用固定的UUID
例如:文件传输服务
OBEXFileTransferServiceClass_UUID = ‘{00001106-0000-1000-8000-00805F9B34FB}‘

发消息方

Activity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button bt_open,bt_close,bt_scan,bt_connected;
    ListView list1,list2;
    BluetoothManager bluetoothManager;
    BluetoothAdapter bluetoothAdapter;
    MyReceiver myReceiver;
    MyAdapter myAdapter;
    MyAdapter myAdapter1;
    ArrayList<BluetoothDevice> arrayList = new ArrayList<>();
    ArrayList<BluetoothDevice> arrayList1 = new ArrayList<>();
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT > 23){
            int i = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (i == PackageManager.PERMISSION_DENIED){
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},100);
            }

        }
        initView();
        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(myReceiver,intentFilter);
        myAdapter = new MyAdapter(MainActivity.this,arrayList);
        list1.setAdapter(myAdapter);
        list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = arrayList.get(position);
                device.createBond();
            }
        });
        myAdapter1 = new MyAdapter(this,arrayList1);
        list2.setAdapter(myAdapter1);
        list2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = arrayList1.get(position);
                try {
                    BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                    new MyThread("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1",socket).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    private void initView() {
        bt_open = findViewById(R.id.btn_open);
        bt_close = findViewById(R.id.btn_close);
        bt_scan = findViewById(R.id.btn_scan);
        bt_connected = findViewById(R.id.btn_connected);
        list1 = findViewById(R.id.list1);
        list2 = findViewById(R.id.list2);
        bt_open.setOnClickListener(this);
        bt_close.setOnClickListener(this);
        bt_scan.setOnClickListener(this);
        bt_connected.setOnClickListener(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_open:
                Intent intent = new Intent();
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,120);
                startActivity(intent);
                break;
            case R.id.btn_close:
                bluetoothAdapter.disable();
                break;
            case R.id.btn_scan:
                bluetoothAdapter.startDiscovery();
                break;
            case R.id.btn_connected:
                arrayList1.clear();
                Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
                arrayList1.addAll(bondedDevices);
                myAdapter1.notifyDataSetChanged();
                break;
        }
    }

    class MyReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                arrayList.add(device);
                myAdapter.notifyDataSetChanged();
            }
        }
    }
}

Adapter

public class MyAdapter extends BaseAdapter {

    Context context;
    ArrayList<BluetoothDevice> arrayList;

    public MyAdapter(Context context, ArrayList<BluetoothDevice> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return arrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = new TextView(context);
        BluetoothDevice device = arrayList.get(position);
        String name = device.getName();
        String address = device.getAddress();
        textView.setText(name+"      "+address);
        return textView;
    }
}

Thread

public class MyThread extends Thread {

    String strUrl;
    BluetoothSocket socket;

    public MyThread(String strUrl, BluetoothSocket socket) {
        this.strUrl = strUrl;
        this.socket = socket;
    }

    @Override
    public void run() {
        super.run();
        OutputStream outputStream = null;
        try {
            socket.connect();
            outputStream = socket.getOutputStream();
            int length = strUrl.getBytes().length;
            outputStream.write((length+"").getBytes());
            Thread.sleep(500);
            outputStream.write(strUrl.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
收消息方

activity

public class MainActivity extends AppCompatActivity {

    BluetoothManager bluetoothManager;
    BluetoothAdapter bluetoothAdapter;
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT > 23){
            int i = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (i == PackageManager.PERMISSION_DENIED){
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},70);
            }
        }
        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        openBlue();
    }

    private void openBlue() {
            Intent intent = new Intent();
            intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,120);
            startActivity(intent);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
                    while(true){
                        BluetoothSocket socket = serverSocket.accept();
                        new MyThread(socket,MainActivity.this).start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}

Thread

public class MyThread extends Thread {

    private BluetoothSocket socket;
    private Activity activity;

    public MyThread(BluetoothSocket socket, Activity activity) {
        this.socket = socket;
        this.activity = activity;
    }

    @Override
    public void run() {
        super.run();
        InputStream inputStream = null;
        Log.e("####","1111");
        try {
            inputStream = socket.getInputStream();
            final byte[] b = new byte[1024];
            int len = inputStream.read(b);
            int i = Integer.parseInt(new String(b, 0, len));
            Log.e("####","   "+i);
            int count=0;
            int len1 = 0;
            final StringBuffer stringBuffer = new StringBuffer();
            while ((len1 = inputStream.read(b)) != -1){
                stringBuffer.append(new String(b,0,len1));
                count+=len1;
                if(count==i){
                    break;
                }
            }
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, stringBuffer.toString(), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("####","3333");
        }finally {
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

标签:BluetoothDevice,socket,BluetoothAdapter,蓝牙,day22,Override,new,public
来源: https://blog.csdn.net/weixin_44419661/article/details/95617610