LocalBroadcastManager局部广播管理员

来源:互联网 发布:知否剧组照片 编辑:程序博客网 时间:2024/05/16 10:35

                                                            LocalBroadcastManager布局广播管理员:顾名思义用于在项目中发送广播的管理员

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="com.example.broadcastrecieverdemo2.MainActivity">    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="send"        android:text="发送广播" />    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></LinearLayout>

java代码:

public class MainActivity extends AppCompatActivity {    //获取局部广播管理员    LocalBroadcastManager lbm;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //通过单利模式获取        lbm = LocalBroadcastManager.getInstance(this);        //注册广播(注意使用LocalBroadcastManager对象)        IntentFilter filter = new IntentFilter("send");        lbm.registerReceiver(receiver, filter);    }    @Override    protected void onDestroy() {        //注销广播(注意在super方法前面执行)        //注意使用局部广播对象注销        lbm.unregisterReceiver(receiver);        receiver = null;        super.onDestroy();    }    //发送局部广播    public void send(View view) {        //发送一个无序广播(注意发送个广播活动名称必须和注册活动名称一样)        Intent intent = new Intent("send");        intent.putExtra("text", "局部广播");        lbm.sendBroadcast(intent);    }    //动态创建广播接受者    BroadcastReceiver receiver = new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) {            //接受广播消息            String text = intent.getStringExtra("text");            Log.e("TAG", "onReceive:---------- " + text);        }    };}

//总结:局部广播管理员主要针对是本APP直接的通讯

优点:安全 !安全!安全! 重要的事情说三遍,通过localbroadcastmanager发广播外部APP接受不到。

0 0
原创粉丝点击