gpt4 book ai didi

java - 如何从服务中的线程以特定时间间隔运行方法...?

转载 作者:行者123 更新时间:2023-11-30 03:44:32 24 4
gpt4 key购买 nike

我正在处理蓝牙聊天示例,我正在尝试从连接蓝牙设备时处于 Activity 状态的线程以特定时间间隔发送“虚拟”数据。每隔一段时间启动/停止另一个服务以调用原始服务中的方法是个好主意吗?我将如何实现?

private class ConnectedThread extends Thread {

static private final String TAG = "PhoneInfoConnectedThread";
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket, String socketType) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;

// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
Log.d(TAG, "In and out streams created");
} catch (IOException e) {
Log.e(TAG, "temp sockets not created " + e.getMessage());
}

mmInStream = tmpIn;
mmOutStream = tmpOut;
}

// this is where we will spend out time when connected to the accessory.
public void run() {
// Keep listening to the InputStream while connected
while (true) {
// do whatever
}
}

// Write to the connected OutStream.
public void write(byte[] buffer) {
if (mmOutStream == null) {
Log.e(TAG, "ConnectedThread.write: no OutStream");
return;
}
try {
Log.d(TAG, "ConnectedThread.write: writing " + buffer.length
+ " bytes");
mmOutStream.write(buffer);

// Share the sent message back to the UI Activity
// mHandler.obtainMessage(PhoneInfoActivity.MESSAGE_WRITE, -1,
// -1, buffer).sendToTarget();
Log.d(TAG, "ConnectedThread.write: sent to calling activity");
} catch (IOException e) {
Log.e(TAG, "Exception during write" + e.getMessage());
}
}

public void cancel() {
try {
Log.d(TAG, "ConnectedThread.cancel: closing socket");
if (mmSocket != null)
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "ConnectedThread.cancel: socket.close() failed"
+ e.getMessage());
}
}
}

最佳答案

希望这个例子对你有帮助。

 MyTimerTask myTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTask, 2000, 1000);


class MyTimerTask extends TimerTask {
public void run() {
Log.v("TAG","Message");
}
}

更多信息see this

关于java - 如何从服务中的线程以特定时间间隔运行方法...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15214655/

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