我是Java /面向对象语言的新手,想在语法上获得一些帮助。

我在ConnectThread.java中有一个定义为的类

public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


public ConnectThread(BluetoothDevice device) {
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    BluetoothSocket tmp = null;
    mmDevice = device;

    // Get a BluetoothSocket to connect with the given BluetoothDevice
    try {
        // MY_UUID is the app's UUID string, also used by the server code
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        tmp = device.createRfcommSocketToServiceRecord(uuid);
    } catch (IOException e) { }
    mmSocket = tmp;
}



public void run() {
    // Cancel discovery because it will slow down the connection
    mBluetoothAdapter.cancelDiscovery();

    try {
        // Connect the device through the socket. This will block
        // until it succeeds or throws an exception
        mmSocket.connect();
    } catch (IOException connectException) {
        // Unable to connect; close the socket and get out
        try {
            mmSocket.close();
        } catch (IOException closeException) { }
        return;
    }

    // Do work to manage the connection (in a separate thread)
    //manageConnectedSocket(mmSocket);
}



/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
    try {
        mmSocket.close();
    } catch (IOException e) { }
}
}


在这里,我尝试通过在connect方法中编写以下代码来创建线程并连接该线程:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice targetdevice;
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0)
{
// Loop through paired devices
    for (BluetoothDevice device : pairedDevices)
    {
         if (device.getName().equals("HC-06"))
            targetdevice = device;
    }
}
Thread writeThread = new Thread();
writeThread.ConnectThread(targetdevice);


我在最后一行收到错误,提示“对于类型Thread未定义方法ConnectThread(BluetoothDevice)”
我以为因为ConnectThread是Thread的扩展类,所以我可以使用它下面的方法。不是这样吗?这样做的正确方法是什么?
谢谢!

最佳答案

将最后两个字符串更改为:

 Thread writeThread = new ConnectThread(targetdevice);


当您需要启动ConnectThread时,请使用start()方法:

 writeThread.start(); //If you need start run() method of ConnectThread.

08-16 18:47