Android中的有序和无序广播浅析

0.894字数 1196阅读 7445

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

无序广播即为我们平时经常使用的广播,其主要是通过public abstract void sendBroadcast (Intent intent)方法进行发送,并通过intent传递数据。代码示例如下:

Intent nonOrderIntent = new Intent();
nonOrderIntent.setAction(ACTION);
sendBroadcast(nonOrderIntent);

无序广播会被注册了的相应的感兴趣(intent-filter匹配)接收,且顺序是无序的。如果发送广播时有相应的权限要求,BroadCastReceiver如果想要接收此广播,也需要有相应的权限。

无序广播的广播接收者不可以使用setResultData()方法和abortBroadcast()方法,如果使用了会报错。 但是可以使用getResultData()方法,虽然不报错,但是获取到的数据为null。但是在一种<u>特殊情况</u>下,getResultData()方法能取到无序广播传递的数据,下文会说明在什么情况下。

无序广播不可以被拦截,不可以被终止,不可以被修改,无序广播任何接收者只要匹配条件都可以接收到,无优先级问题。

如果想通过无序广播传递数据,则可以调用intent.putExtra方法传递, 接收者可通过intent.get...接收,不可通过getResultData接收。

有序广播主要是通过public abstract void sendOrderedBroadcast (Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)方法进行发送。代码示例如下:

Intent intent = new Intent();
intent.setAction(ACTION);
sendOrderedBroadcast(intent, null, new Priority2BroadcastReceiver(), null, Activity.RESULT_OK, "MainActivity发送了一个有序广播", null);

先介绍一下public abstract void sendOrderedBroadcast (Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)方法

官网api的参数解释:

Parameters
intent The Intent to broadcast; all receivers matching this Intent will receive the broadcast.
receiverPermission String naming a permissions that a receiver must hold in order to receive your broadcast. If null, no permission is required.
resultReceiver Your own BroadcastReceiver to treat as the final receiver of the broadcast.
scheduler  A custom Handler with which to schedule the resultReceiver callback; if null it will be scheduled in the Context's main thread.
initialCode    An initial value for the result code. Often Activity.RESULT_OK.
initialData    An initial value for the result data. Often null.
initialExtras  An initial value for the result extras. Often null.

第一个intent:不多说指定intent,所有广播接收者的匹配规则

第二个receiverPermission:指定广播接收器的权限,一般自定义,不常用,可传null。

第三个resultReceiver:指定一个最终的广播接收器,相当于finally功能,不论优先级,最后都要接收一次广播,而这一次收到的广播为无序广播(可以在BroadcastReceiver中通过boolean orderedBroadcast = isOrderedBroadcast()方法验证),但是却可以通过getResultData等方法取得数据,这就是上面提到的特殊情况。

第四个scheduler:看英文没怎么看懂什么意思,一般传null。

第五个initialCode:指定一个code,一般传Activity.RESULT_OK。

第六个initialData:传一个字符串数据。对应的在BroadcastReceiver中通过String resultData = getResultData()取得数据;通过setResultData("优先级为3的setResultData的数据")修改数据,将数据传给下一个优先级较低的BroadcastReceiver;如果在优先级较高的BroadcastReceiver中没有使用setResultData修改数据,那么优先级较低的接收到的数据还是最原始的数据,即initialData的值。

第七个initialExtras:传一个Bundle对象,也就是可以传多种类型的数据。对应的在BroadcastReceiver中通过Bundle bundle = getResultExtras(false)取得Bundle对象,然后再通过bundle的各种get方法取得数据;通过setResultExtras()传入一个修改过的bundle,将该bundle对象传给下一个优先级较低的BroadcastReceiver;如果在优先级较高的BroadcastReceiver中没有使用setResultExtras修改数据,那么优先级较低的接收到的数据还是最原始的bundle对象,即initialExtras的值。

有序广播所对应的所有的receiver按照在intent-filter中设置的android:priority属性依次执行,android:priority表示优先级,值越大,其所对应的广播接收者,越先接收到广播。在android:priority相同的情况下,如果广播接收器是通过静态注册的,则接收到广播的顺序不确定,如果是动态注册的,先注册的将先收到广播。

有序广播可以被拦截,�可以在较高优先级的接收器中通过abortBroadcast()拦截广播,这样就会导致较低优先级的接收器无法收到广播了,但是sendOrderedBroadcast第三个参数指定的BroadcastReceiver还是会收到广播的,而且能获得数据。

有序广播可以通过原始intent.putExtra这种方式传递数据给BroadcastReceiver,也能通过sendOrderedBroadcast方法的最后2个参数传递数据,但是通过第一种方式传递的数据无法中途修改,通过第二种方式传递的可以通过上面参数说明中的方式进行修改。

具体验证方式可通过如下代码验证以上结论:

MainActivity

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.tbc.hsx.testbroadcast.receiver.Priority2BroadcastReceiver;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String ACTION = "com.tbc.hsx.testbroadcast.MainActivity";
    public static final String DATA = "data";
    public static final String ORDER_DATA = "order_data";

    @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();
            }
        });


        findViewById(R.id.send_broadcast_btn).setOnClickListener(this);
        findViewById(R.id.send_ordered_broadcast_btn).setOnClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);

        }
    };

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.send_broadcast_btn) {
            Intent nonOrderIntent = new Intent();
            nonOrderIntent.setAction(ACTION);
            sendBroadcast(nonOrderIntent);
        } else if (view.getId() == R.id.send_ordered_broadcast_btn) {
            Intent intent = new Intent();
            intent.putExtra(DATA, "有序广播通过intent.putExtra传递的数据");
            intent.setAction(ACTION);
            Bundle bundle = new Bundle();
            bundle.putString(ORDER_DATA, "有序广播通过bundle传递的数据");

            sendOrderedBroadcast(intent, null, new Priority2BroadcastReceiver(), handler, Activity.RESULT_OK, "MainActivity发送了一个有序广播", bundle);
        }

    }
}

Priority1BroadcastReceiver

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

/**
 * Created by Doraemon
 * Date: 16/4/27
 * Time: 16:35
 * Summary:优先级为1的广播接收器
 */
public class Priority1BroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        String resultData = getResultData();//获取有序广播的数据
        System.out.println("优先级为1的接收到的广播数据resultData---->" + resultData);
        setResultData("优先级为1的setResultData的数据");//修改有序广播的数据
    }
}

Priority2BroadcastReceiver

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.tbc.hsx.testbroadcast.MainActivity;

/**
 * Created by Doraemon
 * Date: 16/4/27
 * Time: 16:35
 * Summary:
 */
public class Priority2BroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        boolean orderedBroadcast = isOrderedBroadcast();

        if (orderedBroadcast) {
            System.out.println("优先级为1的接收者接收到的是有序广播");
        } else {
            System.out.println("优先级为1的接收者接收到的是无序广播");
        }


        Bundle bundle=getResultExtras(false);
        if (bundle != null) {
            String orderData = bundle.getString(MainActivity.ORDER_DATA);
            System.out.println("Priority2BroadcastReceiver-------->" + orderData);
        }

        String resultData = getResultData();//获取有序广播的数据
        System.out.println("优先级为2的接收到的广播数据resultData---->" + resultData);
        setResultData("优先级为2的setResultData的数据");//修改有序广播的数据
    }
}

Priority3BroadcastReceiver

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.tbc.hsx.testbroadcast.MainActivity;

/**
 * Created by Doraemon
 * Date: 16/4/27
 * Time: 16:32
 * Summary:
 */
public class Priority3BroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle bundle = getResultExtras(false);
        if (bundle != null) {
            String orderData = bundle.getString(MainActivity.ORDER_DATA);
            System.out.println("Priority3BroadcastReceiver-------->" + orderData);
        }

//        bundle.putString(MainActivity.ORDER_DATA, "优先级为3的接收者修改了bundle数据");
//        setResultExtras(bundle);

        boolean orderedBroadcast = isOrderedBroadcast();
        if (orderedBroadcast) {
            System.out.println("优先级为3的接收者接收到的是有序广播");
        } else {
            System.out.println("优先级为3的接收者接收到的是无序广播");
        }
        String resultData = getResultData();//获取有序广播的数据
        System.out.println("优先级为3的接收到的广播数据resultData---->" + resultData);
        setResultData("优先级为3的setResultData的数据");//修改有序广播的数据
//        abortBroadcast();

    }
}

AndroidManifest.xml(BroadcastReceiver注册部分)

<receiver android:name=".receiver.Priority1BroadcastReceiver">
    <intent-filter android:priority="1">
        <action android:name="com.tbc.hsx.testbroadcast.MainActivity" />
    </intent-filter>
</receiver>
<receiver android:name=".receiver.Priority2BroadcastReceiver">
    <intent-filter android:priority="2">
        <action android:name="com.tbc.hsx.testbroadcast.MainActivity" />
    </intent-filter>
</receiver>

<receiver android:name=".receiver.Priority3BroadcastReceiver">
    <intent-filter android:priority="3">
        <action android:name="com.tbc.hsx.testbroadcast.MainActivity" />
    </intent-filter>
</receiver>

推荐阅读更多精彩内容