BluetoothSocket 未连接到目标设备

2024-01-10

我正在尝试通过蓝牙将我的设备连接到另一台设备,但是当我选择要连接的设备时,我得到一个IOException saying

读取失败,套接字可能关闭或超时,读取 ret: -1

只是为了说明我的应用程序是如何工作的,我有一个RecyclerView填充了我的蓝牙扫描找到的设备,然后当我单击某个项目时,应用程序应该与该设备连接。

下面是我的连接线程的代码:

private val MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb")

private lateinit var device: BluetoothDevice
private lateinit var onDeviceActionListener: OnDeviceActionListener
private lateinit var socket: BluetoothSocket

fun init(device: BluetoothDevice,
         onDeviceActionListener: OnDeviceActionListener): ConnectionThread {
    this.device = device
    this.onDeviceActionListener = onDeviceActionListener
    try {
        socket = device.createRfcommSocketToServiceRecord(MY_UUID)
    } catch (e: IOException) {
        Log.e(TAG, "Error creating socket", e)
    }
    return this
}

override fun run() {
    try {
        socket.connect()
    } catch (openException: IOException) {
        Log.e(TAG, "Error opening connection. Trying to close...", openException)
        try {
            socket.close()
        } catch (closeException: IOException) {
            Log.e(TAG, "Error closing socket", closeException)
        }
        return
    }
    onDeviceActionListener.onDeviceConnect(device)
}

我的猜测是我的 UUID 有问题。我尝试了一些其他值,但仍然不起作用。

任何帮助都感激不尽。


好吧,我不明白你在这里做错了什么。不过,我已经做了相当多的蓝牙工作。最近主要关注 BLE。您应该能够发现附近的 BT 设备并查看它们的 UUID。

我大约 3 年前编写了一个辅助类,所以它有点旧,但应该大部分是相同的代码。如果有帮助的话很高兴与您分享。

public class BluetoothConnector {

private static final String TAG = Globals.SEARCH_STRING + BluetoothConnector.class.getSimpleName();
private static final String DEFAULT_SERVER_NAME_FOR_APP = "tn_bt_default_server";
private static final int DEFAULT_DISCOVERABLE_DURATION_MS = 30000;
private static final UUID DEFAULT_UUID = UUID.fromString("6534c201-039c-4e4f-89f9-5ca8cfeb9667");
public static final int ENABLE_DISCOVER_INTENT = 1002;

protected boolean mIsToastEnabled = false; //Access from calling class to enable toasting of progress to screen if necessary
private Handler mUIHandler;
private static ServerSocketThread mServerSocketThread;
private static ClientSocketThread mClientSocketThread;
private ManageConnectionThread mManageConnectionThread;
private Context mContext;
private IBluetoothDataListener mBluetoothDataListener;
public final Object ServerSocketLock = new Object();
public final Object ClientSocketLock = new Object();
public final Object ManageConnectionLock = new Object();



public BluetoothConnector(Context context, IBluetoothDataListener listener){
    this(context, new Handler(Looper.getMainLooper()), listener);

}
public BluetoothConnector(Context context, Handler UIHandler, IBluetoothDataListener listener){
    Log.v(TAG, "BluetoothConnector(context=" + context + ", Handler=" + UIHandler.getClass().getSimpleName() + ", IBluetoothDataListener=" + listener.getClass().getSimpleName());
    mContext = context;
    mUIHandler = UIHandler;
    mBluetoothDataListener = listener;

}


public void makeThisDeviceDiscoverable(Activity callingActivity){
    makeThisDeviceDiscoverable(callingActivity, BluetoothAdapter.getDefaultAdapter(), DEFAULT_DISCOVERABLE_DURATION_MS);

}
public void makeThisDeviceDiscoverable(Activity callingActivity, BluetoothAdapter adapter){
    makeThisDeviceDiscoverable(callingActivity, adapter, DEFAULT_DISCOVERABLE_DURATION_MS);

}
public void makeThisDeviceDiscoverable(Activity callingActivity, int durationInMs){
    makeThisDeviceDiscoverable(callingActivity, BluetoothAdapter.getDefaultAdapter(), durationInMs);

}
public void makeThisDeviceDiscoverable(Activity callingActivity, BluetoothAdapter adapter, int durationInMs) {
    Log.v(TAG, "makeThisDeviceDiscoverable(callingActivity=" + callingActivity.getClass().getSimpleName() + ", BluetoothAdapter=" + (adapter == null ? "null" : adapter.getName()) + ", duration=" + String.valueOf(durationInMs));
    if(adapter == null){
        Log.v(TAG, "adapter is null");

    }else if(adapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
        Log.v(TAG, "Launching Activity to request Discoverable Permission");
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, durationInMs);
        callingActivity.startActivityForResult(discoverableIntent, ENABLE_DISCOVER_INTENT);

    }else{
        Log.v(TAG, "adapter is already in SCAN MODE");

    }

}
public void awaitConnectionFromDevice(){
    awaitConnectionFromDevice(DEFAULT_UUID, BluetoothAdapter.getDefaultAdapter());

}
public void awaitConnectionFromDevice(UUID commonKey){
    awaitConnectionFromDevice(commonKey, BluetoothAdapter.getDefaultAdapter());

}
public void awaitConnectionFromDevice(BluetoothAdapter adapter){
    awaitConnectionFromDevice(DEFAULT_UUID, adapter);

}
public void awaitConnectionFromDevice(UUID commonKey, BluetoothAdapter adapter){
    Log.v(TAG, "awaitConnectionFromDevice for UUID: " + String.valueOf(commonKey) + ", BluetoothAdapter=" + (adapter == null ? "null" : adapter.getName()));
    cancelDiscovery();

    synchronized (ServerSocketLock){
        if(mServerSocketThread != null){
            Log.v(TAG, "Server Socket Thread was not null so canceling current Thread");
            mServerSocketThread.cancel();

        }

        Log.v(TAG, "Attempting to Start new ServerThread");
        mServerSocketThread = new ServerSocketThread(commonKey, adapter);
        mServerSocketThread.start();

    }

}
public void cancelAwaitingConnectionFromDevice(){
    Log.v(TAG, "cancelAwaitingConnectionFromDevice");
    synchronized (ServerSocketLock){
        if(mServerSocketThread != null){
            mServerSocketThread.cancel();
            mServerSocketThread = null;
            Log.v(TAG, "canceling Server Socket Thread");

        }else{
            Log.v(TAG, "Server Socket null, so not canceling");

        }

    }

}

public void startDiscovery() {
    startDiscovery(BluetoothAdapter.getDefaultAdapter());

}
public void startDiscovery(BluetoothAdapter adapter){
    Log.v(TAG, "startDiscovery to find list of devices in range");
    adapter.startDiscovery();

}
public void cancelDiscovery() {
    cancelDiscovery(BluetoothAdapter.getDefaultAdapter());

}
public void cancelDiscovery(BluetoothAdapter adapter){
    Log.v(TAG, "cancelDiscovery");
    adapter.cancelDiscovery();

}
public void connectToDevice(BluetoothDevice device){
    connectToDevice(device, DEFAULT_UUID);

}
public void connectToDevice(BluetoothDevice device, UUID commonKey){
    Log.v(TAG, "connectToDevice(BluetoothDevice=" + (device == null ? "null" : device.getName()) + ", UUID=" + String.valueOf(commonKey));
    synchronized (ClientSocketLock){
        if(mClientSocketThread != null){
            Log.v(TAG, "Client Socket Thread was not null so canceling current Thread");
            mClientSocketThread.cancel();

        }else{
            Log.v(TAG, "Client Socket Thread is NULL so not canceling");

        }

        Log.v(TAG, "ClientSocketThread Starting");
        mClientSocketThread = new ClientSocketThread(device, commonKey);
        mClientSocketThread.start();

    }

}
public BluetoothDevice getBluetoothDeviceByMac(String mac){
    Log.v(TAG, "getBluetoothDeviceByMac(mac=" + mac);
    return getBluetoothDeviceByMac(mac, BluetoothAdapter.getDefaultAdapter());

}
public BluetoothDevice getBluetoothDeviceByMac(String mac, BluetoothAdapter adapter) {
    Log.v(TAG, "getBluetoothDeviceByMac(mac=" + mac + ", BluetoothAdapter=" + (adapter == null ? "null" : adapter.getName()));
    return adapter.getRemoteDevice(mac);

}

public ArrayList<KeyValueModel> getPairedDevices(){
    return getPairedDevices(BluetoothAdapter.getDefaultAdapter());
}
public ArrayList<KeyValueModel> getPairedDevices(BluetoothAdapter adapter){
    ArrayList<KeyValueModel> bondedDevices = new ArrayList<KeyValueModel>();

    Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
    Log.v(TAG, "getPairedDevices Found " + pairedDevices.size() + " number of paired devices");

    // If there are paired devices
    if (pairedDevices.size() > 0) {
        // Loop through paired devices
        for (BluetoothDevice device : pairedDevices) {
            // Add the name and address to an array adapter to show in a ListView
            bondedDevices.add(new KeyValueModel(device.getAddress(), device.getName()));

        }
    }

    return bondedDevices;
}
public static void unpairDevice(BluetoothDevice device){
    Log.v(TAG, "unpairDevice");
    try{
        Method method = device.getClass().getMethod("removeBond", (Class[]) null);
        method.invoke(device, (Object[]) null);

    }catch (Exception ex){
        Log.e(TAG, "Error Unpairing Device: " + ex.getMessage());

    }
}
public boolean sendDataToConnectedDevice(byte[] data){
    Log.v(TAG, "sendDataToConnectedDevice");
    synchronized (ManageConnectionLock){
        mManageConnectionThread.write(data);
        return true;

    }

}
public void setBluetoothDataListener(IBluetoothDataListener listener){
    mBluetoothDataListener = listener;
}
public boolean getIsConnected(){
    synchronized (ManageConnectionLock) {
        return mManageConnectionThread != null && mManageConnectionThread.isAlive();

    }
}

private void startManageConnectionThread(BluetoothSocket socket){
    Log.v(TAG, "startManageConnectionThread for Socket: " + (socket == null ? "null" : socket.getClass().getSimpleName()));
    synchronized (ManageConnectionLock) {
        mManageConnectionThread = new ManageConnectionThread(socket);
        mManageConnectionThread.start();

    }

}
private void handleDataReceivedFromConnectedDevice(final byte[] bytes){
    Log.v(TAG, "handleDataReceivedFromConnectedDevice");
    Log.v(TAG, "bytes to Listener: " + new String(bytes));

    if(mUIHandler != null && mBluetoothDataListener != null){
        mUIHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mBluetoothDataListener != null) {
                    mBluetoothDataListener.onReceivedPayloadFromConnectedDevice(bytes);

                }

            }

        });

    }else{
        Log.v(TAG, "UIHandler was null so skipped sending payload to listener");

    }

}
private void handleConnected(){
    Log.e(TAG, "handleConnected");
    if(mUIHandler != null && mBluetoothDataListener != null){
        mUIHandler.post(new Runnable() {
            @Override
            public void run() {
                if(mBluetoothDataListener != null){
                    mBluetoothDataListener.onConnectedToTargetDevice();

                }

            }

        });

    }else{
        Log.v(TAG, "UIHandler was null so skipped sending payload to listener");

    }

}
private void handleDisconnected(){
    Log.e(TAG, "handleDisconnected");
    if(mUIHandler != null && mBluetoothDataListener != null){
        mUIHandler.post(new Runnable() {
            @Override
            public void run() {
                if(mBluetoothDataListener != null){
                    mBluetoothDataListener.onDisconnectedFromTargetDevice();

                }
            }
        });

    }else{
        Log.v(TAG, "UIHandler or Listener was null so skipped sending payload to listener");

    }
}
private void handleFailedToConnectAsServer(final Exception ex){
    Log.e(TAG, "handleFailedToConnectAsServer ex:  " + ex.getMessage());
    if(mUIHandler != null && mBluetoothDataListener != null){
        mUIHandler.post(new Runnable() {
            @Override
            public void run() {
                if(mBluetoothDataListener != null){
                    mBluetoothDataListener.onFailedToReceiveConnectionFromTargetDevice(ex);

                }
            }
        });

    }else{
        Log.v(TAG, "UIHandler or Listener was null so skipped sending payload to listener");

    }

}
private void handleFailedToConnectAsClient(final Exception ex){
    Log.e(TAG, "handleFailedToConnectAsClient ex:  " + ex.getMessage());
    if(mUIHandler != null && mBluetoothDataListener != null){
        mUIHandler.post(new Runnable() {
            @Override
            public void run() {
                if(mBluetoothDataListener != null){
                    mBluetoothDataListener.onFailedToConnectToTargetDevice(ex);

                }
            }
        });

    }else{
        Log.v(TAG, "UIHandler or Listener was null so skipped sending payload to listener");

    }
}
private void handleErrorInRetrievingData(final Exception ex){
    Log.e(TAG, "handleErrorInRetrievingData ex:  " + ex.getMessage());
    if(mUIHandler != null && mBluetoothDataListener != null){
        mUIHandler.post(new Runnable() {
            @Override
            public void run() {
                if(mBluetoothDataListener != null){
                    mBluetoothDataListener.onErrorReceivingPayloadFromConnectedDevice(ex);

                }

            }
        });

    }else{
        Log.v(TAG, "UIHandler or Listener was null so skipped sending payload to listener");

    }

}
private void handleFailedToSendDataToConnectedDevice(final Exception ex){
    Log.e(TAG, "handleFailedToSendDataToConnectedDevice ex:  " + ex.getMessage());
    if(mUIHandler != null && mBluetoothDataListener != null){
        mUIHandler.post(new Runnable() {
            @Override
            public void run() {
                if(mBluetoothDataListener != null){
                    mBluetoothDataListener.onFailedToSendDataToConnectedDevice(ex);

                }

            }
        });

    }else{
        Log.v(TAG, "UIHandler or Listener was null so skipped sending payload to listener");

    }

}
private void toastMessage(final String value){
    if(!mIsToastEnabled || mUIHandler == null) {
        return;
    }

    mUIHandler.post(new Runnable() {
        @Override
        public void run() {
            try{
                Toast.makeText(mContext, value, Toast.LENGTH_SHORT).show();

            }catch(Exception ex){
                Log.v(TAG, "Error Toasting, possibly bad handler, or context: " + ex.getMessage());

            }
        }
    });
}


private class ServerSocketThread extends Thread{

    private final String TAG = Globals.SEARCH_STRING + ServerSocketThread.class.getSimpleName();
    private final BluetoothServerSocket mServerSocket;

    public ServerSocketThread(UUID commonKey, BluetoothAdapter adapter) {
        Log.v(TAG, "ServerSocketThread Constructor");
        BluetoothServerSocket tmp = null;

        try {
            Log.v(TAG, "listening for RFComas Server: " + DEFAULT_SERVER_NAME_FOR_APP + ", and commonKey: " + String.valueOf(commonKey));
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = adapter.listenUsingRfcommWithServiceRecord(DEFAULT_SERVER_NAME_FOR_APP, commonKey);
            toastMessage("Listening for RFComm As Server on UUID: " + String.valueOf(commonKey));

        } catch (IOException e) {
            Log.e(TAG, "Error creating ServerSocket: " + e.getMessage());
            toastMessage("Error Creating ServerSocket: " + e.getMessage());

        }

        mServerSocket = tmp;

    }

    public void run() {
        Log.v(TAG, "ServerSocket run");
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (mServerSocket != null) {
            try {
                Log.v(TAG, "ServerSocket.accept()");
                toastMessage("ServerSocket.accept()");
                //Waits for Client Connection to pass Socket, then we close down
                socket = mServerSocket.accept();

            } catch (IOException e) {
                Log.e(TAG, "ServerSocket.accept() Error: " + e.getMessage());
                toastMessage("ServerSocket.accept() Error: " + e.getMessage());
                handleFailedToConnectAsServer(e);
                break;

            }

            // If a connection was accepted we don't need to keep server listening, so close unless multiple client/server connections is desired
            if (socket != null) {
                try{
                    Log.v(TAG, "ServerSocket Accepted Client Socket, Begin Listening Connect Thread");
                    toastMessage("ServerSocket Accepted Client Socket, Begin Listening Connect Thread");
                    // Do work to manage the connection (in a separate thread)
                    startManageConnectionThread(socket);
                    //mServerSocket.close();

                }catch(Exception ex){
                    Log.e(TAG, "Exception closing Server Socket");

                }

                //break; //Add in Break if you want to shut down listening for connections
            }else{
                Log.v(TAG, "Socket wasn't accepted");
                toastMessage("Socket wasn't accepted");
                handleFailedToConnectAsServer(new Exception("Socket is Null"));

            }
        }

        Log.v(TAG, "Exiting Server Accept Thread");
    }
    public void cancel() {
        try {
            Log.v(TAG, "ServerSocketThread Canceled");
            mServerSocket.close();

        } catch (IOException e) {
            Log.e(TAG, "ServerSocketThread Error: " + e.getMessage());

        }
    }

}
private class ClientSocketThread extends Thread{

    private BluetoothSocket mSocket;
    private final BluetoothDevice mDevice;

    public ClientSocketThread(BluetoothDevice device, UUID commonKey) {
        Log.v(TAG, "ClientSocketThread Constructor");
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            Log.v(TAG, "Client creating RFComm Socket to Server with UUID: " + String.valueOf(commonKey));
            toastMessage("Client creating RFComm Socket to Server with UUID: " + String.valueOf(commonKey));
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(commonKey);

        } catch (IOException e) {
            Log.e(TAG, "Error creating Client Socket: " + e.getMessage());
            toastMessage("Creating Socket Exception: " + e.getMessage());
            handleFailedToConnectAsClient(e);

        }

        mSocket = tmp;

    }

    public void run() {
        try {
            if(mSocket == null){
                Log.e(TAG, "Error Client Socket is Null, Canceling Client Thread");
                return;

            }

            Log.v(TAG, "Client Connecting");
            // Connect to the server, or timeout eventually
            toastMessage("Client Connecting");
            mSocket.connect();

        } catch (IOException connectException) {
            // Unable to connect; close the socket and try the fallback method of reflection with port to connect
            try {
                Log.e("", "trying fallback...");
                toastMessage("Client Connection Failed Exception: " + connectException.getMessage());

                mSocket = (BluetoothSocket) mDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(mDevice, 1);
                toastMessage("Client Connect Again Attempt 2, but with fall back Reflection and port");
                Log.v(TAG, "Client Connect Again Attempt 2, but with fall back Reflection and port");
                mSocket.connect();

                Log.e("", "Connected");
                toastMessage("Client Connected");

            } catch (Exception ex) {
                Log.e("", "Couldn't establish Bluetooth connection!");
                toastMessage("Client Couldn't Establish Connection to Server: " + ex.getMessage());
                handleFailedToConnectAsClient(ex);
                return;

            }
        }

        // Do work to manage the connection (in a separate thread)
        startManageConnectionThread(mSocket);
    }
    public void cancel() {
        try {
            Log.v(TAG, "Client Socket cancel");
            mSocket.close();

        } catch (IOException e) {
            Log.e(TAG, "Error Closing Socket");

        }
    }

}
private class ManageConnectionThread extends Thread {

    /////////////
    // MEMBERS //
    /////////////
    private final String TAG = Globals.SEARCH_STRING + ManageConnectionThread.class.getSimpleName();
    private final BluetoothSocket mSocket;
    private final InputStream mInStream;
    private final OutputStream mOutStream;


    //////////////////
    //  CONSTRUCTOR //
    //////////////////
    public ManageConnectionThread(BluetoothSocket socket) {
        mSocket = socket;

        handleConnected();
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        try {
            Log.v(TAG, "ManageConnectionThread Constructor");
            Log.v(TAG, "Connected to Socket = " + String.valueOf(socket.isConnected()));
            toastMessage("Listening for input or output Stream");
            Log.v(TAG, "Get InputStream");
            tmpIn = socket.getInputStream();
            Log.v(TAG, "Get OutputStream");
            tmpOut = socket.getOutputStream();

        } catch (IOException e) {
            Log.e(TAG, "Error getting Socket Streams: " + e.getMessage());
            toastMessage("Connect Thread: Error: " + e.getMessage());
            handleErrorInRetrievingData(e);

        }

        mInStream = tmpIn;
        mOutStream = tmpOut;
    }


    ///////////////
    // OVERRIDES //
    ///////////////
    public void run() {
        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                byte[] data = new byte[16384];
                int nRead;
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();

                while ((nRead = mInStream.read(data, 0, data.length)) != -1) {
                    //Log.v(TAG, "bytes Read: " + String.valueOf(nRead));
                    buffer.write(data, 0, nRead);

                    //TODO Find better way to find End Of Message rather than looking for }
                    String temp = new String(buffer.toByteArray());
                    //Log.v(TAG, "current Data: " + temp);
                    if(temp.contains("}")){
                        Log.v(TAG, "bytes reading complete");
                        handleDataReceivedFromConnectedDevice(buffer.toByteArray());
                        buffer.flush();
                        buffer = new ByteArrayOutputStream();

                    }else{
                        Log.v(TAG, "More bytes Available");

                    }

                }

            } catch (IOException e) {
                Log.e(TAG, "Error reading inputStream");
                handleErrorInRetrievingData(e);
                break;

            }

        }

        Log.v(TAG, "Exiting Managed Connection Thread");
        handleDisconnected();

    }


    /////////////
    // METHODS //
    /////////////
    public void write(byte[] bytes) {
        try {
            Log.v(TAG, "ManageConnectionThread write(bytes)");
            mOutStream.write(bytes);

        } catch (IOException e) {
            Log.e(TAG, "Error Writing Stream: " + e.getMessage());
            handleFailedToSendDataToConnectedDevice(e);

        }
    }
    public void cancel() {
        try {
            Log.v(TAG, "ManageConnectionThread cancel");
            handleDisconnected();
            mSocket.close();

        } catch (IOException e) {
            Log.e(TAG, "Error Closing BluetoothSocket: " + e.getMessage());

        }
    }

}


public interface IBluetoothDataListener{

    //////////////////////
    // OVERRIDE METHODS //
    //////////////////////
    void onReceivedPayloadFromConnectedDevice(byte[] payload);
    void onErrorReceivingPayloadFromConnectedDevice(Exception ex);
    void onFailedToConnectToTargetDevice(Exception ex);
    void onFailedToReceiveConnectionFromTargetDevice(Exception ex);
    void onFailedToSendDataToConnectedDevice(Exception ex);
    void onConnectedToTargetDevice();
    void onDisconnectedFromTargetDevice();

}

}

当然,您需要确保您已设置广播接收器:

 <receiver
        android:name=".receivers.BluetoothChangedReceiver"
        android:enabled="true" >
        <intent-filter>
            <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
            <action android:name="android.bluetooth.adapter.action.SCAN_MODE_CHANGED" />
            <action android:name="android.bluetooth.adapter.action.DISCOVERY_STARTED" />
            <action android:name="android.bluetooth.adapter.action.DISCOVERY_FINISHED" />
            <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
            <action android:name="android.bluetooth.device.action.FOUND" />
            <action android:name="android.bluetooth.device.action.DISAPPEARED" />
        </intent-filter>
    </receiver>

    <receiver
        android:name=".receivers.BluetoothDeviceReceiver"
        android:enabled="true" >
        <intent-filter>
            <action android:name="android.bluetooth.device.action.FOUND" />
            <action android:name="android.bluetooth.device.action.DISAPPEARED" />
            <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
            <action android:name="android.bluetooth.device.action.ACTION_ACL_DISCONNECT_REQUESTED" />
            <action android:name="android.bluetooth.device.action.BOND_STATE_CHANGED" />
            <action android:name="android.bluetooth.device.action.UUID" />
        </intent-filter>
    </receiver>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

BluetoothSocket 未连接到目标设备 的相关文章

  • 如何在 ADB 连接期间禁用电池充电?

    问题描述 每次我在电脑和手机之间连接 USB 线时 电池都会自动充电 我想使用 ADB 协议 但我不想在 ADB 连接期间为电池充电 是否可以关闭此充电功能 当然 我该怎么做呢 环境 Android 操作系统 4 及更高版本的手机 我只需要
  • 让协程等待之前的调用

    我还没有完全掌握 Kotlin 协程 基本上我希望协程在执行之前等待任何先前的调用完成 下面的代码似乎可以工作 但它正在做我认为它正在做的事情吗 private var saveJob Job null fun save saveJob s
  • 从历史堆栈中删除活动

    我的应用程序在用户第一次运行应用程序时显示注册活动 如下所示 活动启动画面 欢迎来到游戏 注册帐户 ActivitySplashScreenSignUp 很好 填写此信息 ActivityGameMain 游戏主屏幕 因此 当用户单击每个屏
  • 从 arraylist 和 hashmap 中删除重复项

    我有一个数组列表 其中包含付款人的姓名 另一个数组列表包含每次付款的费用 例如 nameArray 尼古拉 劳尔 洛伦佐 劳尔 劳尔 洛伦佐 尼古拉 价格数组 24 12 22 18 5 8 1 我需要将每个人的费用相加 所以数组必须变成
  • 如何访问android库项目中的资源

    我正在构建一个 android 库项目 它内部需要一些静态资源 图像 xml 等 然后我想知道我可以把这些资源放在哪里以及如何访问它们 既然我把资源放到了assets文件夹 我使用 AssetManager 来访问资源 public cla
  • Android:我可以创建一个不是矩形的视图/画布吗?圆形的?

    我有一个圆形视图 悬停在主要内容上方 gt 从屏幕出来的 z 轴方向 当有人点击屏幕时 我希望选择主要内容或悬停在上方的视图 当它覆盖主视图时 到目前为止效果很好 我在透明画布上有一个圆形物品 这意味着您可以看到该圆圈之外的背景的所有内容
  • Android PhoneGap 插件,UI 选项卡栏,调整 WebView 大小

    我正在创建一个美味的 PhoneGap 插件 希望一旦它能被打开 准备好了 插件基本完成了 我只需要一个漂亮的用户界面 相互作用 简而言之 我想创建一个 本机 android 工具栏组件 如果您实现 PhoneGap UIControls
  • onScale 事件后触发奇怪的 onScroll 事件

    我有一个同时使用 SimpleOnScaleGestureListener 和 SimpleOnGestureListener 的应用程序 每当我进行捏缩放时 我都会得到预期的 onScale 但是当我抬起时 我会看到一个奇怪的 onScr
  • 位图内存不足错误

    我对这个错误有疑问 我从 URL 制作网站图标解析器 我这样做是这样的 public class GrabIconsFromWebPage public static String replaceUrl String url StringB
  • 在 Android Lollipop 中从 Uri 中裁剪照片后总是返回 Null?

    我尝试在拍照或挑选照片后从 Uri 中裁剪图像 我的代码是这样的 public static void cropImage Uri uri Activity activity int action code Intent intent ne
  • 使用 R 下载压缩数据文件、提取和导入数据

    EZGraphs 在 Twitter 上写道 很多在线 csv 都被压缩了 有没有办法下载 解压缩存档并使用 R 将数据加载到 data frame Rstats 我今天也尝试这样做 但最终只是手动下载 zip 文件 我尝试过类似的东西 f
  • 像 WhatsApp 一样发送图片

    我做了一个聊天应用程序 我想添加照片 文件共享我的应用程序中的概念与 WhatsApp 相同 我已经使用该应用程序制作了Xmpp Openfire目前我正在使用此功能进行照片共享 但它并不完全可靠 public void sendFile
  • 如何从android中的外部存储中获取所选文件的文件路径?

    我在选择文件的文件路径时遇到问题 我搜索了整个堆栈溢出 但问题没有解决 从设备中选择文件的代码如下所示 Intent intent new Intent Intent ACTION GET CONTENT intent setType in
  • 具有代理设置的 Android 模拟器 - 致命错误:.//android/base/sockets/ 检查失败:isValidFd(fd)。 FD 1404 最大1024

    需要使用代理设置运行模拟器 我在命令提示符中使用以下命令来启动模拟器 emulator avd AVD for 3 7 WVGA Nexus One http proxy http username password IP Port 如果没
  • Android 纹理仅显示纯色

    我正在尝试在四边形上显示单个纹理 我有一个可用的 VertexObject 它可以很好地绘制一个正方形 或任何几何对象 现在我尝试扩展它来处理纹理 但纹理不起作用 我只看到一种纯色的四边形 坐标数据位于 arrayList 中 the ve
  • android textview 有字符限制吗?

    我正在尝试在 android TextView 中输入超过 2000 3000 个字符 它不显示任何内容 任何一份指南是否对 android textview 有字符限制或什么 我在G3中做了一些小测试 我发现 如果activtiy布局中有
  • Glass 语音命令给定列表中最接近的匹配项

    使用 Glass 您可以通过 确定 Glass 菜单启动应用程序 它似乎会选择最接近的匹配项 除非命令相距数英里 并且您可以明显看到命令列表 无论如何 是否可以从应用程序内或从语音提示 在初始应用程序触发后 给出类似的列表并返回最接近的匹配
  • 如何构建自定义摄像机应用程序?

    我正在尝试开发一个自定义摄像机录像机 当我的设备在 Activity 的 beginRecording 中执行 start MediaRecorder 方法时 应用程序崩溃 我不知道出了什么问题 因为我遵循谷歌API指南 http deve
  • 如何在 Android 上将动态 alpha 遮罩应用于文本

    I want to make a dynamic alpha mask with drawable shapes as circles or whatever and apply it to a drawed text on Android
  • 在 Android 手机中通过耳机插孔发送数据

    我目前正在处理一个新项目 我必须通过具有特定电压的耳机插孔发送数据 然后我可以在该电压上工作 所以这里我需要根据我的数据来编程具体电压 我是否可以在android中访问耳机的输出电压 然后创建一个应用程序来控制该电压 这是一篇讨论此问题的

随机推荐