我正在尝试在 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);
}
)};
此代码设置为使用其蓝牙地址连接到设备,并在单击按钮时向其发送时间戳。它将连接到设备并在此过程中发送一长串数字,但我开始认为它在发送时间戳之前断开连接。