Fork me on GitHub

Wednesday, February 13, 2013

Enriched methods of TelephonyManager

TelephonyManager has several listeners that can be invoked for a certain phone state changes.

val callStateListener = new PhoneStateListener() {
  override def onCallStateChanged(state: Int, incomingNumber:String) {
    if(state == TelephonyManager.CALL_STATE_RINGING) doSomething()
  }
}

override def onCreate(b: Bundle) {
  super.onCreate(b)
  // ...
  telephonyManager.listen(callStateListener, 
                          PhoneStateListener.LISTEN_CALL_STATE)
}

override def onDestroy() {
  telephonyManager.listen(callStateListener, 
                          PhoneStateListener.LISTEN_NONE)
  // ...
  super.onDestroy()
}

The boilerplates that keeps track the listener object obscures the main idea from your code. Using the trait Destroyable, listening phone states becomes much simpler:
onCallStateChanged((state, number) => {
  if(state == TelephonyManager.CALL_STATE_RINGING) doSomething()
})

This enhancement is available on the current snapshot, and will be released in version 1.1.

No comments:

Post a Comment