BroadcastReceiver与LocalBroadcastManager应用及区别

  android中有两种广播机制,一种是BroadcastReceiver,另一种是LocalBroadcastManager。现在来简单介绍一下两者。


一、应用场景

   1、BroadcastReceiver用于应用之间的传递消息;

   2、而LocalBroadcastManager用于应用内部传递消息,比broadcastReceiver更加高效。

二、安全

   1、BroadcastReceiver使用的Content API,所以本质上它是跨应用的,所以在使用它时必须要考虑到不要被别的应用滥用;

   2、LocalBroadcastManager不需要考虑安全问题,因为它只在应用内部有效。

三、例子

BroadcastReceiver示例代码:

public class BroadcastReceiverTest  extends AppCompatActivity
{
    static int flag=1;
    static final String NAME="name";
    static final String ACTION="com.zfeng.broadcastreceiver";

    private Button startBtn;

    private MyBroadcastReceiver myBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.broadcast_layout);

        myBroadcastReceiver=new MyBroadcastReceiver();

        startBtn=(Button)findViewById(R.id.broadcast_start);

        addListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(myBroadcastReceiver,new IntentFilter(ACTION));
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(myBroadcastReceiver);
    }

    private void addListener()
    {
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(ACTION);
                intent.putExtra(NAME,"Andy");
                sendBroadcast(intent);
            }
        });
    }

    public static class MyBroadcastReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            String name=intent.getStringExtra(NAME);
            Toast.makeText(context,name+":"+flag,Toast.LENGTH_SHORT).show();
            ++flag;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

AndroidManifest.xml

            
        


 
  

LocalBroadcastManager例子:

public class MainActivity extends AppCompatActivity
{
    static final String COMMAND="command";
    static final String ACTION_STARTED="com.zfeng.broadcastreceiver.STARTED";
    static final String ACTION_UPDATE="com.zfeng.broadcastreceiver.UPDATE";
    static final String ACTION_STOPPED="com.zfeng.broadcastreceiver.STOPPED";

    static final int FLAG_STARTED=1001;
    static final int FLAG_UPDATE=1002;
    static final int FLAG_STOPPED=1003;

    private LocalBroadcastManager mLocalBroadcastManager;
    private BroadcastReceiver mBroadcastReceiver;

    private Button startBtn,updateBtn,startActivityBtn;
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        mLocalBroadcastManager=LocalBroadcastManager.getInstance(this);
        startBtn=(Button)findViewById(R.id.content_start);
        updateBtn=(Button)findViewById(R.id.content_update);
        startActivityBtn=(Button)findViewById(R.id.content_activity);
        tv=(TextView)findViewById(R.id.content_tv);

        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(ACTION_STARTED);
        intentFilter.addAction(ACTION_UPDATE);
        intentFilter.addAction(ACTION_STOPPED);
        mBroadcastReceiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent.getAction().equals(ACTION_STARTED))
                {
                    tv.setText("STARTED");
                }else if(intent.getAction().equals(ACTION_UPDATE))
                {
                    tv.setText("UPDATE");
                }else if(intent.getAction().equals(ACTION_STOPPED))
                {
                    tv.setText("STOPPED");
                }
            }
        };
        mLocalBroadcastManager.registerReceiver(mBroadcastReceiver,intentFilter);

        addListener();
    }
    private void addListener()
    {
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,LocalService.class);
                intent.putExtra(COMMAND,FLAG_STARTED);
                startService(intent);

            }
        });
        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,LocalService.class);
                intent.putExtra(COMMAND,FLAG_UPDATE);
                startService(intent);
            }
        });
        startActivityBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,BroadcastReceiverTest.class);
                startActivity(intent);
            }
        });
    }

    public static class LocalService extends Service
    {
        LocalBroadcastManager localBroadcastManager;

        private Handler handler=new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                if(msg.what==FLAG_STARTED)
                {
                    localBroadcastManager.sendBroadcast(new Intent(ACTION_STARTED));
                }else if(msg.what==FLAG_UPDATE)
                {
                    localBroadcastManager.sendBroadcast(new Intent(ACTION_UPDATE));
                }
            }
        };
        @Override
        public void onCreate() {
            super.onCreate();
            localBroadcastManager=LocalBroadcastManager.getInstance(this);
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId)
        {
            int command=intent.getIntExtra(COMMAND,FLAG_STARTED);
            handler.sendEmptyMessageDelayed(command,3000);
            return ServiceCompat.START_STICKY;
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            localBroadcastManager.sendBroadcast(new Intent(ACTION_STOPPED));
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
    }
}






你可能感兴趣的:(android内部和网络通讯)