Android read/write serial port (friendlyarm) Import com. friendlyarm. androidsdk. hardwarecontroler;
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. OS. Handler;
Import Android. OS. logoff;
Import Android. OS. message;
Public class mapguider_activity extends activity {
Private int serial_fd = 0;
Private byte [] serial_revbuf = new byte [1, 100];
Private byte [] serial_sendbuf = "fsjajd". getbytes ();
@ Override
Protected void oncreate (bundle savedinstancestate ){
// Todo auto-generated method stub
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. mapguider );
Serial_fd = hardwarecontroler. openserialport ("/dev/g410_serial1", 115200, 8, 1 );
If (serial_fd! =-1)
{
System. Out. println ("the serial port is successfully opened ");
Hardwarecontroler. Write (serial_fd, serial_sendbuf );
Lac_handler.post (reviceposdatathread );
}
Else
{
System. Out. println ("the specified serial port does not exist or has been enabled in other processes ");
}
}
@ Override
Protected void ondestroy (){
// Todo auto-generated method stub
Hardwarecontroler. Close (serial_fd );
System. Out. println ("Disable serial port ");
Lac_handler.removecallbacks (reviceposdatathread );
Super. ondestroy ();
}
Handler lac_handler = new handler (){
@ Override
Public void handlemessage (Message MSG ){
// Todo auto-generated method stub
Super. handlemessage (MSG );
}
};
Runnable reviceposdatathread = new runnable ()
{
Int err = 0;
String S;
Public void run (){
// Todo auto-generated method stub
While (true)
{
// Logoff. Prepare ();
Err = hardwarecontroler. Select (serial_fd, 1, 0 );
If (ERR = 1) // data readable
{
Hardwarecontroler. Read (serial_fd, serial_revbuf, 10 );
S = new string (serial_revbuf );
System. Out. println ("received serial data" + S );
}
Else if (ERR = 0) // No data readable
{
System. Out. println ("Serial Port Data not received ");
}
Else // Error
{
System. Out. println ("failed to receive serial port data ");
}
Try {
Thread. Sleep (2 );
} Catch (interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
}
};
}