|
| 1 | +package com.mparticle.internal |
| 2 | + |
| 3 | +import android.os.Handler |
| 4 | +import android.os.Looper |
| 5 | +import android.os.Message |
| 6 | +import com.mparticle.internal.listeners.InternalListenerManager.Companion.isEnabled |
| 7 | +import com.mparticle.internal.listeners.InternalListenerManager.Companion.listener |
| 8 | +import java.util.concurrent.ConcurrentHashMap |
| 9 | +import java.util.concurrent.CountDownLatch |
| 10 | + |
| 11 | +open class BaseHandler : Handler { |
| 12 | + @Volatile |
| 13 | + var isDisabled: Boolean = false |
| 14 | + private set |
| 15 | + |
| 16 | + @Volatile |
| 17 | + private var handling = false |
| 18 | + private val messageQueue: ConcurrentHashMap<Message, Boolean> = ConcurrentHashMap<Message, Boolean>() |
| 19 | + |
| 20 | + fun getMessageQueue(): Set<Message> { |
| 21 | + return messageQueue.keys |
| 22 | + } |
| 23 | + |
| 24 | + constructor() |
| 25 | + |
| 26 | + constructor(looper: Looper) : super(looper) |
| 27 | + |
| 28 | + fun disable(disable: Boolean) { |
| 29 | + this.isDisabled = disable |
| 30 | + removeCallbacksAndMessages(null) |
| 31 | + while (handling) { |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + fun await(latch: CountDownLatch?) { |
| 36 | + this.sendMessage(obtainMessage(-1, latch)) |
| 37 | + } |
| 38 | + |
| 39 | + override fun handleMessage(msg: Message) { |
| 40 | + if (isDisabled) { |
| 41 | + Logger.error("Handler: " + javaClass.name + " is destroyed! Message: \"" + msg.toString() + "\" will not be processed") |
| 42 | + return |
| 43 | + } |
| 44 | + handling = true |
| 45 | + try { |
| 46 | + messageQueue.remove(msg) |
| 47 | + if (msg.what == -1 && msg.obj is CountDownLatch) { |
| 48 | + (msg.obj as CountDownLatch).countDown() |
| 49 | + } else { |
| 50 | + if (isEnabled) { |
| 51 | + listener.onThreadMessage(javaClass.name, msg, true) |
| 52 | + } |
| 53 | + try { |
| 54 | + handleMessageImpl(msg) |
| 55 | + } catch (error: OutOfMemoryError) { |
| 56 | + Logger.error("Out of memory") |
| 57 | + } |
| 58 | + } |
| 59 | + } finally { |
| 60 | + handling = false |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + override fun sendMessageAtTime(msg: Message, uptimeMillis: Long): Boolean { |
| 65 | + if (isDisabled) { |
| 66 | + return false |
| 67 | + } |
| 68 | + if (isEnabled) { |
| 69 | + listener.onThreadMessage(javaClass.name, msg, false) |
| 70 | + } |
| 71 | + |
| 72 | + messageQueue[msg] = true |
| 73 | + |
| 74 | + return super.sendMessageAtTime(msg, uptimeMillis) |
| 75 | + } |
| 76 | + |
| 77 | + fun removeMessage(what: Int) { |
| 78 | + val messages: Set<Message> = messageQueue.keys |
| 79 | + for (message in messages) { |
| 80 | + if (message.what == what) { |
| 81 | + messageQueue.remove(message) |
| 82 | + } |
| 83 | + } |
| 84 | + super.removeMessages(what) |
| 85 | + } |
| 86 | + |
| 87 | + // Override this in order to handle messages |
| 88 | + open fun handleMessageImpl(msg: Message?) { |
| 89 | + } |
| 90 | +} |
0 commit comments