1

我知道已经有很多关于我上面提供的标题的问题,但我发现没有一个是令人满意的。我还浏览了Android 蓝牙及其示例蓝牙聊天应用程序。但我想要的是创建一个演示 android 应用程序,它从任何其他支持蓝牙的设备(无论是 android 还是非 android)接收数据(字符串消息或文件)以上任何链接或代码片段都会有很大帮助。问候应用编码..

编辑 以下是我从 DeviceListPickerActivity.java 成功选择设备后尝试获取数据的一段代码:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {

                // Get the device MAC address
                String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);

                // Get the BLuetoothDevice object
                device = mBluetoothAdapter.getRemoteDevice(address);
                String deviceFriendlyName = device.getName().toString();

                Toast.makeText(getApplicationContext(), "Device " + deviceFriendlyName +" Selected", Toast.LENGTH_SHORT).show();
                try{
                    BluetoothSocket btSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"));
                    btSocket.connect();
                    String strReceivedBytesFromDevice;
                    InputStream input = btSocket.getInputStream();
                    DataInputStream dinput = new DataInputStream(input);
                    StringBuffer inputLine = new StringBuffer();
                    while((strReceivedBytesFromDevice = dinput.readLine()) != null){
                        inputLine.append(strReceivedBytesFromDevice);
                        System.out.println("Data Received from BT device:" + strReceivedBytesFromDevice);
                    }
                    dinput.close();
                    }catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                            "Error in establishing connection with device.",
                            Toast.LENGTH_SHORT).show();
                    }
                // Attempt to connect to the device
                if(mChatService != null){
                    mChatService.connect(device);
//                  getBluetoothMessageString();
                }else {
                    // Initialize the BluetoothChatService to perform bluetooth connections
                    mChatService = new BluetoothService(this, mHandler);
//                    getBluetoothMessageString();
                }
            }
            /*else{
                Toast.makeText(getApplicationContext(), "Failed to connect to device", Toast.LENGTH_LONG).show();
            }*/
            break;
4

0 回答 0