【发布时间】:2012-04-24 06:22:27
【问题描述】:
我正在尝试在 Android 应用程序中获取当前时间和日期并通过蓝牙传输。我尝试使用时间和日历来获得小时、分钟、秒、月、日和年减去 2000。然后我尝试将每个值转换为一个字节并将它们放入一个字节数组中。但是,当我尝试通过蓝牙发送值时,它们在另一端出现错误。我要拍摄的格式是标题 (0xFF),后跟时、分、秒、月、日、年。
public class Bluetooth extends Activity{
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private String bt_address;//00:18:E4:OC:67:FF
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth);
Button connect = (Button)findViewById(R.id.Btn_Connect);
try{
/*code removed, reads bt_address from a file or creates a file if no file exists yet*/
} catch(IOException ioe){
ioe.getStackTrace();
}
connect.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try{
/*code removed, saves bt_address to a file*/
}
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
/*code removed, prompts user to turn on Bluetooth if not already on*/
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(bt_address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {}
mBluetoothAdapter.cancelDiscovery();
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {}
}
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {}
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {}
Time time = new Time();
byte[] msgbuf = new byte[7];
msgbuf[0] = (byte)0xFF;
msgbuf[1] = (byte)time.hour;
msgbuf[2] = (byte)time.minute;
msgbuf[3] = (byte)time.second;
msgbuf[4] = (byte)(time.month + 1);
msgbuf[5] = (byte)time.monthDay;
msgbuf[6] = (byte)(time.year - 2000);
outStream.write(msgbuf);
}
)};
此代码设置为使用其蓝牙地址连接到设备,并在单击按钮时向其发送时间戳。它将连接到设备并在此过程中发送一长串数字,但我开始认为它在发送时间戳之前断开连接。
【问题讨论】:
-
“出来错了”非常模糊 - 你得到了什么?请注意,如果是
OutputStream,您应该只能调用outStream.write(msgbuf)。 -
当我在另一端收到数据并将其显示为整数时,我得到一些我认为来自应用程序上的连接命令的乱码,最后 7 个数字不是时间值。其他已被覆盖,但最后 5 个是 21、58、52、67、225。这些应该是分、秒、月、日和年减去 2000。当值滚动传递时,我也从未见过标题.第二次运行给了我 233、52、67、225 作为最后 4 个数字。最后 3 个两次都相同会让我相信那些是它认为是月、日和年的值。
-
你还没有向我们展示接收值的代码......哦,你吞下任何抛出的异常也无济于事。不要那样做。
-
接收代码在 Arduino 板上运行。这只是一个简单的循环,它从蓝牙设备读取串行线,并使用库函数将其作为整数打印在 OLED 屏幕上。事情的结局不应该是问题。一旦我正确发送数据,它将使用我发送的值来启动时钟并保存时间戳。我相信我的应用程序上的蓝牙设置代码可能有问题。我会更新问题。
-
“事情的结局不应该是问题”通常是“哦,原来是问题”的前奏。从分离出两个问题开始:1)你能得到正确的时间值吗? 2) 你能正确地通过网络获取数据吗?
标签: java android time bluetooth bytearray