@@ -8,17 +8,11 @@ import android.content.Context
88import android.content.Intent
99import android.content.IntentFilter
1010import android.util.Log
11- import java.io.FileOutputStream
12- import android.os.ParcelFileDescriptor
1311import kotlin.collections.HashMap
1412
1513class EventReceiver : BroadcastReceiver () {
1614 private val tag = this ::class .java.simpleName
1715 private val eventMap = HashMap <String , Int >()
18- private var eventOut: FileOutputStream ? = null
19- private var eventPfd: ParcelFileDescriptor ? = null
20- private var eventFd: Int = - 1
21- private val eventLock = Any ()
2216
2317 init {
2418 eventMap[Intent .ACTION_POWER_CONNECTED ] = 100
@@ -40,38 +34,18 @@ class EventReceiver : BroadcastReceiver() {
4034 }
4135
4236 private fun write (code : Int? ) {
43- code?.let {
44- try {
45- val out = ensureSocketOpen() ? : return
46- // 32-bit event code, low byte first
47- val msg = ByteArray (4 )
48- msg[0 ] = (it and 0xFF ).toByte()
49- msg[1 ] = ((it ushr 8 ) and 0xFF ).toByte()
50- msg[2 ] = ((it ushr 16 ) and 0xFF ).toByte()
51- msg[3 ] = ((it ushr 24 ) and 0xFF ).toByte()
52- out .write(msg)
53- out .flush()
54- } catch (e: Exception ) {
55- Log .e(tag, " Cannot write to event socket: \n $e " )
56- }
57- } ? : Log .e(tag, " Invalid code: must be a 32-bit integer" )
58- }
37+ if (code == null ) {
38+ Log .e(tag, " Invalid code: must be a 32-bit integer" )
39+ return
40+ }
5941
60- private fun ensureSocketOpen (): FileOutputStream ? {
61- synchronized(eventLock) {
62- if (eventOut != null ) {
63- return eventOut
64- }
65- if (eventFd < 0 ) {
66- eventFd = nativeGetEventSocketFd()
67- if (eventFd < 0 ) {
68- Log .e(tag, " Event socket fd is not available" )
69- return null
70- }
42+ try {
43+ val rc = nativeSendEvent(code)
44+ if (rc != 0 ) {
45+ Log .e(tag, " nativeSendEvent failed with code $rc " )
7146 }
72- eventPfd = ParcelFileDescriptor .adoptFd(eventFd)
73- eventOut = FileOutputStream (eventPfd!! .fileDescriptor)
74- return eventOut
47+ } catch (e: Throwable ) {
48+ Log .e(tag, " Cannot send event to native socket: $e " )
7549 }
7650 }
7751
@@ -86,6 +60,6 @@ class EventReceiver : BroadcastReceiver() {
8660
8761 companion object {
8862 @JvmStatic
89- private external fun nativeGetEventSocketFd ( ): Int
63+ private external fun nativeSendEvent ( code : Int ): Int
9064 }
9165}
0 commit comments