显示周围的蓝牙设备

布局文件有一个listview就行

public class ConnectActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initBT();
        listView.setAdapter(adapter);
    }

    void initView(){
        setContentView(R.layout.activity_connect);
        listView= (ListView) findViewById(R.id.lv_connect);

        int layout=android.R.layout.simple_list_item_1;
        //注意这个构造函数,别忘了<>
        adapter=new ArrayAdapter<>(context,layout,name);
    }
    //打开蓝牙和启动扫描
    void initBT(){
        btA=BluetoothAdapter.getDefaultAdapter();
        if (!btA.isEnabled()){//需要权限
            String string=BluetoothAdapter.ACTION_REQUEST_ENABLE;
            Intent intent=new Intent(string);
            startActivityForResult(intent,0);
        }
        String found_bt=BluetoothDevice.ACTION_FOUND;
        registerReceiver(br, new IntentFilter(found_bt));
        name.clear();
        mac.clear();
        btA.startDiscovery();//要蓝牙权限
    }

    //启动这个活动的方法
    public static void startCA(Context context){
        Intent intent=new Intent(context,ConnectActivity.class);
        //注意这一句
        context.startActivity(intent);
    }

    Context context=this;
    ListView listView;
    ArrayAdapter<String> adapter;
    BluetoothAdapter btA;
    List<String> name=new ArrayList<>();
    List<BluetoothDevice> mac=new ArrayList<>();
    //在这里为集合添加数据
    BroadcastReceiver br=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String bt_name=BluetoothDevice.EXTRA_NAME;
            String bt_mac=BluetoothDevice.EXTRA_DEVICE;
            name.add(intent.getStringExtra(bt_name));

            BluetoothDevice bd=intent.getParcelableExtra(bt_mac);
            mac.add(bd);
            adapter.notifyDataSetChanged();
        }
    };
}

我写代码习惯照AS的structure格式写,就是类,然后方法,最后常量或变量structure

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里是一个基于Android平台向蓝牙设备传输数据并显示设备上的完整用例: 1. 首先,需要在AndroidManifest.xml文件中添加以下权限: ```xml <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> ``` 2. 在MainActivity中创建一个蓝牙适配器(BluetoothAdapter)的实例,并启用蓝牙: ```java BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { // 设备不支持蓝牙 return; } if (!bluetoothAdapter.isEnabled()) { // 启用蓝牙 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } ``` 3. 搜索周围蓝牙设备,并选择要连接的设备: ```java Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { // 找到已配对的设备 for (BluetoothDevice device : pairedDevices) { if (device.getName().equals("设备名称")) { // 连接设备 ConnectThread connectThread = new ConnectThread(device); connectThread.start(); break; } } } else { // 没有已配对的设备,搜索新设备 Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION); startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE_BT); } ``` 其中,ConnectThread是自定义的一个线程类,用于连接蓝牙设备: ```java private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { // Use a temporary object that is later assigned to mmSocket // because mmSocket is final. BluetoothSocket tmp = null; mmDevice = device; // Get a BluetoothSocket to connect with the given BluetoothDevice. try { // MY_UUID is the app's UUID string, also used in the server code. tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { Log.e(TAG, "Socket's create() method failed", e); } mmSocket = tmp; } public void run() { // Cancel discovery because it otherwise slows down the connection. bluetoothAdapter.cancelDiscovery(); try { // Connect to the remote device through the socket. This call blocks // until it succeeds or throws an exception. mmSocket.connect(); } catch (IOException connectException) { // Unable to connect; close the socket and return. try { mmSocket.close(); } catch (IOException closeException) { Log.e(TAG, "Could not close the client socket", closeException); } return; } // The connection attempt succeeded. Perform work associated with // the connection in a separate thread. ConnectedThread connectedThread = new ConnectedThread(mmSocket); connectedThread.start(); } // Closes the client socket and causes the thread to finish. public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "Could not close the client socket", e); } } } ``` 4. 建立数据通道并发送数据: ```java private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the input and output streams; using temp objects because // member streams are final. try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "Error occurred when creating input/output stream", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { byte[] buffer = new byte[1024]; int numBytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs. while (true) { try { // Read from the InputStream. numBytes = mmInStream.read(buffer); // Send the obtained bytes to the UI activity. Message readMsg = mHandler.obtainMessage( MESSAGE_READ, numBytes, -1, buffer); readMsg.sendToTarget(); } catch (IOException e) { Log.d(TAG, "Input stream was disconnected", e); break; } } } // Call this method from the main activity to send data to the remote device. public void write(byte[] bytes) { try { mmOutStream.write(bytes); // Share the sent message with the UI activity. Message writtenMsg = mHandler.obtainMessage( MESSAGE_WRITE, -1, -1, bytes); writtenMsg.sendToTarget(); } catch (IOException e) { Log.e(TAG, "Error occurred when sending data", e); // Send a failure message back to the activity. Message writeErrorMsg = mHandler.obtainMessage(MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString("toast", "Couldn't send data to the other device"); writeErrorMsg.setData(bundle); mHandler.sendMessage(writeErrorMsg); } } // Call this method from the main activity to shut down the connection. public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "Could not close the connect socket", e); } } } ``` 5. 在UI线程中发送数据: ```java // 向蓝牙设备发送数据 byte[] bytes = "Hello, world!".getBytes(); connectedThread.write(bytes); ``` 6. 最后,将接收到的数据显示设备上: ```java private final Handler mHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what) { case MESSAGE_READ: byte[] readBuf = (byte[]) msg.obj; // 将接收到的数据显示在UI上 String readMessage = new String(readBuf, 0, msg.arg1); textView.setText(readMessage); break; // ... } return true; } }); ``` 以上就是一个完整的向蓝牙设备传输数据并显示设备上的Android应用程序的实现过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值