连接的线程返回空对象

时间:2018-07-19 07:08:26

标签: android

我在片段上使用了蓝牙连接服务,但ConnectedThread返回空。虽然我正在打电话给bluetoothconnection服务,但没有用。我没有找到任何解决方案。我该如何解决? 片段:

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());

BluetoothConnectionService写入功能的一部分

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 个答案:

答案 0 :(得分:2)

您的代码不是我可以直接修复的。但我这里是一个示例,说明如何建立连接,然后将数据发送到此连接的设备:

col4

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

 variable1='name'    

 variable2='col1,col2,col3,col4'