#Region Service Attributes
#StartAtBoot: False
#End Region
' ignore warnings that Subs ReadPipe and WritePipe are not used
#IgnoreWarnings: 12
Sub Process_Globals
Private NamedPipe1 As NamedPipe
Private PipeReader As Runnable
Private PipeWriter As Runnable
End Sub
Sub Service_Create
NamedPipe1.Initialize
PipeReader.Initialize("PipeReader", Me, "ReadPipe", Array As Object())
PipeWriter.Initialize("PipeWriter", Me, "WritePipe", Array As Object())
PipeReader.Start ' ReadPipe will be executed in a background thread
PipeWriter.Start ' WritePipe will be executed in a background thread
End Sub
Sub Service_Start (StartingIntent As Intent)
End Sub
Sub Service_Destroy
Service.StopAutomaticForeground 'Call this when the background task completes (if there is one)
PipeReader.StopFlag=True
PipeWriter.StopFlag=True
PipeWriter.Interrupt
NamedPipe1.Close
End Sub
Sub PipeReader_Complete(Result As Object)
Log("PipeReader_Complete")
End Sub
Sub PipeWriter_Complete(Result As Object)
Log("PipeWriter_Complete")
End Sub
Sub ReadPipe()
Log("ReadPipeStarted")
Dim AutoCloseInputStream1 As AutoCloseInputStream=NamedPipe1.InputStream
' a 32 byte buffer to read the pipe into
Dim Bytes(32) As Byte
Do Until PipeReader.StopFlag Or PipeReader.IsInterrupted
' this method will block until the pipe contains bytes that it can read
' it's essential that you don't try to use this method on the UI thread
' your app would probably force close if you did so
Dim BytesRead As Int=AutoCloseInputStream1.Read2(Bytes, 0, Bytes.Length)
Log(BytesToString(Bytes, 0, BytesRead, "UTF8"))
Loop
AutoCloseInputStream1.Close
Log("ReadPipeStopped")
End Sub
Sub WritePipe()
Log("WritePipeStarted")
Dim AutoCloseOutputStream1 As AutoCloseOutputStream=NamedPipe1.OutputStream
Dim Thread1 As Thread
Dim Bytes() As Byte="Hello from Sub WritePipe".GetBytes("UTF8")
Do Until PipeWriter.StopFlag Or PipeWriter.IsInterrupted
AutoCloseOutputStream1.Write2(Bytes, 0, Bytes.Length)
Try
Thread1.Sleep(500)
Catch
' an InterruptedException will occur if PipeWriter.Interrupt is executed while Sleep is executing
Log(LastException)
PipeWriter.StopFlag=True
End Try
Loop
AutoCloseOutputStream1.Close
Log("WritePipeStopped")
End Sub