蓝牙系统

首先,先放上布局文件

activity_main布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.bawei.a1508abluetooth.MainActivity_old">

    <TextView
        android:id="@+id/searchBlueTooth"
        android:text="点击搜索蓝牙"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView

        android:id="@+id/devices_list"
        android:visibility="gone"
        android:layout_below="@+id/searchBlueTooth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
          />
    <ListView
        android:id="@+id/bluetooth_devices_list"
        android:layout_below="@+id/searchBlueTooth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </ListView>
</RelativeLayout>

list_item布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.bawei.a1508abluetooth.MainActivity">

</RelativeLayout>

MainActivity

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.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
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 View.OnClickListener {
    public static final String TAG = "ABCDE";
    private List<String> dataSource  = new ArrayList<>();
    private TextView devices_list;
    private BluetoothAdapter bluetoothAdapter;
    private Set<BluetoothDevice> bondedDevices;
    private TextView searchBlueTooth;
    private ListView bluetooth_devices_list;
    //第二部开启广播并且进行获取周边蓝牙并输出到TextView
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            bluetoothAdapter.isEnabled();
            String action = intent.getAction();
            //获取已经搜索到的设备
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (/*bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED*/true) {
                    String address = bluetoothDevice.getAddress();//获取蓝牙的MAC地址
                    String name = bluetoothDevice.getName();//获取蓝牙的名称
                    String name_address= name + ":" + address;
                    dataSource.add(name_address);
//                    devices_list.append(name + ":" + address + "\n");//将蓝牙的地址和名称设置到TextView上
                }
            } else if (bluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                devices_list.append("搜索完毕");
                MyListViewAdapter  myListViewAdapter = new MyListViewAdapter(MainActivity.this,dataSource);
                bluetooth_devices_list.setAdapter(myListViewAdapter);

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //启动子线程创建蓝牙服务器


        IntentFilter intentFilter = new IntentFilter();//广播接收者的过滤器
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);//添加
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//添加发现蓝牙设备的action动作
        intentFilter.addAction(bluetoothAdapter.ACTION_DISCOVERY_FINISHED);//扫描蓝牙设备完毕
        this.registerReceiver(receiver, intentFilter);//注册蓝牙广播

        //第一步打开蓝牙并且将获取到的信息输出
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//获取蓝牙适配器
        bondedDevices = bluetoothAdapter.getBondedDevices();//将搜索到的蓝牙设备放入Set集合中
       /* for (BluetoothDevice device : bondedDevices) {
            String address = device.getAddress();//获取蓝牙的MAC地址
            String name = device.getName();//获取蓝牙的名称
            devices_list.append(name + ":" + address + "\n");//将蓝牙的地址和名称设置到TextView上

        }*/

        BluetoothServerSocketThread bluetoothServerSocketThread = new BluetoothServerSocketThread();
        bluetoothServerSocketThread.start();//开启子线程


    }

    //第三部进行实例化
    private void initView() {
        devices_list = (TextView) findViewById(R.id.devices_list);
        searchBlueTooth = (TextView) findViewById(R.id.searchBlueTooth);
        searchBlueTooth.setOnClickListener(this);
        bluetooth_devices_list = (ListView) findViewById(R.id.bluetooth_devices_list);


        //为ListView添加点击事件,事件的具体内容上是建立蓝牙客户端,客户端给服务器发送一条消息
        bluetooth_devices_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             String TAG = "ABCDE";

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG,"0");
                String devices_name_addresss = dataSource.get(position);//从扫描到的蓝牙设备中拿到蓝牙设备的地址和名称
                Log.i(TAG,"1");
                //   bw:11.22222.444
                String devices_addresss = devices_name_addresss.substring(devices_name_addresss.indexOf(":") + 1);
                Log.i(TAG,"2");
                //getRemoteDevice(String address)
                //通过蓝牙设备的地址创建蓝牙设备
                BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(devices_addresss);
                Log.i(TAG,"3");
                // createRfcommSocketToServiceRecord(UUID uuid)
                UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
                Log.i(TAG,"4");
                try {
                    //根据已经创建的蓝牙设备创建一个该蓝牙设备的客户端,这里的uuid相当于是一个IP地址,通过地址就可以找到服务器
                    BluetoothSocket devicesClient = remoteDevice.createRfcommSocketToServiceRecord(uuid);
                    Log.i(TAG,"5");
                    devicesClient.connect();//链接到蓝牙服务器
                    Log.i(TAG,"6");

                    OutputStream outputStream = devicesClient.getOutputStream();
                    Log.i(TAG,"7");
                    outputStream.write("发送信息到蓝牙设备".getBytes());
                    Log.i(TAG,"8");
                    outputStream.flush();
                    Log.i(TAG,"9");


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



    }


    //点击搜索周围的蓝牙
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.searchBlueTooth://点击按钮开始搜索周边的蓝牙

                if (bluetoothAdapter.isDiscovering()) {//如果正在搜索蓝牙就停止搜索
                    bluetoothAdapter.cancelDiscovery();
                }
                bluetoothAdapter.startDiscovery();//使用蓝牙适配器搜索周边蓝牙
                break;
        }
    }

    //自定义一个展示发现的蓝牙设备的LListView控件的适配器
    class MyListViewAdapter extends BaseAdapter {

        private Context context;
        private List<String> dataSource ;

        public MyListViewAdapter(Context context, List<String> dataSource) {
            this.context = context;
            this.dataSource = dataSource;
        }

        @Override
        public int getCount() {//获取item条目的个数
            return dataSource.size();
        }

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(R.layout.list_item, null);
            }
            TextView item = (TextView) convertView.findViewById(R.id.item);
            item.setText(dataSource.get(position));
            return convertView;
        }
    }

    private class BluetoothServerSocketThread extends Thread {
        private BluetoothServerSocket bluetoothServerSocket;
        private BluetoothSocket clientSocket;
        private InputStream inputStream;
        private OutputStream outputStream;

        public BluetoothServerSocketThread( ) {
            //listenUsingRfcommWithServiceRecord(String name, UUID uuid)
//            UUID uuid = UUID.randomUUID();
            try {
                //创建蓝牙服务器,第一个参数是服务器的名称,第二个是一个唯一标识当前服务器的ID,相当于是一个IP地址
                UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
                bluetoothServerSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord("1508a_Service", uuid);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            super.run();
            try {
                clientSocket = bluetoothServerSocket.accept();//监听客户端的链接
                inputStream = clientSocket.getInputStream();
                outputStream = clientSocket.getOutputStream();


                while (true) {

                    byte[] buffer = new byte[1024];
                    int count = inputStream.read(buffer);
                    String message = new String(buffer, 0, count, "utf-8");
                    Looper.prepare();
                    Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
                    Looper.loop();

                }



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


        }
    }
}

同样注释掉的代码可以去掉!!!
MainActivity_old
这个activity的布局什么都没有,我就不上传了

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.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

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_old extends AppCompatActivity implements View.OnClickListener {
    private List<String> deviceList = new ArrayList<>();

    private TextView devices_list;

    private BluetoothAdapter bluetoothAdapter;
    private Set<BluetoothDevice> bondedDevices;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

        }
    };

    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 bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
                    String address = bluetoothDevice.getAddress();//获取蓝牙的MAC地址
                    String name = bluetoothDevice.getName();//获取蓝牙的名称
                    String name_address = name + ":" + address;
                    deviceList.add(name_address);
//                    devices_list.append(name + ":" + address + "\n");//将蓝牙的地址和名称设置到TextView上
                }
            } else if (bluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                devices_list.append("搜索完毕");
                MyAdapter myAdapter = new MyAdapter(MainActivity_old.this, deviceList);
                bluetooth_devices_list.setAdapter(myAdapter);
            }
        }
    };
    private TextView searchBlueTooth;
    private ListView bluetooth_devices_list;

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

        IntentFilter intentFilter = new IntentFilter();//广播接收者的过滤器
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);//添加
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//添加发现蓝牙设备的action动作
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//添加发现蓝牙设备的action动作
        this.registerReceiver(receiver, intentFilter);//注册蓝牙广播

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//获取蓝牙适配器
        bondedDevices = bluetoothAdapter.getBondedDevices();//将搜索到的蓝牙设备放入Set集合中
        for (BluetoothDevice device : bondedDevices) {
            String address = device.getAddress();//获取蓝牙的MAC地址
            String name = device.getName();//获取蓝牙的名称
            devices_list.append(name + ":" + address + "\n");//将蓝牙的地址和名称设置到TextView上

        }
        AcceptThread acceptThread = new AcceptThread();
        acceptThread.start();

    }

    private void initView() {
        devices_list = (TextView) findViewById(R.id.devices_list);
        searchBlueTooth = (TextView) findViewById(R.id.searchBlueTooth);
        searchBlueTooth.setOnClickListener(this);
        bluetooth_devices_list = (ListView) findViewById(R.id.bluetooth_devices_list);
//        bluetooth_devices_list.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.searchBlueTooth://点击按钮开始搜索周边的蓝牙

                if (bluetoothAdapter.isDiscovering()) {//如果正在搜索蓝牙就停止搜索
                    bluetoothAdapter.cancelDiscovery();
                }

                bluetoothAdapter.startDiscovery();//使用蓝牙适配器搜索周边蓝牙
                break;
        }
    }

    private class AcceptThread extends Thread {
        private BluetoothServerSocket serverSocket;
        private BluetoothSocket socket;
        private InputStream is;
        private OutputStream os;

        public AcceptThread() {
            UUID uuid = UUID.randomUUID();
            try {
                serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("name", uuid);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void run() {
            super.run();
            try {
                socket = serverSocket.accept();
                is = socket.getInputStream();
                os = socket.getOutputStream();
                while (true) {
                    byte[] buffer = new byte[1024];
                    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();
            }
        }
    }

    class MyAdapter extends BaseAdapter {

        private Context context;
        private List<String> deviceList;

        public MyAdapter(Context context, List<String> deviceList) {
            this.context = context;
            this.deviceList = deviceList;
        }


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

        @Override
        public Object getItem(int position) {
            return null;
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.devices_list, null);
            }
            TextView item = (TextView) convertView.findViewById(R.id.devices_item);
            item.setText(deviceList.get(position));
            return convertView;
        }
    }
}

这个代码是蓝牙和广播一起用的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值