BlueTooth(蓝牙)

权限

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

打开

case R.id.bt_open:

                Intent intent = new Intent();
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,2000);
                startActivityForResult(intent,INTENT_CODE);

                break;

关闭

 case R.id.bt_close:

                adapter.disable();

                break;

扫描

 case R.id.bt_discovery:

                adapter.startDiscovery();

                break;
package com.example.app3;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;

import com.example.app3.adapter.DiscoveryAdapter;

import java.util.List;

public class MyReceiver extends BroadcastReceiver {

    private List<BluetoothDevice> list_discovery;
    private DiscoveryAdapter discoveryAdapter;

    public MyReceiver(List<BluetoothDevice> list_discovery, DiscoveryAdapter discoveryAdapter) {
        this.list_discovery = list_discovery;
        this.discoveryAdapter = discoveryAdapter;
    }

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

已配对

case R.id.bt_bond:

                list_bond.clear();
                Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
                list_bond.addAll(bondedDevices);
                adapter_bond.notifyDataSetChanged();

                break;

客户端

lv_bond.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    BluetoothSocket bluetoothSocket = list_bond.get(position).createInsecureRfcommSocketToServiceRecord(uuid);
                    bluetoothSocket.connect();
                    if (bluetoothSocket.isConnected()){
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                        OutputStream outputStream = bluetoothSocket.getOutputStream();
                        outputStream.write("你好吗?".getBytes());

                    }else {
                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

配对

lv_discovery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                list_discovery.get(position).createBond();
            }
        });

服务端

package com.example.app2;

import androidx.appcompat.app.AppCompatActivity;

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.os.Bundle;
import android.widget.Toast;

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


public class MainActivity extends AppCompatActivity {

    private BluetoothManager manager;
    private BluetoothAdapter adapter;
    private String[] strings = new String[]{Manifest.permission.BLUETOOTH,Manifest.permission.BLUETOOTH_ADMIN,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};
    private final int PERSSION_CODE = 101;
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");//蓝牙通讯规范

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(strings,PERSSION_CODE);
        }

        manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        adapter = manager.getAdapter();

        try {
            BluetoothServerSocket serverSocket =  adapter.listenUsingInsecureRfcommWithServiceRecord(adapter.getName(),uuid);
            BluetoothSocket socket = serverSocket.accept();
            Toast.makeText(this, socket.getRemoteDevice().getName()+"连到我了", Toast.LENGTH_SHORT).show();

            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int read = inputStream.read(bytes);
            String string = new String(bytes,0,read);
            Toast.makeText(this, string, Toast.LENGTH_SHORT).show();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

发布了27 篇原创文章 · 获赞 0 · 访问量 619

猜你喜欢

转载自blog.csdn.net/zrx_z/article/details/102943761