亲宝软件园·资讯

展开

Android蓝牙功能

RKGG爱吃鱼 人气:0

蓝牙:短距离无线通讯技术标准。蓝牙协议分为4层,即核心协议层、电缆替代协议层、电话控制协议层和其他协议层。其中核心协议层包括基带、链路管理、逻辑链路控制和适应协议四部分。链路管理(LMP)负责蓝牙组件间的建立。逻辑链路控制与适应协议(L2CAP)位于基带协议层上,属于数据链路层,是一个高层传输和应用层协议屏蔽基带协议的适配协议。

1)、第一种打开蓝牙的方式:

Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
 startActivityForResult(enableIntent,1);

2)、第二种打开蓝牙方式(静默)

权限配置:

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

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.enable();//打开
adapter.disable();//关闭

3)、通过代码搜索蓝牙

蓝牙数据传输:与Socket类似,网络中使用Socket和ServerSocket控制客户端和服务端,蓝牙通讯客户端为BluetoothSocket,服务端为BluetoothServerSocket。二者需要一个UUID(全局唯一标示符),格式如下:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX,被分为5段,其中3段字符数相同,都为4,第1段是8字符,最后一段12字符,UUID相当于Socket的端口,而蓝牙地址相当于Socket的IP。

一、搜索蓝牙设备

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import java.util.Set;
 
public class MainActivity extends AppCompatActivity {
 
    private BluetoothAdapter bluetoothAdapter;
    private TextView tvDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_main);
        tvDevices = (TextView) findViewById(R.id.tvDevices);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> paireDevices = bluetoothAdapter.getBondedDevices();
        if (paireDevices.size()>0){
            for (BluetoothDevice devices:paireDevices){
                tvDevices.append(devices.getName()+":"+devices.getAddress());
            }
        }
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//找到一个设备,发送一个广播
        this.registerReceiver(receiver,filter);
 
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//整个搜索完后发送广播
        this.registerReceiver(receiver,filter);
    }
    public void onClick_Search(View view){
        setProgressBarIndeterminateVisibility(true);
        setTitle("正在扫描...");
        if(bluetoothAdapter.isDiscovering()){
            bluetoothAdapter.cancelDiscovery();
        }
        bluetoothAdapter.startDiscovery();
    }
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    tvDevices.append(device.getName() + ":" + device.getAddress() + "\n");
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarVisibility(false);
                setTitle("搜索完成");
            }
        }
    };
}

真机测试效果图:

二、通过搜索,将搜到的设备连接并实现传输数据

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
 
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private BluetoothAdapter bluetoothAdapter;//蓝牙适配器
    private ListView lvDevices;//显示蓝牙搜索控件
    private List<String> bluetoothDevices = new ArrayList<String>();//存储搜索到的所有蓝牙设备
    private ArrayAdapter<String> arrayAdapter;
    private final UUID MY_UUID = UUID.fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3");//手动输入UUID码
    private final String NAME = "Bluetooth_Socket";
    private BluetoothSocket clientSocket;//服务端
    private BluetoothDevice device;
    private OutputStream os;
    private AcceptThread acceptThread;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_main);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//初始化
        lvDevices = (ListView) findViewById(R.id.lvDevices);
 
     //显示配对的蓝牙信息
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                bluetoothDevices.add(device.getName() + ":" + device.getAddress() + "\n");
            }
        }
        //显示设备在列表上
        arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                android.R.id.text1, bluetoothDevices);
        lvDevices.setAdapter(arrayAdapter);
        lvDevices.setOnItemClickListener(this);
        acceptThread = new AcceptThread();
        acceptThread.start();
    }
 
    public void onClick_Search(View view) {
        setProgressBarIndeterminateVisibility(true);
        setTitle("正在扫描...");
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        bluetoothAdapter.startDiscovery();
    }
 
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    bluetoothDevices.add(device.getName()+":"+device.getAddress()+"\n");
                    arrayAdapter.notifyDataSetChanged();
//                    tvDevices.append(device.getName() + ":" + device.getAddress() + "\n");
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle("连接蓝牙设备");
            }
        }
    };
    /*
    * 客户端设置
    * 单击事件
    * */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String s = arrayAdapter.getItem(position);
        String address = s.substring(s.indexOf(":") + 1).trim();//获取蓝牙IP
 
        try {
            if (bluetoothAdapter.isDiscovering()) {
                bluetoothAdapter.cancelDiscovery();//若当前蓝牙被使用,则关闭重新启用
            }
            try {
                if (device == null) {//若未连接,则获得远程设备
                    device = bluetoothAdapter.getRemoteDevice(address);
                }
                if (clientSocket == null) {
                    clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                    clientSocket.connect();//连接蓝牙
                    os = clientSocket.getOutputStream();//客户端向服务端输出文本
 
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (os != null) {
                os.write("发送信息到其他设备".getBytes("utf-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/*
* 服务端设置
* 设置一个Handler,用来显示
* */
    private android.os.Handler handler = new android.os.Handler() {
        public void handleMessage(Message msg) {
            Toast.makeText(MainActivity.this, String.valueOf(msg.obj), Toast.LENGTH_LONG).show();
            super.handleMessage(msg);
        }
    };
    //线程类
    private class AcceptThread extends Thread {
        private BluetoothServerSocket serverSocket;
        private BluetoothSocket socket;
        private InputStream is;
        private OutputStream os;
 
        public AcceptThread() {
            try {
                serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
        public void run() {
            try {
                socket = serverSocket.accept();
                is = socket.getInputStream();
                os = socket.getOutputStream();
                while (true) {
                    byte[] buffer = new byte[128];
                    int count = is.read(buffer);
                    Message msg = new Message();
                    msg.obj = new String(buffer, 0, count, "utf-8");
                    handler.sendMessage(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

真机测试效果图:

加载全部内容

相关教程
猜你喜欢
用户评论