一、弹窗权限
<uses-permissionandroid:name="android.permission.SYSTEM_ALERT_WINDOW" />
二、广播唤起(活动)Activity
//关键点:需要添加 Intent.FLAG_ACTIVITY_NEW_TASK
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
public class MyAppReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// XXXXXActivity : 唤起的目标Activity活动
Intent intent = new Intent(context,XXXXXActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
三、广播唤起(弹窗)Dialog / Dialog.Bulider
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
public class XXXXReceiver extends BroadcastReceiver{
@Override
public void onReceive(final Context context, Intent intent){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("欢迎来到CSDN博客");
builder.setMessage("欢迎关注彭老希");
builder.setCancelable(false);
builder.setPositiveButton("Welcome", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which){
Intent intent = new Intent(context, LoginActivity.class);
//在广播接受者中启动活动需要添加这个标志
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
AlertDialog dialog = builder.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); //需要设置AlertDialog的类型,保证在广播接收者中可以正常弹出
dialog.show();
}
}
其他方式
正常弹出AlertDialog的流程如下:
new AlertDialog.Builder(context).setTitle("在BroadcastReceiver里弹出AlertDialog").show();
但是其实AlertDialog似乎只能在activity中弹出为了解决在BroadcastReceiver里弹出AlertDialog这个问题,我们可以这样做:
AlertDialog alertDialog=new AlertDialog.Builder(context).create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
最后还要在AndroidManifest.xml文件中加入以下两句话:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW"/>