功能需求:
點(diǎn)擊懸浮窗中的按鈕顯示一個(gè)Dialog
踩坑之路:
先是Context
Dialog adDialog = new Dialog(context, R.style.DialogStyle);
adDialogView = LayoutInflater.from(context).inflate(R.layout.dialog,null);
adDialog.setContentView(adDialogView);
adDialog.show();
崩潰钦铁,log:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
換成ApplicationContext
Dialog adDialog = new Dialog(context.getApplicationContext(), R.style.DialogStyle);
adDialogView = LayoutInflater.from(context).inflate(R.layout.dialog,null);
adDialog.setContentView(adDialogView);
adDialog.show();
崩潰,log:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
換成Activity
Dialog adDialog = new Dialog(activity, R.style.DialogStyle);
adDialogView = LayoutInflater.from(context).inflate(R.layout.dialog,null);
adDialog.setContentView(adDialogView);
adDialog.show();
第一次啟動(dòng)APP解虱,點(diǎn)擊顯示懸浮窗卜录,成功少办!退出APP再次進(jìn)入扼鞋,點(diǎn)擊懸浮窗,崩潰机久!log:
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@41e48918 is not valid; is your activity running?
添加 TYPE_SYSTEM_ALERT
在代碼中添加:adDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
Dialog adDialog = new Dialog(context.getApplicationContext(), R.style.DialogStyle);
adDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
adDialogView = LayoutInflater.from(context).inflate(R.layout.dialog,null);
adDialog.setContentView(adDialogView);
adDialog.show();
并且在manifest中增加權(quán)限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
此時(shí)臭墨,無論是使用context
或者activity
還是context.getApplicationContext()
都可以正常顯示Dialog