android 注册静态广播接收器VS注册动态广播接收器

来源:互联网 发布:python 测试框架 编辑:程序博客网 时间:2024/05/21 12:12

关于android的广播接收器,有静态和动态之分。动态广播接收器是不需要在AndroidManifest.xml文件中声明的,而静态的broadcastReceiver是需要在AndroidManifest.xml文件中声明的。

通常情况下我们习惯于用动态的broadcastReceiver ,不用的时候就销毁,比较节省系统资源。但是需要接收Intent.ACTION_BOOT_COMPLETED 这样开启完成的广播的时候,必须用静态的广播。

一,静态广播的用法:

1,在AndroidManifest.xml文件中声明:

        <receiver
            android:name="com.system.isprite.core.iSpriteBCR"
            android:enabled="true" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

2,创建一个接收器继承BroadcastReceiver类

public class iSpriteBCR extends BroadcastReceiver {
    private static final String TAG = "leichi";

    @Override
    public void onReceive(Context context, Intent intent) {
        String mAction = intent.getAction();
        if (Intent.ACTION_BOOT_COMPLETED.equals(mAction)) {
            Toast.makeText(context, "ACTION_BOOT_COMPLETED", Toast.LENGTH_LONG).show();
           // to do what you want .............
        }
    }

二,动态广播用法:

1,new 一个实例;

private BroadcastReceiver mBCR = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String mAction = intent.getAction();
            if (CONST.ACTION_REGISTER_SUCESS.equals(mAction)) {
                //do what you want .....
            } else if (CONST.ACTION_ACTIVATE_SUCESS.equals(mAction)) {
                // do  what you want ....
            }
        }
    };

2,注册:
    private void registerBCReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(CONST.ACTION_REGISTER_SUCESS);//添加过滤条件
        filter.addAction(CONST.ACTION_ACTIVATE_SUCESS);//添加过滤条件
        filter.setPriority(Integer.MAX_VALUE);
        // filter.addDataScheme("package");//如果接收包的安装和卸载,则必须有这个。
        registerReceiver(mBCR, filter);
    }
3,销毁:
    private void unregisterBCReceiver() {
        unregisterReceiver(mBCR);
    }

一般在onCreate方法中调用注册,在onDestroy方法中调用销毁,根据需要自己决定吧。











原创粉丝点击