Android进阶之路 - BroadcaseReceiver(自定义广播、有序广播、无序广播、广播拦截、动态注册、静态注册)的详细使用方式

众所周知BroadcaseReceiver为Android中的四大组件之一,又名为广播、喇叭,这篇我为大家带来的就是BroadcaseReceiver的详细使用方式,说到使用其中又有些许不同,下面为大家进行讲解

广播分为俩种俩式:

1.有序广播(可拦截)
2.无序广播(不可拦截)

1.动态注册(代码注册)
2.静态注册(清单注册)

使用方式与注意点:

1.使用BroadcaseReceiver首先要创建一个类继承BroadcaseReceiver,重写onReceiver方法(接收到广播的操作在这里执行)
2.在所依赖的Activity等寄生体之中发送广播(分有序和无序想,下文都有介绍)
3.作为Android下的四大组件之一,必不可少的自然是清单注册
4.文中我并没有监听系统的一些广播,如开机,上网之类,均是为了方便自己定义的,有兴趣的可以举一反三进行广播处理

1.MainActivity主代码与各个接收者代码
2.MainActivity的Xml代码
3.清单文件(主要用于观察注册与优先级的处理)

MainActivity的代码:

package com.xiaomage.localbroadcasereceiverdemo

import android.app.Activity
import android.content.Intent
import android.content.IntentFilter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private var activity: Activity?=null
    private val dynamicBroadcastReceiver=DynamicBroadcastReceiver()
    private val myLocalBroadcastReceiver=MyLocalBroadcastReceiver()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        activity=this
        bt_send_self_br.setOnClickListener{
            //发送自定义广播
            intent= Intent("MySelfBroadcastReceiver")
            sendBroadcast(intent)
        }
        bt_dynamic_br.setOnClickListener{
            //动态广播
            //和清单文件格式对应,这里是添加广播的过滤
            val dynamicIntentFilter=IntentFilter()
            //添加动作,设置广播
            dynamicIntentFilter.addAction("DynamicBroadcastReceiver")
            //动态注册
            registerReceiver(dynamicBroadcastReceiver,dynamicIntentFilter)

            //--------------------------------------------------
            //发送广播测试
            intent=Intent("DynamicBroadcaseReceiver")
            sendBroadcast(intent)

        }
        bt_static_br.setOnClickListener{
            //默认即使无序广播
            intent=Intent("StaticBroadcastReceiver")
            sendBroadcast(intent)

            //有序广播:我们可以对其做处理,如拦截之类,
            sendOrderedBroadcast(intent,null)
        }

        bt_local_br.setOnClickListener{
            //获取本地管理者
            val localBroadcastManager=
                    LocalBroadcastManager.getInstance(activity!!)
            //动态注册
            val intentFilter=IntentFilter()
            intentFilter.addAction("MyLocalBroadcastReceiver")
            localBroadcastManager.registerReceiver(
                    myLocalBroadcastReceiver,
                    intentFilter
            )

            //发送广播
            intent=Intent("MyLocalBroadcastReceiver")
            localBroadcastManager.sendBroadcast(intent)

        }

        bt_priority_br.setOnClickListener{
            //优先级测试
            //优先级的测试-这里我们选择静态注册,
            // 也就是直接在清单注册-设置priority
            // 经过测试很明显拦截广播是建立在有序广播的基础上面,
            // 同时拦截广播后只显示静态注册的Toask,而不是优先级的Toask
            intent=Intent("StaticBroadcastReceiver")
            intent.action = "PriorityBroadcastReceiver"
            sendOrderedBroadcast(intent,null)

        }

    }

    override fun onDestroy() {
        super.onDestroy()
        //注销广播-因为不是本地广播的话,会有数据隐患的,
        // 好比你已经关了APP但是还是一直发广播或者接收广播,
        // 系统会自己操作,所以极为不安全,
        unregisterReceiver(dynamicBroadcastReceiver)
        unregisterReceiver(myLocalBroadcastReceiver)
    }
}

以下Recevice方法均只是一个简单的Toask

MySelfBroadcastReceiver的代码(自定义广播):

package com.xiaomage.localbroadcasereceiverdemo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log


class MySelfBroadcastReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.e("自定义广播触发","MySelfBroadcaseReceiver收到信息了")
    }
}

DynamicBroadcaseReceiver的代码(动态注册):

package com.xiaomage.localbroadcasereceiverdemo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

class DynamicBroadcastReceiver :BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.e("自定义广播触发","DynamicBroadcaseReceiver收到信息了")}
}

MyLocalBroadcastReceiver的代码(本地广播):

package com.xiaomage.localbroadcasereceiverdemo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

class MyLocalBroadcastReceiver:BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.e("自定义广播触发","MyLocalBroadcastReceiver收到信息了")
    }
}package com.xiaomage.localbroadcasereceiverdemo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

class MyLocalBroadcastReceiver:BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.e("自定义广播触发","MyLocalBroadcastReceiver收到信息了")
    }
}

StaticBroadcaseReceiver的代码(静态注册):

package com.xiaomage.localbroadcasereceiverdemo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

class StaticBroadcastReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.e("自定义广播触发","StaticBroadcastReceiver收到信息了")
    }
}

PriorityBroadcastReceiver(优先级的广播接收者,做了拦截处理,静态广播被拦截,只能接收到优先级的广播)的代码:

package com.xiaomage.localbroadcasereceiverdemo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

class PriorityBroadcastReceiver:BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.e("自定义广播触发","PriorityBroadcastReceiver收到信息了")
        abortBroadcast()
    }
}

MainActivity的Xml代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    <Button
        android:id="@+id/bt_send_self_br"
        android:text="发送自定义广播"
        android:layout_width="match_parent"
        android:layout_height="40dp" />
    <Button
        android:id="@+id/bt_dynamic_br"
        android:text="动态广播"
        android:layout_width="match_parent"
        android:layout_height="40dp" />
    <Button
        android:id="@+id/bt_static_br"
        android:text="静态广播的有序与无序"
        android:layout_width="match_parent"
        android:layout_height="40dp" />
    <Button
        android:id="@+id/bt_local_br"
        android:text="LocalBroadcaseReceiver"
        android:layout_width="match_parent"
        android:layout_height="40dp" />

    <Button
        android:id="@+id/bt_priority_br"
        android:text="优先级"
        android:layout_width="match_parent"
        android:layout_height="40dp" />

</LinearLayout>

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xiaomage.localbroadcasereceiverdemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!---自定义广播 :静态注册 -->
        <receiver android:name=".MySelfBroadcastReceiver">
            <intent-filter>
                <action android:name="MySelfBroadcaseReceiver" />
            </intent-filter>
        </receiver>
        <!---自定义广播 :静态注册 -->
        <receiver android:name=".StaticBroadcastReceiver">
            <intent-filter>
                <action android:name="StaticBroadcastReceiver"/>
            </intent-filter>
        </receiver>
        <receiver android:name=".PriorityBroadcastReceiver">
            <intent-filter android:priority="100">
                <action android:name="PriorityBroadcastReceiver"/>
                <action android:name="StaticBroadcastReceiver"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

results matching ""

    No results matching ""