android基础学习——service及BroadcastReceiver

(1)demo功能描述:
在Activity中绑定service,在service中接收到绑定的回调后,发送广播,并在Activity中接收Service发送的广播。
(2)实现
关键类及关键方法清单
service—onBind()
ServiceConnection
bindService()
unBindService()
sendBroadcast()
IntentFilter—addAction()
registerReceiver()
unRegisterReceiver()
实现过程—注册广播接受者及绑定Service

    val myReceiver : BroadcastReceiver  = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when(intent?.action){
                "a"->{
                    Log.d("receiver","receive a")
                }
                "b"->{
                    Log.d("receiver","receive b")
                }
                "c"->{
                    Log.d("receiver","receive c")
                }
                "d"->{
                    Log.d("receiver","receive d")
                }
            }
        }

    }
val myConnection = object : ServiceConnection{
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        }
    }
       val filter = IntentFilter()
        filter.addAction("a")
        filter.addAction("b")
        registerReceiver(myReceiver,filter)
        val intent = Intent(this,BroadcastService::class.java)
        intent.putExtra("type","apageActivity")
        bindService(intent,myConnection, Context.BIND_AUTO_CREATE)

实现过程—Service发送广播

override fun onBind(intent: Intent?): IBinder? {
        Log.d(Tag,"onBind")
        val type = intent?.getStringExtra("type")?:"temp"
        val intent = Intent("a")
        intent.putExtra("type",type)
        sendBroadcast(intent)
        val intent1 = Intent("b")
        intent1.putExtra("type",type)
        sendBroadcast(intent1)
        val intent2 = Intent("c")
        intent2.putExtra("type",type)
        sendBroadcast(intent2)
        val intent3 = Intent("d")
        intent3.putExtra("type",type)
        sendBroadcast(intent3)
        return object : Binder(){}
    }

注意事项:
在Activity被销毁之前要将服务解绑将广播接受者取消register
unbindService(myConnection)
unregisterReceiver(myReceiver)

另,service的onBind方法执行的时机参考https://blog.csdn.net/u013553529/article/details/54754491

上一篇:Android四大组件:BroadcastReceiver史上最全面解析


下一篇:移动安全学习笔记——组件安全之BroadcastReceiver组件漏洞挖掘