3. 广播接收器
文档
借助广播接收器组件, 系统能够在常规用户流之外向应用传递事件, 从而允许应用响应系统范围内的广播通知.由于广播接收器是另一个明确定义的应用入口,因此系统甚至可以向当前未运行的应用传递广播.
许多广播均由系统发起, 例如, 通知屏幕已关闭 电池电量不足或已拍摄照片的广播. 应用也可发起广播, 例如, 通知其他应用某些数据已下载至设备, 并且可供其使用.尽管广播接收器不会显示界面, 但其可以创建状态栏通知, 在发生广播事件时提醒用户.
注册
AndroidManifest.xml注册接收器
android:name=“.receiver.BootBroadcastReceiver” //指定类名
<!-- 指定类名 等属性-->
<receiver
android:name=".receiver.BootBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:process="com.joinken.application">
<!-- 意图过滤 感兴趣的广播, 或者说能够触发接受的意图-->
<intent-filter>
<!--系统广播 开机启动 -->
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
<intent-filter>
<!-- 自定义广播 第三方调用-->
<action android:name="com.joinken.application.ACTION_TEST" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<action android:name="android.intent.action.MEDIA_UNMOUNTED" />
<action android:name="android.intent.action.MEDIA_EJECT" />
<data android:scheme="file" />
</intent-filter>
</receiver>代码
广播接收器作为 BroadcastReceiver 的子类实现, 并且每条广播都作为 Intent 对象进行传递.
public class BootBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "BootBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
//start service 启动服务组件
Intent it = new Intent(context, LinstenService.class);
context.startService(it);
/***********start activity 启动activity组件********/
Intent it2 = new Intent(context, MainActivity.class);
it2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//需要这个 FLAG_ACTIVITY_NEW_TASK 才能后台启动activity 弹出到前台
context.startActivity(it2);
}
}通过 ADB 发送广播 /测试
//低电量
adb shell am broadcast -a android.intent.action.ACTION_BATTERY_LOW
//扩展卡 已挂载
adb shell am broadcast -a android.intent.action.ACTION_MEDIA_MOUNTED
//已完成开机
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
//自定义
adb shell am broadcast -a ACTION_TEST