Android 来自不同 class 的对话

Android Dialog from different class

我正在构建一个 android 应用程序并希望从非 activity class(在后台发生)调用一个对话框。 我希望对话框显示在特定的 activity 上,但为了让其他 class 调用此函数,它需要是静态的,但我不能从静态上下文中调用 getSupportFragmentManager() . 有解决这个问题的方法吗?这是我要使用的代码。

    public static void method_invoked_returned_null(String response) {
        ErrorDialog errorDialog = new ErrorDialog();
        ErrorDialog.errorType = "Response Command Error";
        ErrorDialog.errorDialogMessage = "Error in Invoking " + response
                +  ". Do you want to continue?";
        errorDialog.show(getSupportFragmentManager(), "Wrong Response Dialog");
    }

你有两个解决方案

1:使用广播接收器并在 activity 的 onResume 中注册广播并在 onPause 中取消注册。

2:您可以在 activity 中添加静态字段实例并在 onResume 中设置值并在 onPause

中删除它
private static AppCompatActivity instance;
@Override
protected void onResume() {
    super.onResume();
    instance = this;
}

@Override
protected void onPause() {
    super.onPause();
    instance = null;
}
public static void method_invoked_returned_null(String response) {
    if (instance == null)
        return;
    instance.runOnUiThread(new Runnable() {
        @Override
        public void run() {

            ErrorDialog errorDialog = new ErrorDialog();
            ErrorDialog.errorType = "Response Command Error";
            ErrorDialog.errorDialogMessage = "Error in Invoking " + response
                    +  ". Do you want to continue?";
            errorDialog.show(instance.getSupportFragmentManager(), "Wrong Response Dialog");
        }
    });
}