当前位置: 首页 > 知识库问答 >
问题:

Android蓝牙插座连接不工作

锺离德运
2023-03-14

我正在开发一个单例BluetoothHelper类。在connectToBTDevice()方法中,调用了一个新线程,在该线程中,蓝牙套接字试图连接到蓝牙设备。不幸的是,它开始时很好,但退出时有一个警告系统。错误如下:

04-11 20:46:15.711    2848-2848/? D/BluetoothHelper﹕ Connecting...name: Zakariya , address: 84:55:A5:8C:2E:2A
04-11 20:46:17.710    2848-3300/? W/System.err﹕ at com.prome.bluetoothdevicecontroller.helpers.BluetoothHelper.run(BluetoothHelper.java:262)
04-11 20:46:17.710    2848-3300/? D/BluetoothHelper﹕ could not connect to device
04-11 20:46:17.718    2848-3300/? D/BluetoothHelper﹕ socket closed

BluetoothHelper.java

package com.prome.bluetoothdevicecontroller.helpers;

import android.app.Activity;
import android.app.ProgressDialog;
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.Handler;
import android.os.Message;
import android.util.Log;

import com.prome.bluetoothdevicecontroller.activities.MainActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

/**
 * Bluetooth helper class
 *
 * @author Md. Nabid Imteaj
 * @version 1.0
 * @see android.bluetooth.BluetoothAdapter
 * @see <a href="http://developer.android.com/guide/topics/connectivity/bluetooth.html">http://developer.android.com/guide/topics/connectivity/bluetooth.html</a>
 */
public class BluetoothHelper implements Runnable {
    // tag
    public static final String TAG = "BluetoothHelper";

    // make it singleton
    private static BluetoothHelper bluetoothHelper = null;

    // bluetooth adapter
    private static BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // local integer > 0, taking random int which may not conflict
    // with other requestCode
    public static final int REQUEST_ENABLE_BT = 1001;

    // save found bluetooth devices in range
    ArrayList<BluetoothDevice> foundDevices = new ArrayList<>();

    // progress dialog
    ProgressDialog progress;

    // socket
    private BluetoothSocket mBluetoothSocket;
    private BluetoothServerSocket mBluetoothServerSocket;

    // uuid
    private UUID uuid = UUID.randomUUID();

    // bluetooth device
    private BluetoothDevice bluetoothDevice;

    // save context
    private Context context;

    // constructor
    private BluetoothHelper(Context context) {
        this.context = context;
    }

    /**
     * Returns new instance if not created, previous instance otherwise
     *
     * @return bluetoothHelper
     */
    public static BluetoothHelper getInstance(Context context) {
        if(bluetoothHelper == null) bluetoothHelper = new BluetoothHelper(context);
        return bluetoothHelper;
    }

    /**
     * Checks the device is Bluetooth supported or not
     *
     * @return true if the device is Bluetooth supported, false otherwise
     */
    public boolean isBluetoothSupported() {
        if(bluetoothAdapter == null) return false;
        return true;
    }

    /**
     * Enables Bluetooth
     *
     * @param context
     * @see android.app.Activity
     */
    public void enableBluetooth(Activity context) {
        if(!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            // note: onActivityResult() must be implemented in the parent activity
            // in our case it is defined in MainActivity
            context.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

            // save context for future use
            //this.context = context;
        }
    }

    /**
     * Returns paired devices connected with this device
     *
     * @return deviceList
     */
    public ArrayList<BluetoothDevice> getPairedDevices() {
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        ArrayList<BluetoothDevice> deviceList = new ArrayList<>();

        // check has paired devices or not
        if(pairedDevices.size() > 0) {
            // initiate array list
            //deviceList = new ArrayList<>();

            // get names, address and its type
            for(BluetoothDevice device : pairedDevices) {
                //deviceList.add(device.getName() + "\n" + device.getAddress());
                deviceList.add(device);
            }
        }

        return deviceList;
    }

    /**
     * Disables bluetooth
     */
    public void disableBluetooth() {
        bluetoothAdapter.disable();
    }

    /**
     * Cancel discovering devices
     * Must add it in onDestroy() of an activity or fragment
     */
    public void cancelDiscovery(Context context) {
        // if bluetooth is supported and is discovering devices
        // then cancel discovering devices
        if(bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
            // unregister receiver
            context.unregisterReceiver(mReceiver);
        }
    }

    /**
     * Start discovering bluetooth devices in range
     *
     * @param context
     */
    public void startDiscovery(Context context) {
        // get a new IntentFilter
        IntentFilter filter = new IntentFilter();

        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        // register broadcast receiver
        context.registerReceiver(mReceiver, filter);

        bluetoothAdapter.startDiscovery();
    }

    private void showProgress(Context context, String message) {
        progress = new ProgressDialog(context);
        progress.setMessage(message);
        progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progress.setIndeterminate(true);
        progress.setCancelable(false);
        progress.setCanceledOnTouchOutside(false);
        progress.show();
    }

    private void hideProgress() {
        if(progress.isShowing()) {
            progress.dismiss();
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                //discovery starts, we can show progress dialog or perform other tasks
                Log.d(BluetoothHelper.TAG, "discovery started");

                // clear previous list
                foundDevices.clear();

                // show loading dialog
                showProgress(context, "Scanning devices...");

            } else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //discovery finishes, dismis progress dialog
                Log.d(BluetoothHelper.TAG, "discovery finished");

                // hide progress dialog
                hideProgress();

                // show found devices
                ((MainActivity) context).startDeviceListDialog("Paired Devices", foundDevices);

            } else if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                //bluetooth device found
                BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                // insert this device into foundDevice array list
                foundDevices.add(device);

                //showToast("Found device " + device.getName());
                Log.d(BluetoothHelper.TAG, "found: " + device.getName() + ", " + device.getAddress());
            }
        }
    };

    /**
     * Returns found devices by searching in range
     *
     * @return ArrayList<BluetoothDevice>
     */
    public ArrayList<BluetoothDevice> getFoundDevices() {
        return foundDevices;
    }

    public void connectToBTDevice(BluetoothDevice device) {
        // get bluetooth device by address
        bluetoothDevice = bluetoothAdapter.getRemoteDevice(device.getAddress());

        // show dialog connecting
        showProgress(context, "Connecting..."+"\n"+device.getName()+"\n"+device.getAddress());
        Log.d(BluetoothHelper.TAG, "Connecting..."+"name: "+device.getName()+", address: "+device.getAddress());

        // create new thread
        Thread bluetoothConnectThread = new Thread(this);
        // start thread
        bluetoothConnectThread.start();
        //pairToDevice(mBluetoothDevice); This method is replaced by progress dialog with thread
    }

    // thread to connect with bluetooth device
    @Override
    public void run() {
        try {
            // open socket
            uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
            mBluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);

            // cancel discovering
            //cancelDiscovery(context);
            // already cancelled

            // connect through socket
            mBluetoothSocket.connect();

            Log.d(BluetoothHelper.TAG, "connected to device");

            // send empty message
            //mHandler.sendEmptyMessage(0);

        } catch(IOException e) {
            e.printStackTrace();
            Log.d(BluetoothHelper.TAG, "could not connect to device");
            //hide progress bar
            hideProgress();
            // close the socket
            try {
                mBluetoothSocket.close();
                Log.d(BluetoothHelper.TAG, "socket closed");
            } catch(IOException e1) {
                e1.printStackTrace();
                Log.d(BluetoothHelper.TAG, "socket could not be closed");
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideProgress();
            Log.d(BluetoothHelper.TAG, "connected with device");
        }
    };

    /**
     * make the device discoverable within 300 seconds
     */
    public void makeDiscoverable() {
        // create new intent
        Intent discoverableIntent = new
                Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        context.startActivity(discoverableIntent);
    }
}

onnectToBTDevice(BluetoothDevice device)方法位于第234行。BluetoothSocket connect()方法不适用于配对设备和非配对设备。

共有1个答案

酆恩
2023-03-14

连接后将退出线程。在run方法中,需要获取套接字的inputStream和outputStream来读写数据。

// thread to connect with bluetooth device
@Override
public void run() {
    try {
        // open socket
        uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        mBluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);

        // cancel discovering
        //cancelDiscovery(context);
        // already cancelled

        // connect through socket
        mBluetoothSocket.connect();

        Log.d(BluetoothHelper.TAG, "connected to device");


        InputStream mmInStream;
        OutputStream mmOutStream;
        // Get the BluetoothSocket input and output streams
        try 
        {
          mmInStream = socket.getInputStream();
          mmOutStream = socket.getOutputStream();
        } 
        catch (IOException e) 
        {
          Log.e(TAG, "error getting streams", e);
          return;
        }

        byte[] buffer = new byte[1024];
        int bytes;

        //* use the mmOutStream to write to the other end 
        //* but use the mmInSteam to read from the other end
        // Keep listening to the InputStream while connected
        while (true) 
        {
          try 
          {
            // Read from the InputStream
            bytes = mmInStream.read(buffer);
             /* do something with the bytes,
             ..............................
          } 
          catch (IOException e) 
          {
            Log.e(TAG, "disconnected", e);
            connectionLost();
            break;
          }
        }


        // send empty message
        //mHandler.sendEmptyMessage(0);

    } catch(IOException e) {
        e.printStackTrace();
        Log.d(BluetoothHelper.TAG, "could not connect to device");
        //hide progress bar
        hideProgress();
        // close the socket
        try {
            mBluetoothSocket.close();
            Log.d(BluetoothHelper.TAG, "socket closed");
        } catch(IOException e1) {
            e1.printStackTrace();
            Log.d(BluetoothHelper.TAG, "socket could not be closed");
        }
    }
}
 类似资料:
  • 我在我的电脑上开发了一个带有python的HIDServer(蓝牙键盘)。有2个服务器套接字(psm 0x11和0x13)正在侦听连接。当我尝试将IPhone连接到计算机时,我收到了一个传入连接(如hcidump中所示),但不知何故,连接被远程主机终止。我的套接字永远无法接受客户端连接。你能帮帮我吗? hciDumps: 启动我的程序后: HCI事件:命令完成(0x0e)plen 4写入扩展查询响

  • 我正在通过蓝牙连接2台设备,当我按下一台设备上的注销按钮时,我想向另一台设备发送消息(告诉另一台设备也注销),关闭蓝牙连接,并关闭当前活动(即返回我的登录活动) 问题是我总是得到这个异常,这让我觉得我没有正确地关闭我的连接: 是从输入流读取的位置 当按下logout时,我基本上销毁了< code>MainActivity,并在< code>onDestroy()中停止了我的蓝牙服务: < code

  • 问题内容: 我正在开发一个使用蓝牙连接到设备并发送/接收数据的应用程序。我正在使用Nexus One手机进行所有测试。 我从手机到任何设备都无法建立SPP(串行端口)连接。不过,我 已经 能够从一个设备(我的笔记本电脑)连接到使用Mac相当于腻子我的手机(唯一的例外是从市场上的“蓝牙文件传输”应用程序似乎是工作,但我不认为使用RFCOM / SPP …)。 我在LogCat日志中始终看到此消息:

  • 我如何获得Android所有已连接蓝牙设备的列表,而不考虑配置文件? 或者,我看到您可以通过BluetoothManager获取特定配置文件的所有连接设备。获取连接的设备。 我想我可以通过ACTION_ACL_CONNECTED/ACTION_ACL_DISCONNECTED监听连接/断开来查看哪些设备连接...似乎容易出错。 但我想知道是否有更简单的方法来获取所有已连接蓝牙设备的列表。

  • 我有一个android应用程序,它将所有配对的设备放在一个列表视图中。当您单击其中一个列表项时,它将发起连接到该蓝牙设备的请求。 我可以得到设备的列表和他们的地址没有问题。问题是,一旦我尝试连接,我会在socket.connect()上得到一个IOException; 错误消息如下:“连接读取失败,套接字可能关闭或超时,读取RET:-1” 请注意,在“尝试连接到设备”和“连接失败”之间有大约20秒

  • 我正在开发一个蓝牙应用程序来控制Arduino板,但现在我犯了一些错误:当我试图从手机连接时,它会显示一个(没关系)和许多祝酒(它们是从调用的)。BT模块连接到板子是可以的(测试与其他应用程序),所以问题是Java:我不能建立一个连接到我的BT模块。不幸的是,Android Studio没有给我任何日志或错误。这是我的代码: