美文网首页
组件之BroadcastReceiver详解

组件之BroadcastReceiver详解

作者: kjy_112233 | 来源:发表于2017-08-04 13:58 被阅读0次

    一、BroadcastReceiver解析

    (1)广播注册使用

    public class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String name = intent.getStringExtra("name");
        }
    }
    

    (2)动态注册广播

    public class MainActivity extends AppCompatActivity {
    
        private MyBroadcastReceiver myBroadcastReceiver;
        private IntentFilter intentFilter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            myBroadcastReceiver = new MyBroadcastReceiver();
            intentFilter = new IntentFilter();
            intentFilter.addAction("android.intent.action.MY_BROADCAST_RECEIVER");
            registerReceiver(myBroadcastReceiver, intentFilter);//注册广播
        }
    
        //发送广播
        private void sendOut(){
            Intent intent = new Intent("android.intent.action.MY_BROADCAST_RECEIVER");
            intent.putExtra("name","name");
            sendBroadcast(intent);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            unregisterReceiver(myBroadcastReceiver);//注解广播
        }
    }
    

    (3)在配置文件中静态注册广播

    <receiver android:name=".类名">
        <intent-filter>
            <action android:name="android.intent.action.MY_BROADCAST_RECEIVER"/>
        </intent-filter>
    </receiver>
    

    特点:动态注册广播接收器特点是当用来注册的Activity关掉后,广播也就失效了。静态注册无需担忧广播接收器是否被关闭,只要设备是开启状态,广播接收器也是打开着的

    (4)其他广播

    • 有序广播:将sendBroadcast改成sendOrderedBroadcast。priority接收广播的优先级
    • 系统广播:
      屏幕被关闭:Intent.ACTION_SCREEN_OFF
      屏幕被打开:Intent.ACTION_SCREEN_ON
      系统启动完成:Intent.ACTION_BOOT_COMPLETED
      网络变化:android.net.conn.CONNECTIVITY_CHANGE
      充电时或电量发生变化:Intent.ACTION_BATTERY_CHANGED
    • 本地广播:只有动态注册的广播才能使用,主要使用了一个LocalBroadcastManager来对广播进行管理,并提供了相应的发送广播和注册广播接收器的方法
    LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
    //注册广播
    localBroadcastManager.registerReceiver(myBroadcastReceiver,intentFilter);
    //发送广播
    localBroadcastManager.sendBroadcast(intent);
    //反注册广播
    localBroadcastManager.unregisterReceiver(myBroadcastReceiver);
    
    • 粘性广播:.sendStickyBroadcast发送粘性广播,广播会一直滞留,当有匹配该广播的接收器被注册后,该接收器就会收到此条广播。sendStickyBroadcast只保留最后一条广播,并且一直保留。如果只想处理一遍该广播,可通过removeStickyBroadcast来实现。
      BroadcastReceiver源码解析

    相关文章

      网友评论

          本文标题:组件之BroadcastReceiver详解

          本文链接:https://www.haomeiwen.com/subject/ggdvlxtx.html