Andriod studio 学习 之 蓝牙

蓝牙

是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换

关于蓝牙的权限主要涉及到下面四个:

BLUETOOTH:允许配对的设备进行连接

BLUETOOTH_ADMIN:允许搜索和配对设备

ACCESS_COARSE_LOCATION:广播接收器接收BluetoothDevice.ACTION_FOUND广播需要改权限
ACCESS_FINE_LOCATION








一些介绍

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}’

真机测试效果

Andriod studio 学习 之 蓝牙_第1张图片

代码案例

xml布局

  

    
        

适配器xml布局

 

    

适配器中的代码

      package com.example.bluetooth.client;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.bluetooth.R;

import java.util.ArrayList;

public class Mybondedadpater extends BaseAdapter {
    private Context context;
    private ArrayList list;

    public Mybondedadpater(Context context, ArrayList list) {
        this.context = context;
        this.list = list;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Viewholder viewholder;
        if (convertView==null){
            convertView = LayoutInflater.from(context).inflate(R.layout.bonded_item, null);
            viewholder = new Viewholder();
            viewholder.blue = convertView.findViewById(R.id.blueid);
            convertView.setTag(viewholder);
        }else {
            viewholder = (Viewholder) convertView.getTag();
        }
        viewholder.blue.setText(list.get(position).getName());
        return convertView;
    }
    class Viewholder{
        TextView blue;
    }
}

activity代码

    package com.example.bluetooth.client;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothServerSocket;
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.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.example.bluetooth.R;
import com.example.bluetooth.Server.BlueSever;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

public class BlueClient extends AppCompatActivity {
    private Button open;
    private Button close;
    private Button search;
    private Button pair;
    private ListView nearblue;
    private ListView alerady;
    private BluetoothAdapter adapter;
    private ArrayList list = new ArrayList<>();
    private Mybondedadpater mybondedadpater;

    private Mybondedadpater mysearchadpater;
    private BluetoothDevice bluetoothDevice;
    private ArrayList devices = new ArrayList<>();
    private Mybroad mybroad;
    private Button server;
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==101){
                Toast.makeText(BlueClient.this, msg.obj.toString()+"连接成功", Toast.LENGTH_SHORT).show();
                Log.i("连接成功", "handleMessage: "+msg.obj.toString());
            }else if (msg.what==102){
                Toast.makeText(BlueClient.this, "接收到数据"+msg.obj.toString(), Toast.LENGTH_SHORT).show();
                Log.i("接收到数据", "handleMessage: "+msg.obj.toString());
            }
        }
    };
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_client);

        open = (Button) findViewById(R.id.open);
        close = (Button) findViewById(R.id.close);
        search = (Button) findViewById(R.id.search);
        pair = (Button) findViewById(R.id.pair);
        nearblue = (ListView) findViewById(R.id.nearblue);
        alerady = (ListView) findViewById(R.id.alerady);
        server = (Button) findViewById(R.id.server);


        String[] s={Manifest.permission.BLUETOOTH,Manifest.permission.BLUETOOTH_ADMIN,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            requestPermissions(s,101);
        }
        BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        adapter = manager.getAdapter();

        //已经配对的蓝牙的适配器
        mybondedadpater = new Mybondedadpater(this, list);
        alerady.setAdapter(mybondedadpater);

        //搜索的蓝牙
        mysearchadpater = new Mybondedadpater(this,devices);
        nearblue.setAdapter(mysearchadpater);

        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        mybroad = new Mybroad();
        registerReceiver(mybroad,intentFilter);

        //打开蓝牙
        open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                startActivity(intent);
            }
        });
        //关闭蓝牙
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.disable();
            }
        });

        //搜索蓝牙
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                devices.clear();
                adapter.startDiscovery();
            }
        });

        //接收他人消息
        server.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                startActivity(intent);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            BluetoothServerSocket serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(adapter.getName(), uuid);
                            while (true){
                                BluetoothSocket socket = serverSocket.accept();
                                Message message = new Message();
                                message.what=101;
                                message.obj=socket.getRemoteDevice().getName();
                                handler.sendMessage(message);
                                new MyServerThread(socket,handler).start();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        //已经配对的蓝牙
        pair.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.clear();
                Set bondedDevices = adapter.getBondedDevices();
                list.addAll(bondedDevices);
                mybondedadpater.notifyDataSetChanged();
            }
        });

        //进行配对
        nearblue.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                devices.get(position).createBond();
            }
        });

        //已经配对的开启线程发送数据
        alerady.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                BluetoothDevice device = list.get(position);
                try {
                    BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                    new MyClientThread(socket,"hello!").start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    class Mybroad extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
                if (device!=null){
                    devices.add(device);
                    mysearchadpater.notifyDataSetChanged();
                }
            }
        }
    }
    class MyClientThread extends Thread{
        private BluetoothSocket socket;
        private String message;

        public MyClientThread(BluetoothSocket socket, String message) {
            this.socket = socket;
            this.message = message;
        }

        @Override
        public void run() {
            super.run();
            try {
                socket.connect();
                if (socket.isConnected()){
                    socket.getOutputStream().write(message.getBytes());
                }else {
                    Log.i("xxx", "run: 连接失败");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    class MyServerThread extends Thread{
        BluetoothSocket socket;
        Handler handler;

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

        @Override
        public void run() {
            super.run();
            try {
                InputStream inputStream = socket.getInputStream();
                byte[] b = new byte[1024];
                int read = inputStream.read(b);
                String s = new String(b, 0, read);
                Message message = new Message();
                message.what=102;
                message.obj=s;
                handler.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(IT,安卓,计算机)