Android BroadcastReceiver

一、简介

广播接收者是Android四大组件之一,每个应用程序都可以对自己感兴趣的广播进行注册,这样该程序就能接收到自己所关心的广播内容,广播的注册有两种,分别是静态注册(配置文件注册)和动态注册(代码手动注册),广播的分类有两种,分别是标准广播(异步执行)和有序广播(同步执行)。

二、创建广播

新建一个类,继承BroadcastReceiver

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class BootCompleteReceiver extends BroadcastReceiver {
    public BootCompleteReceiver() {
         
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"接收到广播",Toast.LENGTH_SHORT).show();
    }
}

三、注册广播

静态注册(Manifest.xml)

        
            //设置接收广播的优先级
            
                
                
            
        

动态注册(与Activity生命周期同步)

    private IntentFilter mFilter;
    private BootCompleteReceiver mReceiver;

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

        mFilter = new IntentFilter();
        mFilter.addAction("com.BootCompleteReceiver");
        mReceiver = new BootCompleteReceiver();
        registerReceiver(mReceiver,mFilter);
    }

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

四、发送广播

发送标准广播(无序广播、异步广播)

        //Action与广播注册的Action要一致
        Intent intent = new Intent("com.BootCompleteReceiver");
        sendBroadcast(intent);

发送有序广播(同步广播,有接收的先后顺序),优先级越高,越先接收到广播

        //Action与广播注册的Action要一致
        Intent intent = new Intent("com.BootCompleteReceiver");
        sendOrderedBroadcast(intent,null);

拦截广播(用于有序广播),在接收广播的方法里实现拦截

        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();
        }
    }

五、本地广播(推荐使用,必须动态注册)

普通的广播属于系统全局广播,即发出的广播可以被其他应用程序接收,也可以接收其他应用程序发出的广播,这样既会造成安全性的问题,也会使自身应用的性能降低,而本地广播可以解决上述问题

    private IntentFilter mFilter;
    private BootCompleteReceiver mReceiver;
    private LocalBroadcastManager mManager;

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

        mFilter = new IntentFilter();
        mFilter.addAction("com.BootCompleteReceiver");
        mReceiver = new BootCompleteReceiver();
        mManager = LocalBroadcastManager.getInstance(this);
        mManager.registerReceiver(mReceiver,mFilter);
    }

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

你可能感兴趣的:(Android BroadcastReceiver)