android 开机启动一个流量提示的dialog

原理很简单,监听系统启动时候的广播:android.intent.action.BOOT_COMPLETED

监听该广播时需要添加权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

广播注册,一定要加category否则无法监测到:

<receiver
android:name=".DataConnectTipReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>

<category android:name="android.intent.category.HOME"/>
</intent-filter>
</receiver>

然后是设置dialog,其他东西就不详细展示,展示核心代码:

alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();

注意:使用的是Alertdialog,先调用create()方法得到一个dialog对象然后设置该dialog的窗口类型为WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,如果不这么设置dialog将会因为没有上下文而报错,。

最后只要将广播安装就好了,开机的时候就能看到效果了,在此分享一个模拟开机广播的方法:

调用adb:adb shell am broadcast -a android.intent.action.BOOT_COMPLETED  模拟手机发送BOOT_COMPLETED广播

命令发送BOOT_COMPLETED广播,而不用重启测试机或模拟器来测试BOOT_COMPLETED广播,这条命令可以更精确的发送到某个package:
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n package_name/class_name 。本次分享不多,只希望用到的时候能帮助到各位读者

 ————一个成长中的迷途小码农;


猜你喜欢

转载自blog.csdn.net/wh2526422/article/details/50377639