Skip to content

Commit

Permalink
Tweak on registering of localbroadcast receiver
Browse files Browse the repository at this point in the history
  • Loading branch information
nekocode committed May 31, 2019
1 parent 23ef3fa commit 0232f7c
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 11 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,19 @@ The template project imports the [Meepo](https://github.com/nekocode/Meepo) libr
// Navigate to a new activity
activityRouter.gotoXxxActivity(this)

// Broadcast something
// Broadcast action
broadcastRouter.tellSomeSth(this)

// Register broadcast receiver
registerLocalReceiver({ _, intent ->
registerLocalReceiver(BroadcastRouter.Action1, BroadcastRouter.Action2) { _, intent ->
val action = (intent ?: return@registerLocalReceiver).action
?: return@registerLocalReceiver
when (action) {
BroadcastRouter.Action1 -> {
// Do sth
}
}
}, BroadcastRouter.Action1, BroadcastRouter.Action2)
}
```

Sending a network request in this project is also simple:
Expand Down
10 changes: 5 additions & 5 deletions app/src/main/java/cn/nekocode/gank/GankApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ val Context.broadcastRouter get() = (this.applicationContext as GankApplication)
val Context.gankIoService get() = (this.applicationContext as GankApplication).gankIoService

fun Context.registerLocalReceiver(
receiver: BroadcastReceiver.(Context?, Intent?) -> Unit,
intentFilter: IntentFilter
intentFilter: IntentFilter,
receiver: BroadcastReceiver.(Context?, Intent?) -> Unit
) {
LocalBroadcastManager.getInstance(this)
.registerReceiver(object : BroadcastReceiver() {
Expand All @@ -69,12 +69,12 @@ fun Context.registerLocalReceiver(
}

fun Context.registerLocalReceiver(
receiver: BroadcastReceiver.(Context?, Intent?) -> Unit,
vararg actions: String
vararg actions: String,
receiver: BroadcastReceiver.(Context?, Intent?) -> Unit
) {
val intentFilter = IntentFilter()
actions.forEach {
intentFilter.addAction(it)
}
registerLocalReceiver(receiver, intentFilter)
registerLocalReceiver(intentFilter, receiver)
}
5 changes: 2 additions & 3 deletions app/src/main/java/cn/nekocode/gank/ui/home/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class MainActivity : BaseActivity() {
}

// Register local broadcast receiver
registerLocalReceiver({ _, intent ->
registerLocalReceiver(BroadcastRouter.FETCH_SUC) { _, intent ->
val action = (intent ?: return@registerLocalReceiver).action
?: return@registerLocalReceiver
when (action) {
Expand All @@ -50,8 +50,7 @@ class MainActivity : BaseActivity() {
fetchBtn.isEnabled = false
}
}

}, BroadcastRouter.FETCH_SUC)
}
}

override fun onSaveInstanceState(outState: Bundle) {
Expand Down

0 comments on commit 0232f7c

Please sign in to comment.