知识问答

Android四大组件之broadcast广播使用讲解

Android四大组件之broadcast广播使用讲解

在Android开发中,广播(Broadcast)是四大组件之一,广播是一种可以跨应用程序的组件间传递数据的机制。本文将详细讲解broadcast的使用方法及示例。

1. broadcast的定义

广播是一种可以跨应用程序的组件间传递数据的一种机制,在应用中进行发出及接收。广播可以被普通应用程序接收,所以与其它组件一样,可以在一个应用中发送广播,而能够接收它的应用也并不限于它与发送者相同的那个应用程序。

2. broadcast的使用

broadcast要涉及到两个角色,发送者和接收者,即广播的发射源以及接收源。

我们可以通过发送一个Intent对象(也就是广播信号)的方式,将需要传递的数据发送出去(由系统将数据分发给广播接收器),或者通过动态注册的方式,将自己注册为广播接收者,从而接收到系统发出的广播。

2.1 发送者

发送者需要构建一个Intent对象,设置action并添加需要传递的数据,然后通过sendBroadcast(Intent)方法将数据发送出去。如下所示:

// 发送广播Intent intent = new Intent();intent.setAction("com.example.broadcast");intent.putExtra("data", "hello world");sendBroadcast(intent);

2.2 接收者

接收者需要动态注册成为广播接收者或者在manifest文件中静态注册,然后实现onReceive()方法,接收到广播后,即可获取到发送者发送的数据。如下所示:

// 动态注册广播接收者BroadcastReceiver receiver = new BroadcastReceiver() {    @Override    public void onReceive(Context context, Intent intent) {        if ("com.example.broadcast".equals(intent.getAction())) {            String data = intent.getStringExtra("data");            Log.d(TAG, "onReceive: " + data);        }    }};IntentFilter filter = new IntentFilter("com.example.broadcast");registerReceiver(receiver, filter);

3. broadcast的示例

3.1 系统广播示例

系统提供了很多广播动作,我们可以通过注册系统广播的方式,响应系统广播。

下面提供两个示例,第一个是**网络状态发生变化:

public class NetworkChangeReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        // 获取网络状态        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();        if (activeInfo != null && activeInfo.isConnected()) {            Toast.makeText(context, "网络已连接", Toast.LENGTH_SHORT).show();        } else {            Toast.makeText(context, "网络已断开", Toast.LENGTH_SHORT).show();        }    }}

在manifest文件中注册:

<receiver android:name=".NetworkChangeReceiver">    <intent-filter>        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />        <category android:name="android.intent.category.DEFAULT" />    </intent-filter></receiver>

第二个示例是在接收到短信时弹出一个Toast:

public class SmsReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        Bundle bundle = intent.getExtras();        if (bundle != null) {            Object[] pdus = (Object[])bundle.get("pdus");            StringBuilder sb = new StringBuilder();            for (Object pdu : pdus) {                SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);                sb.append("短信来源: " + message.getDisplayOriginatingAddress());                sb.append("\n短信内容: " + message.getDisplayMessageBody());            }            Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();        }    }}

动态注册:

BroadcastReceiver receiver = new SmsReceiver();IntentFilter filter = new IntentFilter();filter.addAction("android.provider.Telephony.SMS_RECEIVED");registerReceiver(receiver, filter);