如何在没有 Activity 上下文的情况下在 android 中显示对话框? [英] How do I display a dialog in android without an Activity context?

查看:39
本文介绍了如何在没有 Activity 上下文的情况下在 android 中显示对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来应该很简单,但我在任何地方都找不到答案.我有一个在后台执行网络任务的 Android 应用程序.如果错误再次出现,我想显示一个错误对话框.当任务返回时,我不知道哪个 Activity 在前台.基于这篇文章,看起来我们不能使用应用程序上下文显示一个对话框(如果我尝试确实会崩溃).

This seems like it should be simple, but I'm not finding an answer anywhere. I have an Android application that performs network tasks in the background. If an error comes back, I want to display an error dialog. When the task returns, I don't know which Activity is in the foreground. Based on this post, it looks like we can't use the application context to display a dialog (and indeed I do get the crash if I try).

那么我怎样才能获得当前活动的上下文呢?同样,网络任务的接收器在应用程序上下文中运行,而不是在特定的活动中.还有其他想法吗?

So how can I get the context of the current activity? Again, the receiver for the network task is running in the Application context, not in a particular Activity. Any other ideas?

我应该澄清一下.如果我不是前台应用程序,我不想显示错误对话框.我只对我们的应用目前处于前台的情况感兴趣.

I should clarify. I don't want to display an error dialog if I'm not the foreground application. I'm only interested in the case where our app is in the foreground for now.

推荐答案

如果错误再次出现,我想显示一个错误对话框.

If an error comes back, I want to display an error dialog.

仅当您知道用户正在积极使用您的应用程序时才执行此操作.如果你在做其他事情(玩游戏、看电影、看书)时打断他们,用户会非常非常恼火.

Please only do this if you know that the user is actively using your application. The user will be very very annoyed if you interrupt them in the middle of something else (playing a game, watching a movie, reading a book).

那么我怎样才能获得当前活动的上下文呢?

So how can I get the context of the current activity?

你没有.至多,您让当前活动知道它需要做某事.

You don't. At most, you let the current activity know that it needs to do something.

还有其他想法吗?

一种可能性是使用有序广播,所以如果你有一个前台活动,它会得到控制,否则你会提出一个Notification让用户知道没有弹出对话框的问题.接收有序广播的活动可以显示 AlertDialog 或以其他方式让用户了解问题.我在博客中写了有关如何执行此操作的详细信息发布(和一本书章节,就此而言)和这里是一个示例应用程序,演示了该技术.

One possibility is to use an ordered broadcast, so if you have a foreground activity, it gets control, otherwise you raise a Notification to let the user know about the problem without popping a dialog. The activity that receives the ordered broadcast can display an AlertDialog or otherwise let the user know about the problem. I wrote about the details of how to do this in a blog post (and a book chapter, for that matter), and here is a sample application demonstrating the technique.

或者,让服务调用 startActivity() 来启动 以对话为主题的活动.

Or, have the service call startActivity() to start up a dialog-themed activity.

这篇关于如何在没有 Activity 上下文的情况下在 android 中显示对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆