zoukankan      html  css  js  c++  java
  • BroadcastReceiver的两种注册方式和使用

    1.静态注册,在minifest文件中

    <receiver android:name=".BroadcastReceiverDemo" >
                <intent-filter>
                    <action android:name="com.simware.BroadcastReceiverDemo" >
                    </action>
                </intent-filter>
    </receiver>

    注册完之后即可以发送广播,使用Context.sendBroadcast()、Context.sendOrderedBroadcast()或者Context.sendStickyBroadcast()来实现

    接受广播使用代码:
    public class BroadcastReceiverDemo extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    String msg = intent.getStringExtra("message");
    Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }
    }

    发送广播:
    Intent mIntent = new Intent("com.simware.BroadcastReceiverDemo");
    mIntent.putExtra("message", "hahahahaha");
    sendBroadcast(mIntent);

    2.动态注册,在代码中注册解注册

    registerReceiver(BroadcastReceiver receiver, IntentFilter filter)

    unregisterReceiver(BroadcastReceiver receiver) 

    在Activity中代码注册广播建议在:onResume()中注册(也可在onCreate里面注册);

    在Activity中代码注销广播建议在:onPause()中注销(也可在onDestory里面注销)

    如果一个BroadcastReceiver用于更新UI(User Interface),那么通常会使用这种方法进行注册,在Activity启动的时候进行注册,在Activity不可见后取消注册。不过应用内的更建议使用LocalBroadcastReceiver

    区别:

            在AndroidManifest中进行注册后,不管该应用程序是否处于活动状态,都会进行监听,比如某个程序是监听 内存 的使用情况的,当在手机上安装好后,不管该应用程序是处于什么状态,都会执行改监听方法中的内容。

            在代码中进行注册后,当应用程序关闭后,就不再进行监听。如果是在Activity中进行的注册和解注册,则生命周期是跟随该Activity的。我们知道,应用程序是否省电,决定了该应用程序的受欢迎程度,所以,对于那些没必要在程序关闭后仍然进行监听的Receiver,在代码中进行注册,无疑是一个明智的选择。

  • 相关阅读:
    python3 获取n天后的日期时间
    python3 获取n年前日期
    RequestsDependencyWarning: urllib3 (1.25.2) or chardet (3.0.4) doesn't match a supported version!
    html5 富文本编辑器
    python3 md5 加密
    python3 获取当前日期以及7天后的日期(2016-03-20 11:45:39 形式)
    python3 生成随机手机号
    python 列表 字典转json
    (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1076)')))
    【Python】时间与时间戳
  • 原文地址:https://www.cnblogs.com/genggeng/p/6760513.html
Copyright © 2011-2022 走看看