蓝牙

一.蓝牙介绍:

是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换,我们主要掌握这几项技能:

布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/open"
            android:text="打开蓝牙"
            android:layout_weight="1"></Button>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/colse"
            android:layout_weight="1"
            android:text="关闭蓝牙"></Button>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/scan"
            android:layout_weight="1"
            android:text="扫描蓝牙"></Button>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/show"
            android:layout_weight="1"
            android:text="显示已配对"></Button>
    </LinearLayout>
   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="horizontal">
       <LinearLayout
           android:layout_width="0dp"
           android:layout_height="match_parent"
           android:layout_weight="1">
           <TextView
               android:layout_width="0dp"
               android:layout_height="30dp"
               android:layout_weight="1"></TextView>
           <ListView
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:id="@+id/view_scan"></ListView>
       </LinearLayout>
       <LinearLayout
           android:layout_width="0dp"
           android:layout_height="match_parent"
           android:layout_weight="1">
           <TextView
               android:layout_width="0dp"
               android:layout_height="30dp"
               android:layout_weight="1"></TextView>
           <ListView
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:id="@+id/view_show"></ListView>
       </LinearLayout>
   </LinearLayout>


</LinearLayout>

适配器

public class MyBaseAdapter extends BaseAdapter {
    private ArrayList<BluetoothDevice> list;
    private Context context;

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

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

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        Holder holder;
        if (view==null){
            view = LayoutInflater.from(context).inflate(R.layout.layout,null);
            holder = new Holder();
            holder.textView = view.findViewById(R.id.textview);
            view.setTag(holder);
        }else{
            holder=(Holder)view.getTag();
        }
        holder.textView.setText(list.get(i).getName());
        return view;
    }
    class Holder{
        TextView textView;
    }
}

添加权限

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

打开蓝牙并设置允许被搜索

     open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
                startActivityForResult(intent,100);
            }
        });

关闭蓝牙

  colse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bluetoothAdapter.disable();
            }
        });

显示已经配对的蓝牙设备

 show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scanlist.clear();
                Toast.makeText(MainActivity.this,"显示已配对",Toast.LENGTH_SHORT).show();
                Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
                scanlist.addAll(bondedDevices);
                myBaseAdapter.notifyDataSetChanged();

            }
        });

扫描蓝牙

1.搜索附近蓝牙

  scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bluetoothAdapter.startDiscovery();
            }
        });

2.动态添加receiver

 IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        MyRecevier myRecevier = new MyRecevier();
        registerReceiver(myRecevier,intentFilter);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
            bluetoothAdapter = bluetoothManager.getAdapter();
        }

3.MyReceiver中的代码

 private class MyRecevier extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                showlist.add(device);
                myBaseAdapter1.notifyDataSetChanged();
            }
        }
    }

点击请求配对

  viewScan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                BluetoothDevice device = scanlist.get(i);
                device.createBond();
            }
        });

蓝牙通信客户端

1.线程中代码

public class ClientSendThread extends Thread{
    BluetoothSocket bluetoothSocket;
    String message;

    public ClientSendThread(BluetoothSocket bluetoothSocket, String message) {
        this.bluetoothSocket = bluetoothSocket;
        this.message = message;
    }

    @Override
    public void run() {
        super.run();
        try {
            bluetoothSocket.connect();
            if (bluetoothSocket.isConnected()){
                Log.i("-------------", "run: "+"连接成功");
                bluetoothSocket.getOutputStream().write(message.getBytes());
            }else{
                Log.i("-------------", "run: "+"连接失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.Activity中代码

   viewShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                BluetoothDevice device = showlist.get(i);
                try {
                    BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                    new ClientSendThread(socket,"啦啦啦").start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

服务器端

1.线程类

public class ServerThread extends Thread {
    BluetoothSocket socket;
    Handler handler;

    public ServerThread(BluetoothSocket socket, Handler handler) {
        this.socket = socket;
        this.handler = handler;
    }

    @Override
    public void run() {
        super.run();
        try {
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len = inputStream.read(bytes);
            String s = new String(bytes, 0, len);

            Message obtain = Message.obtain();
            obtain.what=102;
            obtain.obj=s;
            handler.sendMessage(obtain);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.Activity中代码


        open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
                startActivityForResult(intent,100);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
                            while (true){
                                BluetoothSocket socket = serverSocket.accept();
                                Message obtain = Message.obtain();
                                obtain.what=105;
                                obtain.obj = socket.getRemoteDevice().getName();
                                handler.sendMessage(obtain);
                                new ServerThread(socket,handler).start();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==105){
                Toast.makeText(MainActivity.this,""+msg.obj+"连接成功",Toast.LENGTH_SHORT).show();
            }else if (msg.what==102){
                Toast.makeText(MainActivity.this,"接收到数据"+msg.obj,Toast.LENGTH_SHORT).show();

            }
        }
    };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值