Android:蓝牙套接字关闭

时间:2017-06-16 10:30:26

标签: android exception bluetooth connection android-bluetooth

我一直在使用蓝牙设备并正在为它创建一个应用程序。

我应该可以通过发送代码0或1打开或关闭此设备LED。

我有一些错误赶上来帮助我解决这个问题,并且在盯着它多年后看不出问题出在哪里。

我正确找到设备,并检查了设备返回的MAC地址,这一切都很好。从我可以看到的日志我也似乎正确打开所有套接字。

在将字节数据发送到设备的过程的最后阶段发生错误。任何人都可以发现我无法做到的事情吗?也许连接没有成功?

澄清触发的异常是在sendData()方法中。

如果你发现错误,我会永远爱你。

错误消息: Fatal Error, In onResume() and an exception occurred during write:socket closed.

那么套接字在数据发送之前关闭了什么,或者从未成功打开过什么?

无论如何,很多代码入站:

public class ScanFragment extends Fragment {

    ArrayList<DeviceItem> scannedList;
    Button scanningButton;
    TextView scanningText;
    ListView scannedListView;
    BluetoothAdapter mBluetoothAdapter;
    DeviceItem item;
    DeviceCustomAdapter adapter;
    BluetoothDevice device;
    String TAG = "TEST";

    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private OutputStream outStream = null;

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_ENABLE_BT = 3;

    // Well known SPP UUID
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // Insert your bluetooth devices MAC address
    private static String address = "00:00:00:00:00:00";

    public ScanFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_scan, container, false);
    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            Log.i("found", "hello" + "");
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                item = new DeviceItem();
                item.setDeviceName(device.getName());
                item.setDeviceCode(device.getAddress());
                item.setDeviceId(MY_UUID);
                scannedList.add(item);
                Log.i("BT", device.getName() + "\n" + device.getAddress());
            } else {
                Log.i("BT", "none" + "");
            }
            adapter = new DeviceCustomAdapter(
                    getActivity().getApplicationContext(), scannedList);
            scannedListView.setAdapter(adapter);
        }
    };

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        super.onActivityCreated(savedInstanceState);

        scannedList = new ArrayList<>();
        scanningButton = (Button) getActivity().findViewById(R.id.scanningButton);
        scanningText = (TextView) getActivity().findViewById(R.id.scanningText);
        scannedListView = (ListView) getActivity().findViewById(R.id.scannedListView);
        scannedListView.setVisibility(View.VISIBLE);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (Build.VERSION.SDK_INT >= 15 &&
                ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }

        if (mBluetoothAdapter == null) {
            scanningText.setText("Your device does not support Bluetooth, Sorry!");
        } else if (!mBluetoothAdapter.isEnabled()) {
            scanningText.setText("You need to enable bluetooth to use this app..");
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        scanningButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scanningText.setText("Scanning...");
                mBluetoothAdapter.startDiscovery();
                mBluetoothAdapter.isDiscovering();

                scanningText.setText("Click on a device to connect");
            }
        });

        // Register for broadcasts when a device is discovered.
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        getActivity().registerReceiver(mReceiver, filter);

        scannedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                item = scannedList.get(position);
                String name= scannedList.get(position).getDeviceName();
                Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Connecting to " + item.getDeviceCode() + "" + name, Toast.LENGTH_SHORT);
                toast.show();
                scanningText.setText(item.getDeviceCode());
                mBluetoothAdapter.cancelDiscovery();
                address = item.getDeviceCode();
                // Create the result Intent and include the MAC address
                connectDevice(address, true);
                ledOff(view);
            }
        });
    }

    public void ledOn(View v){
        sendData("1");
        Toast msg = Toast.makeText(getActivity().getApplicationContext(), "LED is ON", Toast.LENGTH_SHORT);
        msg.show();
    }

    public void ledOff(View v){
        sendData("0");
        Toast msg = Toast.makeText(getActivity().getApplicationContext(), "LED is OFF", Toast.LENGTH_SHORT);
        msg.show();
    }


    public void connectToDevice(String adr) {
        super.onResume();

        //enable buttons once connection established.
//        btnOn.setEnabled(true);
//        btnOff.setEnabled(true);

        // Set up a pointer to the remote node using it's address.
        btAdapter = mBluetoothAdapter;
        BluetoothDevice device = btAdapter.getRemoteDevice(adr);

        // Two things are needed to make a connection:
        //   A MAC address, which we got above.
        //   A Service ID or UUID.  In this case we are using the
        //     UUID for SPP.
        try {
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

        // Discovery is resource intensive.  Make sure it isn't going on
        // when you attempt to connect and pass your message.
        btAdapter.cancelDiscovery();

        // Establish the connection.  This will block until it connects.
        try {
            btSocket.connect();
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
            }
        }

        // Create a data stream so we can talk to server.
        try {
            outStream = btSocket.getOutputStream();
        } catch (IOException e) {
            errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
        }
    }

    private void errorExit(String title, String message){
        Toast msg = Toast.makeText(getActivity().getApplicationContext(), title + " - " + message, Toast.LENGTH_SHORT);
        msg.show();
//        finish();
    }

    private void sendData(String message) {
        byte[] msgBuffer = message.getBytes();
        try {
            outStream.write(msgBuffer);
        } catch (IOException e) {
            String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
            errorExit("Fatal Error", msg);
        }
    }

    private void connectDevice(String address, boolean secure) {
        // Get the device MAC address
        connectToDevice(address);
        // Get the BluetoothDevice object
        BluetoothDevice device = btAdapter.getRemoteDevice(address);
    }

}

1 个答案:

答案 0 :(得分:0)

套接字一直关闭。我在这个帖子的帮助下修复了它。

Link