1

我正在尝试使用createInsecureRfcommSocketToServiceRecord无法连接设备的方法连接两部手机而不配对它,它会抛出 IOException。 System.err: java.io.IOException: socket closed

你可以看到我的代码。在应用程序中有新的扫描蓝牙设备列表,当我单击该特定项目时,它会转到第二个活动并与该设备连接。

代码 :

此 OnItemClick 是 Searched new devices 列表的列表器。

  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        bdDevice = arrayListBluetoothDevices.get(position);
        Intent intents = new Intent(Main_Activity.this, SecondActivity.class);
        intents.putExtra("deviceAddress", bdDevice.getAddress());
        startActivity(intents);
       }

SecondActivity.class:

@Override
    public void onResume() {
        super.onResume();
        Intent intent = getIntent();
        address = intent.getStringExtra("deviceAddress");
    BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
    try {

   //I am creating   insecureRFcomm  because of  no pairing dialog required.

        socket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
        socket.getRemoteDevice().getAddress();

    } catch (Exception e) {
        e.printStackTrace();
    }
    bluetoothAdapter.cancelDiscovery();
    Log.d(TAG, "...Connecting to Remote...");
    try {

        //Connection establish between BT-Device  and phone.
        socket.connect();


        counter = 0;
        Log.d(TAG, "...Connection established and data link opened...");
    } catch (IOException e) {
        try {
            //Connection close.
            socket.close();
            if (inStream!=null){
                inStream.close();
            }
        } catch (Exception e2) {
            e.printStackTrace();
            e2.printStackTrace();
        }
        finally {
            final AlertDialog alertDialog = new AlertDialog.Builder(SBLActivity.this).create();
            alertDialog.setMessage("Device is Non SBL.");
            alertDialog.setTitle("Device  Connection");
            alertDialog.setCancelable(false);
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    alertDialog.dismiss();
                    finish();
                }
            });
            alertDialog.show();
        }
    }
    }

我遇到错误,Socket.connect(); 它会去捕获块。如何解决这个问题,或者以任何其他方式在没有配对对话框 或配对设备 或使用配对设备但没有配对对话框的情况下连接蓝牙插座

谢谢你。

4

0 回答 0