在Intent服务中弹出Android提示对话框

12

我想在Intent Service内部显示一个警告对话框。

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

这会抛出以下异常

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

我已经尝试过IntentService.this和getApplicationContext()了,但我不想使用Activity来实现。我只想显示一个简单的带有一些文本的警告对话框。


1
请访问 https://code.google.com/p/android-smspopup/。 - Jitesh Upadhyay
1
请访问 https://github.com/selmantayyar/Custom-SMS-Popup 了解有关编程的更多信息。 - Jitesh Upadhyay
感谢提供链接。 - Sayed Jalil Hassan
1
可能是重复的问题:来自服务的Android警报对话框 - naXa stands with Ukraine
https://stackoverflow.com/a/29804684/2149195 - RBK
4个回答

24

为了显示AlertDialog,需要使用Activity,因为我们无法从任何Service中显示Dialog。

解决方案。

创建一个Dialog主题的Activity,并从Service中启动该Activity。

只需要像下面这样在manifest.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();
    }
}

不想使用Activity,但似乎这是唯一的方法。感谢您的帮助。 - Sayed Jalil Hassan
6
同时在启动活动前添加intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - Maverick
1
使用android:theme="@android:style/Theme.Translucent.NoTitleBar"可以像Sharm一样工作,而在关闭对话框后,使用android:theme="@android:style/Theme.Dialog"会在其他弹出对话框中重新显示标题。 - Choletski

11

只有当你将alertDialog的类型设置为TYPE_SYSTEM_ALERT时,它才会从意图服务中显示出来。

 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()被调用了,但是什么也没发生。是的,在此之前我已经设置了权限 - 在我这样做之前,它会引发异常,现在它什么也不做。 - Stephen Hosking
找到问题了!因为这是在IntentService中运行的,所以对话框会在onHandleIntent结束后立即销毁,而这几乎是在alertDialog.show之后。它发生得如此之快,以至于你甚至看不到它在屏幕上闪烁。解决方案是要么使用Service(而不是IntentService),要么使用这个长时间运行的IntentService:https://dev59.com/questions/x2w15IYBdhLWcg3wFHtZ - Stephen Hosking

1
请访问。

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

它肯定会帮助你!

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

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

或者

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

并绕过它


我一开始想避免使用Activity,但最终决定使用它。感谢您的帮助。 - Sayed Jalil Hassan

-2
问题出在上下文。你不能在Intent Service中使用this作为上下文。因此需要将Intent Service的上下文变量传递给警报对话框。例如,
AlertDialog alertDialog = new AlertDialog.Builder(context).create();

AlertDialog需要Activity(Activity的上下文),而服务中没有活动的上下文。 - Niranj Patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接