2014-03-25 32 views
10

我想從意向服務內部顯示警告對話框。來自意向服務內部的Android警報對話框

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

這將引發以下異常

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

我試圖IntentService.this和getApplicationContext()爲好。我不想用活動做它。我只是想顯示一個簡單的警告對話框,一點點文字。

+1

訪問https://code.google.com/p/android-smspopup/ –

+1

也訪問https:// github。com/selmantayyar/Custom-SMS-Popup –

+0

感謝您的聯繫。 –

回答

21

需要Activity顯示AlertDialog,因爲我們可以't display Dialog from Service

解決方案。

創建Activity作爲對話框主題,並從Service開始Activity

只需要Activity註冊你menifest.xml類似如下

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

不想使用活動,但它似乎是唯一的方法。謝謝您的幫助。 –

+5

還要添加intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);而在開始活動之前 – Maverick

+0

在關閉對話框之後使用'android:theme =「@ android:style/Theme.Translucent.NoTitleBar」',用'android:theme =「@ android:style/Theme.Dialog」'工作,就像sharm一樣。標題在其他彈出對話框 – Choletski

0

請訪問

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

這將切切實實的幫助你!

或者你可以做的是menifest.xml註冊anActivity如下

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

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

,並解決它

+0

我只是試圖避免使用一項活動。但我終於決定使用它。感謝您的幫助 –

-1

問題是因爲續分機號。 Intent Service中不能使用這個作爲上下文。所以需要將你的Intent服務的Context變量傳遞給你的Alert對話框。像,

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

這不會工作.. –

+0

爲什麼它不會? – 2014-03-25 07:05:39

+0

AlertDialog需要** Activity **(Activity的上下文),並且服務中沒有活動的上下文。 –

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" /> 
+0

棒棒堂裏沒有爲我工作。 'alertDialog.show()'被調用,但沒有任何反應。是的,我已經設置了權限 - 在我這樣做之前,它提出了一個例外,現在它什麼都不做。 –

+0

發現問題了!因爲這是在IntentService中運行的,所以一旦'onHandleIntent'結束,對話就會被銷燬,這幾乎就在'alertDialog.show'之後。它發生得非常快,你甚至不會在屏幕上看到它閃爍。解決方案是使用服務(而不是IntentService)或長時間運行的IntentService:http://stackoverflow.com/questions/6841212/can-in-intentservice-run-indefinitely –