如何在phonestatelistener中创建android alertdialog?

如何在phonestatelistener中创建android alertdialog?,android,android-alertdialog,builder,Android,Android Alertdialog,Builder,代码如下所示: 1) 在清单文件中声明新活动。 (AndroidManifest.xml): 3) 在phonestatelistener中使用新创建的活动。 (公共类侦听器扩展PhoneStateListener) 并非所有的Context对象都是相等的,重用它们是危险的,因为这可能会导致您看到的错误。根据您的评论,您的修订代码正在Config类中存储来自SherlockFragmentActivity的上下文,然后在该活动(及其使用的窗口)可能不再存在时使用它。上下文不是空的,可能用于执行T

代码如下所示:

1) 在清单文件中声明新活动。 (AndroidManifest.xml):

3) 在phonestatelistener中使用新创建的活动。 (公共类侦听器扩展PhoneStateListener)


并非所有的
Context
对象都是相等的,重用它们是危险的,因为这可能会导致您看到的错误。根据您的评论,您的修订代码正在
Config
类中存储来自SherlockFragmentActivity的
上下文
,然后在该
活动
(及其使用的窗口)可能不再存在时使用它。
上下文
不是空的,可能用于执行
Toast
,但是执行窗口操作是非常危险的

一个解决方案是在你的应用程序中创建一个对话框主题的活动,只显示对话框。在
confirmCall()
中,使用
startActivity()
启动活动,然后让活动创建对话框。对于用户来说,屏幕上会出现一个对话框,但没有运行应用程序,但实际上您的应用程序正在运行,并且可以响应用户在对话框上的是/否选择。一定要使用

new AlertDialog.Builder(this)

因此,对话框的
上下文
是一个
活动

,错误日志输出是什么?android.view.WindowManager$BadTokenException:无法添加窗口--标记null不适用于应用程序
mContext
可能为null。如果没有完整日志和code.mContext不为null,则无法判断,因为代码Toast.makeText(mContext,“error!”,Toast.LENGTH_LONG).show();除了尝试,一切都很好!您正在使用的
上下文
可能对执行窗口操作无效,例如创建对话框。有关一些建议,请参见的答案。正如Eric所说,我们需要查看代码。
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);
}
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);
}
new AlertDialog.Builder(this)