android.view.WindowManager$BadTokenException: Unable to add window – token android.os.xxx is not valid; is your activity running?

android app的bug统计工具中常遇会记录到这个异常,错误的代码如下:

  public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    findViewById(R.id.button1).setOnClickListener(new Button.OnClickListener() {                public void onClick(View v) {            new AlertDialog.Builder(getApplicationContext())            .setTitle(R.string.dialogTitle)            .setMessage(R.string.dialogMessage)            .setPositiveButton("确定", new DialogInterface.OnClickListener() {                public void onClick(DialogInterface dialog, int which) {                    Toast.makeText(getApplicationContext(), "你按了确定。", Toast.LENGTH_SHORT).show();                }            }).show();        }    });}

异常原因:AlertDialog创建语句public AlertDialog.Builder (Context context)中,不能使用getApplicationContext()得到的context,而必须使用Activity,所以解决如下

解决办法:

将 new AlertDialog.Builder(getApplicationContext()) 改为 new AlertDialog.Builder(MainActivity.this)

其中MainActivity 为当前Activity的名称

更多相关文章

  1. Android各版本名称
  2. 使用HTTPclient访问豆瓣API问题
  3. Android(安卓)Program type already present: XXXX
  4. Android项目打包遇com.android.builder.internal.aapt.v2.Aapt2E
  5. 升级到3.6.3 之后,原项目出现错误 Found tag id where item is ex
  6. [Android]错误: -source 1.7 中不支持 lambda 表达式 (请使用 -s
  7. android studio错误: 常量字符串过长
  8. android mk学习-添加lib包
  9. layout_marginBottom的使用(将VIEW放置在布局底部)

随机推荐

  1. android broadcast intent
  2. Android(安卓)SDK Installation
  3. android中之断点续传
  4. Android(安卓)Light Sensor与Temperature
  5. Android(安卓)P sensor对某个APP方向做旋
  6. 2011.07.05(2)——— android PopupWindo
  7. android 加密 解密
  8. 运行时报错:Invoke-customs are only supp
  9. android recovery 和reboot
  10. Android中Binder类代码(android-5.0.2)