代码之家  ›  专栏  ›  技术社区  ›  NetworkStudent

连接的线程返回空对象

  •  -1
  • NetworkStudent  · 技术社区  · 7 年前

    我正在我的片段上使用蓝牙连接服务,但ConnectedThread返回空虽然我打电话给蓝牙连接服务,但不起作用我找不到解决办法我该怎么解决? 碎片:

    if(convertView==null) {
                convertView = inflater.inflate(R.layout.fragment_ota__update, container, false);
    
                text=(TextView)convertView.findViewById(R.id.text);
                InputStream  is =this.getResources().openRawResource(R.raw.blink);
                BufferedReader reader = new BufferedReader( new InputStreamReader(is));
                send =(Button) convertView.findViewById(R.id.send);
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
                getActivity().registerReceiver(mBroadcastReceiver4, filter);
    
                mBluetoothConnection = new BluetoothConnectionService(getActivity().getApplicationContext());
                mBluetoothConnection.startClient(mBTDevice,MY_UUID_INSECURE);
                if(is!=null){
    
                    try {
                        while ((data = reader.readLine()) != null) {
                            char [] ch =data.toCharArray();
    
                            for (char c: ch) {
                                int i= (int) c;
                                sbuffer.append(Integer.toHexString(i).toUpperCase());
                                text.setText(sbuffer);
    
                            }
    
                        }
    
                        is.close();
    
                    }
                     catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                send.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(sbuffer!=null) {
    
                            byte[] bytes = sbuffer.toString().getBytes(Charset.defaultCharset());
                            mBluetoothConnection.write(bytes);
    
                        }
                    }
                });
            }
    

    在我用以下代码调用的片段中:

      mBluetoothConnection = new BluetoothConnectionService(getActivity().getApplicationContext());
    

    写入函数的蓝牙连接服务部分

    public void write(byte[] out) {
            if(mConnectedThread !=null ){
                // Create temporary object
    
    
                // Synchronize a copy of the ConnectedThread
                Log.d(TAG, "write: Write Called.");
                //perform the write
                mConnectedThread.write(out);
            }
            else{
                Log.d(TAG, "mConnectedThread empty ");
    
    
            }
        }
    

    这是我的蓝牙连接课程: https://paste.ubuntu.com/p/gcPrydZnDw/

    1 回复  |  直到 7 年前
        1
  •  2
  •   CU_dev    7 年前

    你的代码不是我能直接修复的。但我这里有一个例子,说明了我如何建立连接,然后将数据发送到这个连接的设备:

    public class BluetoothConnection extends Thread {
    
    public static  BluetoothSocket mSocket;
    
    private InputStream mInStream;
    private OutputStream mOutStream;
    private byte[] buffer;
    private BluetoothAdapter mAdapter;
    private Handler mHandler;
    private String output;
    private String sendString;
    private String tempTester = "";
    
    static UUID MY_UUID;
    
    /**
     * Constructor initializes all necessary variables.
     * @param device the device that the constructor will connect to
     */
    public BluetoothConnection(BluetoothDevice device){
        MY_UUID = device.getUuids()[0].getUuid();
        mAdapter = null;
        mSocket = createMSocket(device);
        mSocket = connectSocket(mSocket);
    
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try{
            tmpIn = mSocket.getInputStream();
            tmpOut = mSocket.getOutputStream();
        }catch (IOException e){
            e.printStackTrace();
        }
        mInStream = tmpIn;
        mOutStream = tmpOut;
        buffer = new byte[25];
    }// end constructor
    
    /**
     * Creates the main socket that will be used in connection with device.
     * @param device a BluetoothDevice
     * @return a BluetoothSocket mSocket.
     */
    private BluetoothSocket createMSocket(BluetoothDevice device) {
        BluetoothSocket tmp = null;
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tmp;
    }// end createMSocket
    
    /**
     * Socket makes connection to device then returns back the updated socket.
     * @param socket BluetoothSocket
     * @return an updated version of the parameter socket.
     */
    private BluetoothSocket connectSocket(BluetoothSocket socket){
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            socket.connect();
            System.out.println("$$$$$$$$$$$$$$$$****** socket connected ******$$$$$$$$$$$$$$$$");
        } catch (IOException e) {
            //connection to device failed so close the socket
            try {
                socket.close();
                System.out.println("$$$$$$$$$$$$$$$$****** socket closed ******$$$$$$$$$$$$$$$$");
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        return socket;
    }// end connectSocket
    
    /**
     * Sends message back to device in the form of a byte[].
     * @param buffer byte[]
     */
    public void write(byte[] buffer){
        try{
            mOutStream.write(buffer);
        }catch(IOException e) {
            e.printStackTrace();
        }
    }// end write
    
    
    /**
     * Closes the connection with the device
     */
    public void cancel(){
        try{
            mSocket.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }// end cancel
    
    }
    

    然后,在活动的主线程上,可以调用以下代码(只要知道要连接的设备):

    BluetoothConnection connection = new BluetoothConnection(connectedDevice);
    
    public void sendData(){
    
       String s = editText.getText().toString();
    
       byte[] b = s.getBytes();
    
       connection.write(b);
    
       //System.out.println("Bytes Sent");
    }// end sendData