我想在安卓框架的某个地方弹出一个AlertDialog,问题是需要一个ui上下文,而在框架的大多数部分都没有这样的ui上下文。
经过一番研究,我在AutofillManagerService.java中找到了一个例子:https://cs.android.com/android/platform/superproject/+/master:frameworks/base/services/autofill/java.com/android/server/autofill/AutofillManagerService.java;l=199?q=自动填充管理&ss=安卓%2Fplatform%2Fsuperproject
mUi = new AutoFillUI(ActivityThread.currentActivityThread().getSystemUiContext());
这里ui上下文(ActivityThread.currentActivityThread().getSystemUiContext()
(将被传递给SaveUi
以创建对话框:https://cs.android.com/android/platform/superproject/+/master:frameworks/base/services/autofill/java.com/android/server/autofill/ui/SaveUi.java;l=340;bpv=0;bpt=1
mDialog = new Dialog(context, mThemeId);
mDialog.setContentView(view);
// Dialog can be dismissed when touched outside, but the negative listener should not be
// notified (hence the null argument).
mDialog.setOnDismissListener((d) -> mListener.onCancel(null));
final Window window = mDialog.getWindow();
window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
| WindowManager.LayoutParams.FLAG_DIM_BEHIND);
window.setDimAmount(0.6f);
window.addPrivateFlags(WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS);
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
window.setGravity(Gravity.BOTTOM | Gravity.CENTER);
window.setCloseOnTouchOutside(true);
final WindowManager.LayoutParams params = window.getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.accessibilityTitle = context.getString(R.string.autofill_save_accessibility_title);
params.windowAnimations = R.style.AutofillSaveAnimation;
show();
然而,当我尝试做同样的事情时,它崩溃了,我的代码类似于:
new AlertDialog.Builder(ActivityThread.currentActivityThread().getSystemUiContext())
.setTitle("some title")
.setMessage("some message")
.setPositiveButton("yes", (dialog, which) -> {
})
.setNegativeButton("no", (dialog, which) -> {
})
.create()
.show();
任何帮助都将不胜感激,谢谢。
在android中有很多方法可以获取上下文。在活动中,您可以通过this关键字获取上下文,或者在片段中,它可能是requireContext((,或者简单的是applicationContext。你试过这个吗?
经过一些研究和测试,我终于找到了解决方案。
在Android框架中,我们可以使用ActivityThread.currentActivityThread().getSystemUiContext()
来创建AlertDialog,即使ActivityThread.currentActivityThread().getSystemContext()
也可以,关键是:
window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
设置对话框的窗口类型在这里是必要的。
请参阅示例代码:https://cs.android.com/android/platform/superproject/+/master:frameworks/base/services/autofill/java.com/android/server/autofill/ui/SaveUi.java;l=348
我已经在两种情况下(getSystemUiContext()
和getSystemContext()
(对它进行了测试,结果都有效。