android广播机制BroadCastReceiver解析

1.BroadCastReceiver之场景还原

        近些日子,项目中涉及到了许多广播,有监听自定义广播,还有监听系统级广播;广播机制在android中十分重要,今天趁有时间,给大家解析一下BroadCastReceiver的用法。

2.BroadCastReceiver的具体用法

     一般要使用广播,第一必须自定义一个广播类,并且继承BroadCastReceiver,并且还需要重写onReceive()方法;当广播接受到信号后,立即回调onReceive()重载方法;一般分为两种形式的注册:

①静态注册(Mainfest中注册)

1.1自定义BroadCastReceiver

public class AnotherReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"被点击了",Toast.LENGTH_SHORT).show();
    }
}

1.2在manifest中注册

<receiver android:name=".AnotherReceiver">
    <intent-filter>
        <action android:name="android.com.zhangxing"/>
    </intent-filter>
</receiver>

1.3在代码中发送“相同频率“的广播

public void sendBroad(View v){
    Intent intent = new Intent();
    intent.setAction("android.com.zhangxing");
    sendBroadcast(intent);
}

ok,这样静态注册就完成了!

②动态注册(一般监听系统级的广播:网络,电量等)

2.1自定义BroadCastReceiver

public class NetworkChangeReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isAvailable()){
            Toast.makeText(context,"网络可用",Toast.LENGTH_SHORT).show();

        }else{
            Toast.makeText(context,"网络不可用",Toast.LENGTH_SHORT).show();
        }


    }
}

2.2设置监听的action

//动态注册广播 IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

2.3注册广播

receiver = new NetworkChangeReceiver();
registerReceiver(receiver,intentFilter);

2.4最后,别忘了在onDestory()解绑广播

@Override
protected void onDestroy() {
    super.onDestroy();
 unregisterReceiver(receiver);
}

这个在动态注册广播时,千万别忘了,否则会出现OOM.

好了,又该告一段落了;在实战中学习,在实战中精进,我是张星,欢迎您的关注!

    原文作者:eagle-zhang
    原文地址: https://blog.csdn.net/zhangxing52077/article/details/54143373
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞