从意图服务中的Andr​​oid警报对话框警报、对话框、意图、oid

2023-09-04 09:51:43 作者:云胡

我想从一个意图服务中显示一个警告对话框。

I want to display an alert dialog from inside an intent service.

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

这将引发以下异常

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

我已经试过IntentService.this和getApplicationContext()也是如此。之间,我不想用一个活动来做到这一点。我只是想表明一个小文本的简单警告对话框。

I have tried IntentService.this and getApplicationContext() as well. Between i dont want to do it using an activity. I just want to show a simple alert dialog with a little text.

推荐答案

需要活动显示 AlertDialog ,因为我们无法显示对话框任何服务

Need Activity for display AlertDialog, because we can't display Dialog from any Service

解决方案。

创建活动作为对话主题,并启动活动服务

Create Activity as Dialog Theme and start that Activity from Service.

只需要您注册活动 menifest.xml 类似如下

Just need to register you Activity in menifest.xml like as below

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();
    }
}