[英]Set timer on a method of class implementing runnable in main UI thread
I'm an absolute beginner in android. 我是android的绝对初学者。 Currently, I'm trying to make an app that sends output data to arduino via bluetooth.
目前,我正在尝试制作一个通过蓝牙将输出数据发送到arduino的应用程序。 For that purpose, I have created a class as follows.
为此,我创建了一个如下的类。
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");
}
}
}
In my OnCreate() method, I'm doing as follows. 在我的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;
The problem I'm currently having is with the right procedure for invoking method write(). 我目前遇到的问题是调用方法write()的正确过程。 What would be the right way to go on with that?
正确的做法是什么?
Look at this class that connects to an arduino. 看一下连接到arduino的此类。 I wrote this a while ago.
我前一段时间写的。 The problem is that if you do not know android starting here is very difficult.
问题是,如果您不知道android从这里开始是非常困难的。 Look at the BluetoothHandlerClass
看一下BluetoothHandlerClass
https://github.com/rush2sk8/BluetoothHandler https://github.com/rush2sk8/BluetoothHandler
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.