蓝牙

折月煮酒 提交于 2020-02-27 14:09:18

蓝牙客户端

package com.example.day5_bluetooth;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");//蓝牙通讯规范
    private Button btOpen;
    private Button btClose;
    private Button btDiscovery;
    private Button btBond;
    private RecyclerView rvDiscovery;
    private RecyclerView rvBond;
    private BluetoothManager bluetoothManager;
    private static final String TAG = "MainActivity";
    private BluetoothAdapter bluetoothAdapter;
    private MyReceiver myReceiver;
    private MyAdapter myAdapter;
    private List<BluetoothDevice> list_device = new ArrayList<>();

    private MyAdapter mbone;
    private List<BluetoothDevice> list_bone = new ArrayList<BluetoothDevice>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            },120);
        }
        initView();

        initBluetooth();//获得本机设备
        //注册广播
        initReceVier();


    }

    private void initReceVier() {
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(myReceiver,intentFilter);

        
    }

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

    private void initBluetooth() {
        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
    }

    private void initView() {
        btOpen = (Button) findViewById(R.id.bt_open);
        btClose = (Button) findViewById(R.id.bt_close);
        btDiscovery = (Button) findViewById(R.id.bt_discovery);
        btBond = (Button) findViewById(R.id.bt_bond);
        rvDiscovery = (RecyclerView) findViewById(R.id.rv_discovery);
        rvBond = (RecyclerView) findViewById(R.id.rv_bond);
        //查询附近的蓝牙
        myAdapter = new MyAdapter(list_device,this);
                Log.i(TAG, "initView: "+list_device.size());
                rvDiscovery.setAdapter(myAdapter);
                //设置布局方式
                rvDiscovery.setLayoutManager(new LinearLayoutManager(this));
            myAdapter.setMyOnItemOnClick(new MyAdapter.MyOnItemOnClick() {
                @Override
                public void OnClick(int postition) {
                    list_device.get(postition).createBond();//进行配对
                }
            });
         //已经配对的设备
        mbone = new MyAdapter(list_bone,this);
        rvBond.setAdapter(mbone);
        rvBond.setLayoutManager(new LinearLayoutManager(this));
        mbone.setMyOnItemOnClick(new MyAdapter.MyOnItemOnClick() {
            @Override
            public void OnClick(int postition) {
                /**
                 * 客户端逻辑
                 * 创建BlueToothsocket
                 * 调用connect方法
                 * 发送数据/接受数据
                 */
                
                try {//1.创建bluetoothsocket
                    BluetoothSocket socket = list_bone.get(postition).createInsecureRfcommSocketToServiceRecord(uuid);
                    //2.调用connect方法建立连接
                    socket.connect();
                    //3.判断连接是否成功
                    if (socket.isConnected()){
                        Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();
                        //发送数据给服务端
                        socket.getOutputStream().write("碧海".getBytes());
                        //5.接送服务器返回的数据
                        InputStream inputStream = socket.getInputStream();
                        byte[] bys = new byte[1024];
                        int len = inputStream.read(bys);
                        String s = new String(bys,0,len);
                        Log.i(TAG, "OnClick: "+s);
                    }else {
                        Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void cli(View view) {
        int id = view.getId();
        switch (id){
            case R.id.bt_open:
                open();
                break;
            case R.id.bt_close:
                close();
                break;
            case R.id.bt_discovery:
                discovery();
                break;
            case R.id.bt_bond://获得配对
                //清空数据
                list_bone.clear();
                //获取到配对上的
                Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
                list_bone.addAll(bondedDevices);//添加数据源
                mbone.notifyDataSetChanged();//刷新
                break;
        }
    }
    //discover 发现
    private void discovery() {
        bluetoothAdapter.startDiscovery();
    }

    //关闭蓝牙
    private void close() {
        bluetoothAdapter.disable();
    }

    //打开蓝牙
    private void open() {
        Intent intent = new Intent();
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//被人发现
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//蓝牙可以用
        //设置时长
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,50);
        startActivity(intent);
    }
    //每扫描一个设备,手机会发送一个系统广播
    class MyReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //判断广播频道
            if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())){
                //扫描得到的设备             //BluetoothDevice 实现Parcelable 跨手机序列化
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                list_device.add(device);
                myAdapter.notifyDataSetChanged();
            }
        }
    }
}

蓝牙服务端

package com.example.day_lanya_server;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    private Button btOpenServer;
    private TextView tv;
    private static final String TAG = "MainActivity";
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");//蓝牙通讯规范
    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            }, 101);
        }
        btOpenServer = (Button) findViewById(R.id.bt_open_server);
        tv = (TextView) findViewById(R.id.tv);
        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        btOpenServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                open_server();
            }

        });
    }
    //启动服务端接受客户端的链接

    /**
     * 服务端逻辑
     * 创建BlueToothServersockt
     * 调用accpet接受客户端的链接
     * 发送数据/接受数据
     */
    private void open_server() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //创建ServerSocket
                    BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
                    //TODO 2:调用accept方法接受链接 注意 该方法是阻塞方法 长时间没有链接 UI阻塞
                    BluetoothSocket socket = serverSocket.accept();
                    //接受数据
                    InputStream inputStream = socket.getInputStream();
                    byte[] bytes = new byte[1024];
                    int len = inputStream.read(bytes);
                    String s = new String(bytes, 0, len);
                    Log.i(TAG, "run: "+s);
                    socket.getOutputStream().write("我不好".getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

添加的权限

<!-- 用于进行网络定位 -->
<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"/>


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!