单击通知后未显示AlertDialog

时间:2015-08-11 17:51:23

标签: java android android-asynctask notifications android-alertdialog

我正在努力做到以下几点:

我的应用程序有一个AsyncTask,它最终会创建一个AlertDialog来请求用户输入代码。这可以在应用程序位于前台时发生,因此我发出通知以通知用户,我的想法是,一旦他点击通知,就会显示带有AlertDialog的主要活动。

然而,发生的事情是,一旦用户点击通知,就会显示AlertDialog应该出现的活动,并且我得到一个可能由Dialog引起的WindowLeaked异常。

我正在使用代码来启动通知(来自AsyncTask的onProgressUpdate方法):

public void launch_notification(){
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(context.getString(R.string.opening_request_notification_title))
                    .setContentText(context.getString(R.string.opening_request_notification_text));
    /* The intent must be created with an specific content and then frozen to be used
    later using a pending intent.
     */
    Intent notificationIntent = new Intent(context, Main.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notificationBuilder.setContentIntent(pendingIntent);
    notificationBuilder.setAutoCancel(true);
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}

任何想法都会受到欢迎。 非常感谢:)

2 个答案:

答案 0 :(得分:1)

最好在DialogActivity的清单集中创建单独的Activity(示例DialogActivity)。

答案 1 :(得分:1)

您的通知创建似乎很好,您可以从onProgressUpdate调用该方法,这也很好 所以你的活动和处理对话的方式一定有问题。

如果你可以提供你的Main课程,我们可以肯定地知道,但是我猜你在AsyncTask中发生了什么,你会显示某种对话,也许是一个进度对话框。
如果是这种情况,那么当您收到通知(进度更新)并单击它时,您再次启动主要活动,因此您最终会创建另一个主要活动实例,从而导致泄漏窗口。 尝试添加标记FLAG_ACTIVITY_CLEAR_TOP 正如API所述:

  

如果已设置,并且正在启动的活动已在当前任务中运行,则不会启动该活动的新实例,而是将关闭其上的所有其他活动,并将此Intent传递给(现在在最前面)作为新意图的旧活动。

希望这会帮助你。