线程变为空,即使它被初始化了?

时间:2017-07-09 18:55:41

标签: java android bluetooth

我在使用蓝牙聊天服务示例中的某些代码时出现问题。我能够连接到HC-05蓝牙设备,但是当我从另一个活动调用write方法时,我得到一个nullpointerexception,因为mConnectThread是Null。这是活动A:

public void btn1(View view){

    byte[] n= {0x00000001};
    ChatService mChatservice = new ChatService();
    mChatservice.write(n);
}

这是我的Chatservice类中的write方法:

public  void write (byte[] out){    
    if(mConnectThread == null){
        Log.i(TAG, "mConnectedThread is null");
    }
    else {
        Log.i(TAG, "mConnectedThread is not null");
    }
}

我初始化了mConnectedThread,类似于在蓝牙样本中完成的,在connectthread中工作正常。

private class ConnectThread extends Thread {
    // Use a temporary object that is later assigned to mmSocket
    // because mmSocket is final.
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;


    public ConnectThread(BluetoothDevice device) {
        mmDevice = device;
        BluetoothSocket tmp = null;
        try
        {
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
        } catch (IOException e)
        {
            Log.i(TAG, "Socket's create() method failed");
        }

        mmSocket = tmp;
    }


    public void run() {
        try {
            // Connect to the remote device through the socket. This call blocks
            // until it succeeds or throws an exception.
            mmSocket.connect();

        } catch (IOException connectException) {

            // Unable to connect; close the socket and return.
            try {
                mmSocket.close();
            } catch (IOException closeException) {

            }
            return;
        }
            mConnectedThread = new ConnectedThread(mmSocket);
            mConnectedThread.start();

    }
    // Closes the client socket and causes the thread to finish.
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {

        }
    }
}

当我在write方法中调用mConnectedThread时,它是Null。为什么mConnectedThread即使在Connectthread中初始化也会变为空?

0 个答案:

没有答案
相关问题