使用扩展类

时间:2014-04-26 22:52:46

标签: java android class extends

我是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);

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

1 个答案:

答案 0 :(得分:2)

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

 Thread writeThread = new ConnectThread(targetdevice);

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

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