java在主UI线程中实现runnable的类方法上设置计时器
我是安卓的绝对初学者。目前,我正在尝试制作一款通过蓝牙向arduino发送输出数据的应用程序。为此,我创建了一个类,如下所示
private class SendReceiveBytes implements Runnable {
private BluetoothSocket btSocket;
private InputStream inputStream;
private OutputStream outputStream;
String TAG = "SendReceiveBytes";
public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try {
inputStream = btSocket.getInputStream();
outputStream = btSocket.getOutputStream();
}
catch (IOException streamError) {
Log.e(TAG, "Error when getting input or output Stream");
}
}
@Override
public void run() {
// buffer store for the stream.
byte[] buffer = new byte[1024];
// bytes returned from the stream.
int bytes;
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = inputStream.read(buffer);
// Send the obtained bytes to the UI activity
socketHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}
catch (IOException e) {
Log.e(TAG, "Error reading from inputStream");
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String outputData) {
try {
outputStream.write(outputData.getBytes(Charset.forName("UTF-8")));
}
catch (IOException e) {
Log.e(TAG, "Error when writing to outputStream");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
btSocket.close();
}
catch (IOException e) {
Log.e(TAG, "Error when closing the btSocket");
}
}
}
在我的OnCreate()方法中,我将执行以下操作
final SendReceiveBytes sendBytes = new SendReceiveBytes(bluetoothSocket);
final Handler moveHandler = new Handler();
View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
public boolean onLongClick(View view) {
switch (view.getId()) {
case R.id.driveFwd:
moveHandler.postDelayed(sendBytes.write("MOVE_FORWARD"), 250);
sendBytes.write("MOVE_FORWARD");
break;
我目前遇到的问题是调用方法write()的正确过程。什么是正确的方式继续下去
共 (0) 个答案