gpt4 book ai didi

java - 使用扩展类

转载 作者:行者123 更新时间:2023-12-02 05:53:34 25 4
gpt4 key购买 nike

我是 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) { }
}
}

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

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 的扩展类,我就可以使用它下面的方法。难道不是这样吗?这样做的正确方法是什么?谢谢!

最佳答案

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

 Thread writeThread = new ConnectThread(targetdevice);

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

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

关于java - 使用扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23317360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com