Android四大组件之broadcast广播详解
在Android应用中,Broadcast广播是一种非常重要的组件。它可以在应用内部或应用之间传递消息,帮助我们处理系统级别的事件,比如网络状态变化、电池电量变化、时间时钟等,同时也可以自定义消息传递,使我们的应用更加灵活。
一、Broadcast广播的概念及其种类
Broadcast广播时一种异步的消息收发机制,可以让应用中的不同组件或不同应用之间进行通信。Android中的Broadcast广播分为两种类型:标准广播和有序广播。
1. 标准广播
标准广播是异步完成的,不同组件之间没有先后顺序的关系。它是完全异步执行的,并且无法被截断,无法被取消。发送标准广播的代码如下:
Intent intent = new Intent("custom.action.MY_BROADCAST");// 创建一个intent对象
intent.putExtra("name", "Tom");// 设置广播携带的参数
sendBroadcast(intent);// 发送广播
2. 有序广播
有序广播是有序执行的,它会按照广播注册的先后顺序依次执行每一个接收者。有序广播可以截断并且取消,只要有一个接收者截断了广播,后面所有的接收者都无法再接收到此广播。发送有序广播的代码如下:
Intent intent = new Intent("custom.action.MY_BROADCAST");// 创建一个intent对象
intent.putExtra("account", "1345XXXXXX");// 设置广播携带的参数
sendOrderedBroadcast(intent, null);// 发送广播
二、Broadcast广播的实现方法
1. 静态注册
静态注册是指将BroadcastReceiver在AndroidManifest.xml文件中注册,这种方式优点是可以在应用未运行时也能正确接收Broadcast广播,同时广播接收者可以得到所有广播,无论应用是否在前台,缺点是不管你要用不要用,广播接收者都会创建实例,从而会消耗一定的内存和CPU。
<manifest>
<uses-permission android:name="android.permission.INTERNET"/>
<application>
<receiver android:name=".MyBroadcastReceiver" >
<intent-filter>
<action android:name="com.example.broadcastreceiver" />
</intent-filter>
</receiver>
</application>
</manifest>
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received a broadcast message", Toast.LENGTH_LONG).show();
}
}
2. 动态注册
动态注册BroadcastReceiver需要在代码中通过registerReceiver()方法进行注册,并且需要注意在不需要使用了的时候要主动unregisterReceiver()进行注销,否则会造成内存泄漏。
public class MyActivity extends Activity {
private static final String ACTION_CUSTOM_BROADCAST = BuildConfig.APPLICATION_ID + ".ACTION_CUSTOM_BROADCAST";
private MyBroadcastReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. 创建 BroadcastReceiver 子类实例
mReceiver = new MyBroadcastReceiver();
// 2. 创建 IntentFilter 实例
IntentFilter intentFilter = new IntentFilter();
// 3. 添加想要监听的广播
intentFilter.addAction(ACTION_CUSTOM_BROADCAST);
// 4. 动态注册广播
registerReceiver(mReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 5. 取消注册广播
unregisterReceiver(mReceiver);
}
}
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String ACTION_CUSTOM_BROADCAST = BuildConfig.APPLICATION_ID + ".ACTION_CUSTOM_BROADCAST";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_CUSTOM_BROADCAST.equals(action)) {
String name = intent.getStringExtra("name");
Toast.makeText(context, "Received a custom broadcast message, name: " + name, Toast.LENGTH_LONG).show();
}
}
}
三、Broadcast使用示例
1. 监听网络变化
我们可以使用系统广播来监听网络状态的变化,这里需要动态注册。代码如下:
public class NetworkStateReceiver extends BroadcastReceiver {
private ConnectivityManager mConnectivityManager;
private NetworkInfo mLastNetworkInfo;
@Override
public void onReceive(Context context, Intent intent) {
if (mConnectivityManager == null) {
mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
// 获取当前的网络状态信息
NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
if (networkInfo == null) {
return;
}
// 如果当前的网络状态已变化
if (mLastNetworkInfo != null && mLastNetworkInfo.getState() == networkInfo.getState()) {
return;
}
// 更新最新的网络状态信息
mLastNetworkInfo = networkInfo;
// 执行相应的网络状态处理
if (networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
// 网络连接已断开
Toast.makeText(context, "网络连接已断开", Toast.LENGTH_SHORT).show();
} else if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
// 网络连接已恢复
Toast.makeText(context, "网络连接已恢复", Toast.LENGTH_SHORT).show();
}
}
}
public class MainActivity extends AppCompatActivity {
private NetworkStateReceiver mNetworkStateReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 注册网络状态广播
mNetworkStateReceiver = new NetworkStateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 取消注册网络状态广播
unregisterReceiver(mNetworkStateReceiver);
}
}
2. 发送自定义广播
我们也可以自定义广播,来实现不同组件之间的数据交互。代码如下:
// 发送广播
Intent intent = new Intent(ACTION_CUSTOM_BROADCAST);
intent.putExtra("name", "Tom");
sendBroadcast(intent);
// 接收广播
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_CUSTOM_BROADCAST.equals(action)) {
String name = intent.getStringExtra("name");
Toast.makeText(context, "Received a custom broadcast message, name: " + name, Toast.LENGTH_LONG).show();
}
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Android四大组件之broadcast广播详解 - Python技术站