全局的AlertDialog,不依靠activity

情景:后台service接收到某个广播后发出事件,在application中接收到事件,处理事件是要弹出一个dialog,直接显示会报错:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

在网上查了很久,终于找到方法,作为笔记记录一下:

        AlertDialog.Builder builder = new Builder(context.getApplicationContext());
        builder.setTitle("标题");
        builder.setPositiveButton("确定",null);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setMessage("啊啊啊");
        AlertDialog dialog = builder.create();
        dialog .getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show(); 

记得加权限:

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

参考文章:http://www.eoeandroid.com/thread-199060-1-1.html

http://blog.csdn.net/xixinyan/article/details/6897778


ps:我只是记录一下,详细信息请查看我参考的文章

再ps:http://blog.csdn.net/race604/article/details/9331807这篇文觉得有用,记一下

你可能感兴趣的:(全局的AlertDialog,不依靠activity)