android 9 广播接收者
时间: 2023-07-22 07:26:28 浏览: 64
Android 9(API级别28)中的广播接收器需要在运行时进行注册,而不能在AndroidManifest.xml文件中进行静态注册。这是为了增强应用程序的安全性,以防止恶意应用程序在后台注册广播接收器并接收敏感广播。
以下是在Android 9中注册BroadcastReceiver的步骤:
1. 在Activity或Service中创建BroadcastReceiver对象。
2. 创建IntentFilter对象并添加接收的广播类型。
3. 调用Context的registerReceiver()方法,将BroadcastReceiver对象和IntentFilter对象传递给它。
4. 在不再需要接收广播时,调用Context的unregisterReceiver()方法来注销BroadcastReceiver。
例如,以下代码演示如何在Activity中注册BroadcastReceiver:
```
public class MyActivity extends Activity {
private MyBroadcastReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 创建BroadcastReceiver对象
mReceiver = new MyBroadcastReceiver();
// 创建IntentFilter对象并添加接收的广播类型
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_POWER_CONNECTED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
// 注册BroadcastReceiver
registerReceiver(mReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 注销BroadcastReceiver
unregisterReceiver(mReceiver);
}
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)