【问题标题】:Android Alert dialog from inside an intent serviceIntent 服务内部的 Android 警报对话框
【发布时间】:2014-05-02 20:37:26
【问题描述】:

我想从 Intent 服务中显示一个警报对话框。

   AlertDialog alertDialog = new AlertDialog.Builder(this).create();

这会引发以下异常

   Unable to add window — token null is not for an application

我也尝试过 IntentService.this 和 getApplicationContext()。在我不想使用活动之间。我只想显示一个带有小文本的简单警报对话框。

【问题讨论】:

标签: android android-intent android-alertdialog intentservice


【解决方案1】:

需要Activity 来显示AlertDialog,因为我们无法从任何Service 中显示Dialog

解决方案。

创建Activity 作为对话框主题并从Service 开始Activity

只需在menifest.xml 中注册Activity,如下所示

android:theme="@android:style/Theme.Dialog"

android:theme="@android:style/Theme.Translucent.NoTitleBar"

MyDialog.java

public class MyDialog extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("your title");
        alertDialog.setMessage("your message");
        alertDialog.setIcon(R.drawable.icon);

        alertDialog.show();
    }
}

【讨论】:

  • 不想使用活动,但它似乎是唯一的方法。感谢您的帮助。
  • 同时添加intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);在开始活动之前
  • 使用 android:theme="@android:style/Theme.Translucent.NoTitleBar" 像 sharm 一样工作,关闭对话框后使用 android:theme="@android:style/Theme.Dialog" 在其他弹出对话框中重新显示标题
【解决方案2】:

仅当您将 alertDialog 类型设置为 TYPE_SYSTEM_ALERT 时,它才会从 Intent 服务中显示。

 AlertDialog alertDialog = new AlertDialog.Builder(this).create();

在您的代码后添加这些:

alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();

但是,这是有代价的:

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

【讨论】:

  • 在 Lollipop 中对我不起作用。 alertDialog.show() 被调用但没有任何反应。是的,我已经设置了权限——在我这样做之前,它引发了一个异常,现在它什么都不做。
  • 发现问题了!因为这是在 IntentService 中运行的,所以对话框会在 onHandleIntent 结束后立即销毁,这几乎是在 alertDialog.show 之后立即销毁的。它发生得如此之快,你甚至看不到它在屏幕上闪烁。解决方案是使用服务(而不是 IntentService)或这个长期运行的 IntentService:stackoverflow.com/questions/6841212/…
【解决方案3】:

请访问

https://github.com/selmantayyar/Custom-SMS-Popup

它会对你有帮助的!!

或者你可以在menifest.xml中注册一个Activity,如下所示

android:theme="@android:style/Theme.Dialog"

android:theme="@android:style/Theme.Translucent.NoTitleBar"

并解决它

【讨论】:

  • 我只是想避免使用活动。但我最终决定使用它。感谢您的帮助
【解决方案4】:

问题在于上下文。您不能将 this 用作 Intent Service 中的上下文。所以需要将 Intent Service 的 Context 变量传递给 Alert Dialog。喜欢,

AlertDialog alertDialog = new AlertDialog.Builder(context).create();

【讨论】:

  • AlertDialog 需要 Activity(Activity 的上下文)并且服务中没有 Activity 的上下文。
猜你喜欢
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
  • 1970-01-01
  • 2012-08-06
  • 2012-02-07
相关资源
最近更新 更多