zoukankan      html  css  js  c++  java
  • 本地广播 localBroadcastManager Android

    使用localBroadcastManager发出的广播只能在本应用程序的内部进行传递。类似于iOS的NSNotificationCenter

    App应用内广播可理解为一种局部广播,广播的发送者和接收者都同属于一个App。

    相比于全局广播(普通广播),App应用内广播优势体现在:安全性高 & 效率高

    步骤:

    1.注册广播(onResume方法内

    2.发送广播

    3.收到广播

    4.销毁广播(onPause方法内

    package com.fengbang.localbroadcasttest;

    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.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;
    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;


    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    localBroadcastManager = LocalBroadcastManager.getInstance(this);

    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    Intent intent = new Intent("com.fengbang.localbroadcasttest.LOCAL_BROADCAST");
    localBroadcastManager.sendBroadcast(intent);//发送广播
    }
    });

    }

    @Override
    protected void onResume() {
    super.onResume();

    intentFilter = new IntentFilter();
    intentFilter.addAction("com.fengbang.localbroadcasttest.LOCAL_BROADCAST");
    localReceiver = new LocalReceiver();
    localBroadcastManager.registerReceiver(localReceiver,intentFilter);//注册广播
    }

    @Override
    protected void onPause() {
    super.onPause();

    localBroadcastManager.unregisterReceiver(localReceiver);//销毁广播
    }

    class LocalReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "onReceive: 收到广播");
    }
    }
    }
  • 相关阅读:
    Rabbit官方文档翻译之Publish Subscribe(三)
    Maven项目导入本地Jar包
    位运算实现整数的加减乘数运算
    SpringMVC通过工具类获取Request域
    终止线程的2种方法。标记法和中断
    Spring 下默认事务机制中@Transactional 无效的原因
    java泛型 泛型的内部原理:类型擦除以及类型擦除带来的问题
    java.lang.Object.clone()分析
    我的Node.js学习历程
    setTimeout的妙用2——防止循环超时
  • 原文地址:https://www.cnblogs.com/huangzs/p/9077991.html
Copyright © 2011-2022 走看看