zoukankan      html  css  js  c++  java
  • Android学习总结——本地广播机制

       为了简单解决广播的安全性问题,Android引入了一套本地广播机制,使用这个机制发出的广播只能在程序的内部进行传递,只能接受来自本应用程序发出的广播。否则当我们发送一些携带关键数据的广播可能被截获,一些恶意程序也可能向我们的广播接收器中发送各种垃圾广播。

    用法如下:(主要就是使用LocalBroadcastManager来对广播进行管理,并提供注册广播和发送广播的方法)。

    package com.example.xch.localbroadcast;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.support.v4.content.LocalBroadcastManager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    public class MainActivity extends AppCompatActivity {
        private IntentFilter intentFilter;
        private Button sendBroadcast;
        private LocalReceiver localReceiver;
        private LocalBroadcastManager localBroadcastManager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            localBroadcastManager=LocalBroadcastManager.getInstance(this);//通过getInstance()得到LocalBroadcastManager的实例
    
            sendBroadcast=(Button) findViewById(R.id.sendBroadcast);
            sendBroadcast.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //发送本地广播
                    Intent intent=new Intent("com.example.LOCAL_BROADCAST");
                    localBroadcastManager.sendBroadcast(intent);
                }
            });
            //注册本地广播监听器
            intentFilter=new IntentFilter();
            intentFilter.addAction("com.example.LOCAL_BROADCAST");
            localReceiver=new LocalReceiver();
            localBroadcastManager.registerReceiver(localReceiver,intentFilter);
        }
        class LocalReceiver extends BroadcastReceiver{
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context,"接受到本地广播",Toast.LENGTH_SHORT).show();
            }
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            localBroadcastManager.unregisterReceiver(localReceiver);//关闭广播
        }
    }
  • 相关阅读:
    C语言博客作业06--结构体&文件
    C语言博客05--指针
    C语言博客作业04--数组
    LeetCode错题集
    C博客作业--指针
    深入浅出强化学习:原理入门(待更新)
    Detectron2环境配置+Ubantu+CUDA10.1+pytorch1.7.0
    论文记载:A Survey on Traffic Signal Control Methods
    论文记载:FRAP:Learning Phase Competition for Traffic Signal Control
    周博磊老师强化学习纲领笔记第三课:无模型的价值函数估计和控制
  • 原文地址:https://www.cnblogs.com/xch-yang/p/6181556.html
Copyright © 2011-2022 走看看