码迷,mamicode.com
首页 > 移动开发 > 详细

Android BroadcastReceiver

时间:2016-08-23 13:05:15      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <!--<intent-filter android:priority="11">-->
            <intent-filter >
                <action android:name="com.grandkai.learnbroadcastreceiver.intent.action.MyReceiver" />
            </intent-filter>

        </receiver>

        <receiver
            android:name=".MyReceiver2"
            android:enabled="true"
            android:exported="true">
            <!--<intent-filter android:priority="10">-->
            <intent-filter >
                <action android:name="com.grandkai.learnbroadcastreceiver.intent.action.MyReceiver" />
            </intent-filter>
        </receiver>

不指定优先级的情况下,先注册的BroadcastReceiver先执行,不想继续向下执行其他BroadcastReceiver需要在onReceive中执行abortBroadcast();同时启动广播时需要发送有序广播sendOrderedBroadcast(..);

 @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:
                Intent intent = new Intent(ACTION);
//                Intent intent = new Intent(MainActivity.this, MyReceiver.class);
                intent.putExtra("data","111");
                sendOrderedBroadcast(intent, null);
                break;
            case R.id.btnReg:
                if (myReceiver == null) {
                    System.out.println("注册服务");
                    myReceiver = new MyReceiver();
                    registerReceiver(myReceiver , new IntentFilter(ACTION));
                }
                break;
            case R.id.btnUnreg:
                if (myReceiver != null) {
                    System.out.println("注销服务");
                    unregisterReceiver(myReceiver);
                }
                break;

        }
    }
    private MyReceiver myReceiver = null;

  

BroadcastReceiver所对应的广播分两类:普通广播和有序广播。

(1)普通广播所有的receivers接收器的执行顺序不确定。    因此,所有的receivers接收器接收broadcast的顺序不确定。

(2)有序广播通过在intent-filter中设置android:priority属性来设置receiver的优先级。优先级相同的receiver其执行顺序不确定。代码中注册的话,且其intent-filter拥有相同android:priority属性的话,先注册的将先收到广播。

Android BroadcastReceiver

标签:

原文地址:http://www.cnblogs.com/sallet/p/5798617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!