1+ /*
2+ * Copyright 2018. nekocode ([email protected] ) 3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+ package cn.nekocode.gank
18+
19+ import android.app.Application
20+ import android.content.BroadcastReceiver
21+ import android.content.Context
22+ import android.content.Intent
23+ import android.content.IntentFilter
24+ import android.support.v4.content.LocalBroadcastManager
25+ import cn.nekocode.gank.backend.GankIoService
26+ import cn.nekocode.gank.broadcast.BroadcastCallAdapter
27+ import cn.nekocode.gank.broadcast.BroadcastConfig
28+ import cn.nekocode.gank.broadcast.BroadcastRouter
29+ import cn.nekocode.meepo.Meepo
30+ import cn.nekocode.meepo.config.UriConfig
31+ import com.google.gson.Gson
32+ import okhttp3.OkHttpClient
33+
34+ /* *
35+ * @author nekocode ([email protected] ) 36+ */
37+ class GankApplication : Application () {
38+ lateinit var activityRouter: ActivityRouter
39+ lateinit var broadcastRouter: BroadcastRouter
40+ lateinit var gankIoService: GankIoService
41+
42+ override fun onCreate () {
43+ super .onCreate()
44+
45+ activityRouter = Meepo .Builder ()
46+ .config(UriConfig ().scheme(BuildConfig .SCHEME ).host(BuildConfig .APPLICATION_ID ))
47+ .build().create(ActivityRouter ::class .java)
48+ broadcastRouter = Meepo .Builder ()
49+ .config(BroadcastConfig ()).adapter(BroadcastCallAdapter ())
50+ .build().create(BroadcastRouter ::class .java)
51+ gankIoService = GankIoService (OkHttpClient (), Gson ())
52+ }
53+ }
54+
55+ fun Context.activityRouter () = (this .applicationContext as GankApplication ).activityRouter
56+ fun Context.broadcastRouter () = (this .applicationContext as GankApplication ).broadcastRouter
57+ fun Context.gankIoService () = (this .applicationContext as GankApplication ).gankIoService
58+
59+ fun Context.registerLocalReceiver (
60+ receiver : (Context ? , Intent ? ) -> Unit , intentFilter : IntentFilter ) {
61+
62+ LocalBroadcastManager .getInstance(this )
63+ .registerReceiver(object : BroadcastReceiver () {
64+ override fun onReceive (context : Context ? , intent : Intent ? ) {
65+ receiver.invoke(context, intent)
66+ }
67+ }, intentFilter)
68+ }
69+ fun Context.registerLocalReceiver (receiver : (Context ? , Intent ? ) -> Unit , vararg actions : String ) {
70+ val intentFilter = IntentFilter ()
71+ actions.forEach {
72+ intentFilter.addAction(it)
73+ }
74+ registerLocalReceiver(receiver, intentFilter)
75+ }
0 commit comments