2012-10-20 55 views
0

代碼如下所示:如何在phonestatelistener中創建一個android alertdialog?

1)在清單文件中聲明新的活動。 (AndroidManifest.xml中):

<activity 
     android:name=".ConfirmDialog" 
     android:label="@string/app_name" 
     android:theme="@android:style/Theme.Dialog" 
     android:launchMode="singleTask" 
     android:screenOrientation="vertical">   
    </activity> 

2)創建新的類延伸活性。 (公共類ConfirmDialog擴展活動)

private static final int DIALOG_YES_NO_MESSAGE = 1; 

@Override 
protected Dialog onCreateDialog(int id) { 
    switch (id) { 
    case DIALOG_YES_NO_MESSAGE: 
     return new AlertDialog.Builder(ConfirmDialog.this) 
      .setIconAttribute(android.R.attr.alertDialogIcon) 
      .setTitle(R.string.app_name) 
      .setMessage(R.string.ask_confirm) 
      .setPositiveButton(R.string.ask_confirm_yes, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int whichButton) { 
        dialog.cancel(); 
        finish(); 
       } 
      }) 
      .setNegativeButton(R.string.ask_confirm_no, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int whichButton) { 
        dialog.cancel(); 
        finish(); 
       } 
      }) 
      .create(); 
    } 
    return null; 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    showDialog(DIALOG_YES_NO_MESSAGE); 
} 

3)使用新創建的活動中phonestatelistener。 (公共類監聽器擴展PhoneStateListener)

public void onCallStateChanged(int state, String incomingNumber){ 

    switch(state){    
     case TelephonyManager.CALL_STATE_OFFHOOK: 
      confirmCall();   
     break; 
    } 

    super.onCallStateChanged(state, incomingNumber); 

} 

private void confirmCall(){ 
    Intent intent = new Intent(); 
    intent.setComponent(new ComponentName("com.example", "com.example.ConfirmDialog")); 
    mContext.startActivity(intent); 
} 
+0

什麼是錯誤日誌輸出? – Eric

+0

android.view.WindowManager $ BadTokenException:無法添加窗口 - 標記null不適用於應用程序 – Ludiaz

+0

'mContext'可能爲null。沒有完整的日誌和代碼是不可能分辨的。 – Eric

回答

0

並非所有Context對象是相等的,和重用他們是危險的,因爲它會導致你看到的錯誤。根據您的評論,您的修改代碼將在您的Config類中存儲來自SherlockFragmentActivity的Context,然後在該Activity(及其使用的窗口)可能不再存在時再使用它。 Context不爲空,可能可以用於執行Toast,但執行窗口操作非常危險。

一個解決方案是在您的應用程序中創建一個對話框主題的活動,只顯示對話框。在confirmCall()中,使用startActivity()啓動您的活動,然後讓活動創建對話框。對於用戶來說,屏幕上會出現一個對話框,但沒有運行應用程序,但實際上您的應用程序正在運行,並且可以響應用戶對話框上的「是/否」選項。一定要使用

new AlertDialog.Builder(this) 

使對話框的ContextActivity

相關問題