当进度对话框和后台线程处于活动状态时如何处理屏幕方向变化?
我的程序在后台线程中执行一些网络活动。 在开始之前,它会弹出一个进度对话框。 该对话框在处理程序上被关闭。 这一切都工作正常,除非在对话框启动时屏幕方向发生变化(并且后台线程正在运行)。 此时,应用程序要么崩溃,要么死锁,或者进入一个奇怪的阶段,在该阶段应用程序根本无法工作,直到所有线程都被杀死。
如何优雅地处理屏幕方向的变化?
下面的示例代码大致匹配我的真实程序的功能:
public class MyAct extends Activity implements Runnable {
public ProgressDialog mProgress;
// UI has a button that when pressed calls send
public void send() {
mProgress = ProgressDialog.show(this, "Please wait",
"Please wait",
true, true);
Thread thread = new Thread(this);
thread.start();
}
public void run() {
Thread.sleep(10000);
Message msg = new Message();
mHandler.sendMessage(msg);
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mProgress.dismiss();
}
};
}
Stack:
E/WindowManager( 244): Activity MyAct has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@433b7150 that was originally added here
E/WindowManager( 244): android.view.WindowLeaked: Activity MyAct has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@433b7150 that was originally added here
E/WindowManager( 244): at android.view.ViewRoot.<init>(ViewRoot.java:178)
E/WindowManager( 244): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:147)
E/WindowManager( 244): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:90)
E/WindowManager( 244): at android.view.Window$LocalWindowManager.addView(Window.java:393)
E/WindowManager( 244): at android.app.Dialog.show(Dialog.java:212)
E/WindowManager( 244): at android.app.ProgressDialog.show(ProgressDialog.java:103)
E/WindowManager( 244): at android.app.ProgressDialog.show(ProgressDialog.java:91)
E/WindowManager( 244): at MyAct.send(MyAct.java:294)
E/WindowManager( 244): at MyAct$4.onClick(MyAct.java:174)
E/WindowManager( 244): at android.view.View.performClick(View.java:2129)
E/WindowManager( 244): at android.view.View.onTouchEvent(View.java:3543)
E/WindowManager( 244): at android.widget.TextView.onTouchEvent(TextView.java:4664)
E/WindowManager( 244): at android.view.View.dispatchTouchEvent(View.java:3198)
我尝试关闭 onSaveInstanceState 中的进度对话框,但这只是防止立即崩溃。 后台线程仍在运行,UI 处于部分绘制状态。 需要先杀死整个应用程序,然后才能重新开始工作。
My program does some network activity in a background thread. Before starting, it pops up a progress dialog. The dialog is dismissed on the handler. This all works fine, except when screen orientation changes while the dialog is up (and the background thread is going). At this point the app either crashes, or deadlocks, or gets into a weird stage where the app does not work at all until all the threads have been killed.
How can I handle the screen orientation change gracefully?
The sample code below matches roughly what my real program does:
public class MyAct extends Activity implements Runnable {
public ProgressDialog mProgress;
// UI has a button that when pressed calls send
public void send() {
mProgress = ProgressDialog.show(this, "Please wait",
"Please wait",
true, true);
Thread thread = new Thread(this);
thread.start();
}
public void run() {
Thread.sleep(10000);
Message msg = new Message();
mHandler.sendMessage(msg);
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mProgress.dismiss();
}
};
}
Stack:
E/WindowManager( 244): Activity MyAct has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@433b7150 that was originally added here
E/WindowManager( 244): android.view.WindowLeaked: Activity MyAct has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@433b7150 that was originally added here
E/WindowManager( 244): at android.view.ViewRoot.<init>(ViewRoot.java:178)
E/WindowManager( 244): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:147)
E/WindowManager( 244): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:90)
E/WindowManager( 244): at android.view.Window$LocalWindowManager.addView(Window.java:393)
E/WindowManager( 244): at android.app.Dialog.show(Dialog.java:212)
E/WindowManager( 244): at android.app.ProgressDialog.show(ProgressDialog.java:103)
E/WindowManager( 244): at android.app.ProgressDialog.show(ProgressDialog.java:91)
E/WindowManager( 244): at MyAct.send(MyAct.java:294)
E/WindowManager( 244): at MyAct$4.onClick(MyAct.java:174)
E/WindowManager( 244): at android.view.View.performClick(View.java:2129)
E/WindowManager( 244): at android.view.View.onTouchEvent(View.java:3543)
E/WindowManager( 244): at android.widget.TextView.onTouchEvent(TextView.java:4664)
E/WindowManager( 244): at android.view.View.dispatchTouchEvent(View.java:3198)
I have tried to dismiss the progress dialog in onSaveInstanceState, but that just prevents an immediate crash. The background thread is still going, and the UI is in partially drawn state. Need to kill the whole app before it starts working again.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(28)
编辑:正如 Dianne Hackborn(又名 hackbod)所述,Google 工程师不推荐这种方法在此StackOverflow 帖子中。 查看这篇博文< /a> 了解更多信息。
您必须将其添加到清单中的活动声明中:
所以看起来像
这样,问题是当配置发生更改时系统会销毁该活动。 请参阅ConfigurationChanges。
因此,将其放入配置文件中可以避免系统破坏您的活动。 相反,它会调用
onConfigurationChanged(Configuration)
方法。Edit: Google engineers do not recommend this approach, as described by Dianne Hackborn (a.k.a. hackbod) in this StackOverflow post. Check out this blog post for more information.
You have to add this to the activity declaration in the manifest:
so it looks like
The matter is that the system destroys the activity when a change in the configuration occurs. See ConfigurationChanges.
So putting that in the configuration file avoids the system to destroy your activity. Instead it invokes the
onConfigurationChanged(Configuration)
method.当你切换方向时,Android 将创建一个新的视图。 您可能会崩溃,因为您的后台线程正在尝试更改旧线程的状态。 (它也可能遇到麻烦,因为你的后台线程不在 UI 线程上)
我建议使该 mHandler 可变并在方向更改时更新它。
When you switch orientations, Android will create a new View. You're probably getting crashes because your background thread is trying to change the state on the old one. (It may also be having trouble because your background thread isn't on the UI thread)
I'd suggest making that mHandler volatile and updating it when the orientation changes.
我针对这些问题提出了一个符合“Android 方式”的可靠解决方案。 我所有长时间运行的操作都使用 IntentService 模式。
也就是说,我的活动广播意图,IntentService 完成工作,将数据保存在数据库中,然后广播粘性意图。 粘性部分很重要,这样即使 Activity 在用户启动工作后的时间内暂停并错过了来自 IntentService 的实时广播,我们仍然可以响应并从调用 Activity 中获取数据。
ProgressDialog
可以通过onSaveInstanceState()
很好地处理这种模式。基本上,您需要保存一个标志,表明您在保存的实例包中运行了进度对话框。 不要保存进度对话框对象,因为这会泄漏整个 Activity。 为了获得进度对话框的持久句柄,我将其作为弱引用存储在应用程序对象中。 在方向更改或其他导致活动暂停(电话、用户回家等)然后恢复的情况下,我会关闭旧对话框并在新创建的活动中重新创建新对话框。
对于不确定进度对话框,这很容易。 对于进度条样式,您必须将最后已知的进度放入包中,以及您在活动中本地使用的任何信息来跟踪进度。 在恢复进度时,您将使用此信息以与之前相同的状态重新生成进度条,然后根据当前状态进行更新。
总而言之,将长时间运行的任务放入 IntentService 中并明智地使用 onSaveInstanceState() 可以让您有效地跟踪对话框并在整个 Activity 生命周期事件中进行恢复。 活动代码的相关部分如下。 您还需要 BroadcastReceiver 中的逻辑来适当处理粘性意图,但这超出了本文的范围。
I came up with a rock-solid solution for these issues that conforms with the 'Android Way' of things. I have all my long-running operations using the IntentService pattern.
That is, my activities broadcast intents, the IntentService does the work, saves the data in the DB and then broadcasts sticky intents. The sticky part is important, such that even if the Activity was paused during during the time after the user initiated the work and misses the real time broadcast from the IntentService we can still respond and pick up the data from the calling Activity.
ProgressDialog
s can work with this pattern quite nicely withonSaveInstanceState()
.Basically, you need to save a flag that you have a progress dialog running in the saved instance bundle. Do not save the progress dialog object because this will leak the entire Activity. To have a persistent handle to the progress dialog, I store it as a weak reference in the application object. On orientation change or anything else that causes the Activity to pause (phone call, user hits home etc.) and then resume, I dismiss the old dialog and recreate a new dialog in the newly created Activity.
For indefinite progress dialogs this is easy. For progress bar style, you have to put the last known progress in the bundle and whatever information you're using locally in the activity to keep track of the progress. On restoring the progress, you'll use this information to re-spawn the progress bar in the same state as before and then update based on the current state of things.
So to summarize, putting long-running tasks into an IntentService coupled with judicious use of
onSaveInstanceState()
allows you to efficiently keep track of dialogs and restore then across the Activity life-cycle events. Relevant bits of Activity code are below. You'll also need logic in your BroadcastReceiver to handle Sticky intents appropriately, but that is beyond the scope of this.我遇到了同样的问题。 我的活动需要从 URL 解析一些数据,但速度很慢。 因此,我创建一个线程来执行此操作,然后显示一个进度对话框。 我让线程在完成时通过
Handler
将消息发送回 UI 线程。 在 Handler.handleMessage 中,我从线程获取数据对象(现已准备好)并将其填充到 UI。 所以它与你的例子非常相似。经过多次尝试和错误,我似乎找到了解决方案。 至少现在我可以在线程完成之前或之后随时旋转屏幕。 在所有测试中,对话框均已正确关闭并且所有行为均符合预期。
我所做的如下所示。 目标是填充我的数据模型 (
mDataObject
),然后将其填充到 UI。 应该允许屏幕随时旋转,不会出现意外。这对我有用。 我不知道这是否是 Android 设计的“正确”方法——他们声称这种“在屏幕旋转期间销毁/重新创建活动”实际上使事情变得更容易,所以我想这应该不会太棘手。
如果您在我的代码中发现问题,请告诉我。 楼上说了,不知道有没有副作用。
I met the same problem. My activity needs to parse some data from a URL and it's slow. So I create a thread to do so, then show a progress dialog. I let the thread post a message back to UI thread via
Handler
when it's finished. InHandler.handleMessage
, I get the data object (ready now) from thread and populate it to UI. So it's very similar to your example.After a lot of trial and error it looks like I found a solution. At least now I can rotate screen at any moment, before or after the thread is done. In all tests, the dialog is properly closed and all behaviors are as expected.
What I did is shown below. The goal is to fill my data model (
mDataObject
) and then populate it to UI. Should allow screen rotation at any moment without surprise.That's what works for me. I don't know if this is the "correct" method as designed by Android -- they claim this "destroy/recreate activity during screen rotation" actually makes things easier, so I guess it shouldn't be too tricky.
Let me know if you see a problem in my code. As said above I don't really know if there is any side effect.
最初发现的问题是代码无法在屏幕方向更改后继续存在。 显然,这是通过让程序自行处理屏幕方向更改来“解决”的,而不是让 UI 框架来处理(通过调用 onDestroy))。
我认为,如果根本问题是程序无法在 Destroy() 上生存,那么接受的解决方案只是一种解决方法,使程序面临严重的其他问题和漏洞。 请记住,Android 框架明确指出,由于您无法控制的情况,您的活动几乎随时都有被破坏的风险。 因此,您的 Activity 必须能够因任何原因而在 onDestroy() 和后续的 onCreate() 中生存,而不仅仅是屏幕方向更改。
如果您打算自己接受处理屏幕方向更改来解决 OP 的问题,则需要验证 onDestroy() 的其他原因不会导致相同的错误。 你能做到吗? 如果不是,我会质疑“接受”的答案是否真的是一个非常好的答案。
The original perceived problem was that the code would not survive a screen orientation change. Apparently this was "solved" by having the program handle the screen orientation change itself, instead of letting the UI framework do it (via calling onDestroy)).
I would submit that if the underlying problem is that the program will not survive onDestroy(), then the accepted solution is just a workaround that leaves the program with serious other problems and vulnerabilities. Remember that the Android framework specifically states that your activity is at risk for being destroyed almost at any time due to circumstances outside your control. Therefore, your activity must be able to survive onDestroy() and subsequent onCreate() for any reason, not just a screen orientation change.
If you are going to accept handling screen orientation changes yourself to solve the OP's problem, you need to verify that other causes of onDestroy() do not result in the same error. Are you able to do this? If not, I would question whether the "accepted" answer is really a very good one.
我的解决方案是扩展
ProgressDialog
类以获得我自己的MyProgressDialog
。我重新定义了
show()
和dismiss()
方法在显示Dialog
之前锁定方向,并在Dialog
关闭时将其解锁。因此,当显示
Dialog
并且设备方向发生变化时,屏幕方向保持不变,直到调用dismiss()
,然后屏幕方向根据传感器发生变化价值观/设备导向。这是我的代码:
My solution was to extend the
ProgressDialog
class to get my ownMyProgressDialog
.I redefined
show()
anddismiss()
methods to lock the orientation before showing theDialog
and unlock it back whenDialog
is dismissed.So when the
Dialog
is shown and the orientation of the device changes, the orientation of the screen remains untildismiss()
is called, then screen-orientation changes according to sensor-values/device-orientation.Here is my code:
我遇到了同样的问题,我想出了一个不涉及使用 ProgressDialog 的解决方案,并且我得到了更快的结果。
我所做的是创建一个其中包含进度条的布局。
然后在 onCreate 方法中执行以下
操作然后在线程中执行长任务,完成后将 Runnable 设置为要用于此活动的实际布局的内容视图。
例如:
这就是我所做的,我发现它比显示 ProgressDialog 运行得更快,而且在我看来它的侵入性更小并且外观更好。
但是,如果您想使用 ProgressDialog,那么这个答案不适合您。
I faced this same problem, and I came up with a solution that didn't invole using the ProgressDialog and I get faster results.
What I did was create a layout that has a ProgressBar in it.
Then in the onCreate method do the following
Then do the long task in a thread, and when that's finished have a Runnable set the content view to the real layout you want to use for this activity.
For example:
This is what I did, and I've found that it runs faster than showing the ProgressDialog and it's less intrusive and has a better look in my opinion.
However, if you're wanting to use the ProgressDialog, then this answer isn't for you.
我发现了一个我在其他地方还没有见过的解决方案。 您可以使用自定义应用程序对象,该对象知道您是否有后台任务正在进行,而不是尝试在方向更改时被销毁并重新创建的活动中执行此操作。 我在此处发表了有关此内容的博客。
I discovered a solution to this that I haven't yet seen elsewhere. You can use a custom application object that knows if you have background tasks going, instead of trying to do this in the activity that gets destroyed and recreated on orientation change. I blogged about this in here.
我将贡献我的方法来处理这个轮换问题。 这可能与 OP 无关,因为他没有使用
AsyncTask
,但也许其他人会发现它很有用。 它非常简单,但似乎适合我:我有一个登录活动,其中包含一个名为
BackgroundLoginTask
的嵌套AsyncTask
类。在我的
BackgroundLoginTask
中,除了在调用ProgressDialog
的关闭时添加空检查之外,我没有做任何异常的事情:这是为了处理后台任务的情况当
Activity
不可见时完成,因此,进度对话框已被onPause()
方法关闭。接下来,在我的父
Activity
类中,我为我的AsyncTask
类和我的ProgressDialog
(AsyncTask
>,嵌套,可以访问这些变量):这有两个目的:首先,它允许我的
Activity
始终访问AsyncTask
对象,即使是从新的、后轮换的对象活动。 其次,它允许我的BackgroundLoginTask
即使在旋转后也可以访问和关闭ProgressDialog
。接下来,我将其添加到
onPause()
中,导致当我们的Activity
离开前台时进度对话框消失(防止丑陋的“强制关闭”崩溃):最后,我的
onResume()
方法中有以下内容:这允许
Dialog
在重新创建Activity
后重新出现。以下是整个课程:
我绝不是经验丰富的 Android 开发人员,所以请随意发表评论。
I going to contribute my approach to handling this rotation issue. This may not be relevant to OP as he's not using
AsyncTask
, but maybe others will find it useful. It's pretty simple but it seems to do the job for me:I have a login activity with a nested
AsyncTask
class calledBackgroundLoginTask
.In my
BackgroundLoginTask
I don't do anything out of the ordinary except to add a null check upon callingProgressDialog
's dismiss:This is to handle the case where the background task finishes while the
Activity
is not visible and, therefore, the progress dialog has already been dismissed by theonPause()
method.Next, in my parent
Activity
class, I create global static handles to myAsyncTask
class and myProgressDialog
(theAsyncTask
, being nested, can access these variables):This serves two purposes: First, it allows my
Activity
to always access theAsyncTask
object even from a new, post-rotated activity. Second, it allows myBackgroundLoginTask
to access and dismiss theProgressDialog
even after a rotate.Next, I add this to
onPause()
, causing the progress dialog to disappear when ourActivity
is leaving the foreground (preventing that ugly "force close" crash):Finally, I have the following in my
onResume()
method:This allows the
Dialog
to reappear after theActivity
is recreated.Here is the entire class:
I am by no means a seasoned Android developer, so feel free to comment.
将长任务移至单独的类中。 将其实现为主体-观察者模式。 每当创建活动时,都会向任务类注册并在关闭时取消注册。 任务类可以使用AsyncTask。
Move the long task to a seperate class. Implement it as a subject-observer pattern. Whenever the activity is created register and while closing unregister with the task class. Task class can use AsyncTask.
技巧是像往常一样在 onPreExecute/onPostExecute 期间显示/关闭 AsyncTask 中的对话框,但在方向更改的情况下,在活动中创建/显示对话框的新实例并将其引用传递给任务。
The trick is to show/dismiss the dialog within AsyncTask during onPreExecute/onPostExecute as usual, though in case of orientation-change create/show a new instance of the dialog in the activity and pass its reference to the task.
我已经这样做了。 代码改编自 Android使用处理程序、AsyncTask 和加载器进行后台处理 - Lars Vogel 的教程:
您也可以尝试让我知道它是否适合您
I have done it like this. The code is adapted from Android Background Processing with Handlers and AsyncTask and Loaders - Tutorial by Lars Vogel:
You can also try and let me know it works for you or not
这是我建议的解决方案:
void showProgressDialog()
方法添加到片段活动侦听器接口中。This is my proposed solution:
void showProgressDialog()
method can be added to the fragment-activity listener interface for this purpose.这是一个非常古老的问题,由于某种原因出现在侧边栏上。
如果后台任务只需要在 Activity 位于前台时生存,则“新”解决方案是将后台线程(或者最好是
AsyncTask
)托管在保留片段中strong>,如本开发人员指南和大量问答。如果活动因配置更改而被销毁,则保留的片段将继续存在,但如果活动在后台或返回堆栈中被销毁,则保留的片段不会继续存在。 因此,如果
isChangingConfigurations,后台任务仍应被中断()
在onPause()
中为 false。This is a very old question that came up on the sidebar for some reason.
If the background task only needs to survive while the activity is in the foreground, the "new" solution is to host the background thread (or, preferably,
AsyncTask
) in a retained fragment, as described in this developer guide and numerous Q&As.A retained fragment survives if the activity is destroyed for a configuration change, but not when the activity is destroyed in the background or back stack. Therefore, the background task should still be interrupted if
isChangingConfigurations()
is false inonPause()
.如果您创建一个后台
Service
所有繁重的工作(tcp 请求/响应、解组)、View
和Activity
都可以被销毁并重新创建,而不会泄漏窗口或丢失数据。 这允许 Android 推荐的行为,即在每次配置更改时销毁 Activity (例如,对于每个方向变化)。它有点复杂,但它是调用服务器请求、数据预处理/后处理等的最佳方式。
您甚至可以使用
Service
将每个请求排队到服务器,因此它使处理这些事情变得简单而高效。开发指南有一个关于
服务
的完整章节。If you create a background
Service
that does all the heavy lifting (tcp requests/response, unmarshalling), theView
andActivity
can be destroyed and re-created without leaking window or losing data. This allows the Android recommended behavior, which is to destroy an Activity on each configuration change (eg. for each orientation change).It is a bit more complex, but it is the best way for invoking server request, data pre/post-processing, etc.
You may even use your
Service
to queue each request to a server, so it makes it easy and efficient to handle those things.The dev guide has a full chapter on
Services
.我有一个实现,允许在屏幕方向更改时销毁活动,但仍然成功地销毁重新创建的活动中的对话框。
我使用
...NonConfigurationInstance
将后台任务附加到重新创建的活动。普通的 Android 框架负责重新创建对话框本身,没有任何改变。
我对 AsyncTask 进行了子类化,添加了“拥有”活动的字段以及更新此所有者的方法。
在我的活动类中,我添加了一个引用“拥有的”backgroundtask 的字段
backgroundTask
,并使用onRetainNonConfigurationInstance
和getLastNonConfigurationInstance
更新该字段。进一步改进的建议:
backgroundTask
引用,以释放与其关联的任何内存或其他资源。ownerActivity
引用,以防它不会立即重新创建。BackgroundTask
接口和/或集合,以允许不同类型的任务从同一所属活动运行。I have an implementation which allows the activity to be destroyed on a screen orientation change, but still destroys the dialog in the recreated activity successfully.
I use
...NonConfigurationInstance
to attach the background task to the recreated activity.The normal Android framework handles recreating the dialog itself, nothing is changed there.
I subclassed AsyncTask adding a field for the 'owning' activity, and a method to update this owner.
In my activity class I added a field
backgroundTask
referring to the 'owned' backgroundtask, and I update this field usingonRetainNonConfigurationInstance
andgetLastNonConfigurationInstance
.Suggestions for further improvement:
backgroundTask
reference in the activity after the task is finished to release any memory or other resources associated with it.ownerActivity
reference in the backgroundtask before the activity is destroyed in case it will not be recreated immediately.BackgroundTask
interface and/or collection to allow different types of tasks to run from the same owning activity.如果维护两个布局,则所有 UI 线程都应终止。
如果您使用AsynTask,那么您可以轻松地在当前活动的
onDestroy()
方法中调用.cancel()
方法。对于 AsyncTask,请阅读此处的“取消任务”部分的更多信息。
更新:
添加了检查状态的条件,因为只有处于运行状态才能取消。
另请注意,AsyncTask 只能执行一次。
If you maintain two layouts, all UI thread should be terminated.
If you use AsynTask, then you can easily call
.cancel()
method insideonDestroy()
method of current activity.For AsyncTask, read more in "Cancelling a task" section at here.
Update:
Added condition to check status, as it can be only cancelled if it is in running state.
Also note that the AsyncTask can only be executed one time.
尝试实施jfelectron的解决方案,因为它是“针对这些问题的坚如磐石的解决方案,符合‘Android Way’事物”,但花了一些时间查找并将所有提到的元素放在一起。 最终得到了这个稍微不同的、我认为更优雅的解决方案,完整地发布在这里。
使用从活动激发的 IntentService 在单独的线程上执行长时间运行的任务。 该服务将粘性广播意图触发到更新对话框的活动。 Activity 使用showDialog()、onCreateDialog() 和onPrepareDialog() 来消除在应用程序对象或savedInstanceState 包中传递持久数据的需要。 无论您的应用程序如何中断,这都应该有效。
活动类:
IntentService 类:
清单文件条目:
应用程序部分之前:
应用程序部分内部
Tried to implement jfelectron's solution because it is a "rock-solid solution to these issues that conforms with the 'Android Way' of things" but it took some time to look up and put together all the elements mentioned. Ended up with this slightly different, and I think more elegant, solution posted here in it's entirety.
Uses an IntentService fired from an activity to perform the long running task on a separate thread. The service fires back sticky Broadcast Intents to the activity which update the dialog. The Activity uses showDialog(), onCreateDialog() and onPrepareDialog() to eliminate the need to have persistent data passed in the application object or the savedInstanceState bundle. This should work no matter how your application is interrupted.
Activity Class:
IntentService Class:
Manifest file entries:
before application section:
inside application section
我也面临着同样的情况。 我所做的只是在整个应用程序中为我的进度对话框获取一个实例。
首先,我创建了一个 DialogSingleton 类来仅获取一个实例(单例模式),
正如我在此类中所示,我将进度对话框作为属性。 每次我需要显示进度对话框时,我都会获取唯一的实例并创建一个新的 ProgressDialog。
当我完成后台任务时,我再次调用唯一实例并关闭其对话框。
我将后台任务状态保存在我的共享首选项中。 当我旋转屏幕时,我会询问是否有为此活动运行的任务:(onCreate)
当我开始运行后台任务时:
当我完成运行后台任务时:
我希望它有帮助。
I faced the same situation. What I did was get only one instance for my progress dialog in the entire application.
First, I created a DialogSingleton class to get only one instance (Singleton pattern)
As I show in this class, I have the progress dialog as attribute. Every time I need to show a progress dialog, I get the unique instance and create a new ProgressDialog.
When I am done with the background task, I call again the unique instance and dismiss its dialog.
I save the background task status in my shared preferences. When I rotate the screen, I ask if I have a task running for this activity: (onCreate)
When I start running a background task:
When I finish running a background task:
I hope it helps.
我是android新手,我尝试过这个并且它有效。
I am a fresher in android and I tried this and it's worked.
我已经尝试了一切。 花了几天时间进行实验。 我不想阻止活动轮换。 我的场景是:
问题是,当旋转屏幕时,书中的每个解决方案都失败了。 即使使用 AsyncTask 类,这也是 Android 处理这种情况的正确方法。 旋转屏幕时,启动线程正在使用的当前上下文消失了,这会扰乱正在显示的对话框。 问题始终是对话框,无论我在代码中添加了多少技巧(将新上下文传递给正在运行的线程,通过旋转保留线程状态等......)。 最后的代码复杂度总是很大,而且总有可能出错的地方。
对我有用的唯一解决方案是活动/对话框技巧。 它简单而天才,而且都是旋转证明:
不要创建一个对话框并要求显示它,而是创建一个已在清单中使用 android:theme="@android:style/Theme.Dialog" 设置的 Activity。 因此,它看起来就像一个对话框。
将 showDialog(DIALOG_ID) 替换为 startActivityForResult(yourActivityDialog, yourCode);
在调用 Activity 中使用 onActivityResult 从执行线程获取结果(甚至包括错误)并更新 UI。
在“ActivityDialog”上,使用线程或 AsyncTask 执行长任务,并使用 onRetainNonConfigurationInstance 在旋转屏幕时保存“对话框”状态。
这很快并且工作正常。 我仍然使用对话框来执行其他任务,并使用 AsyncTask 来执行不需要在屏幕上持续显示对话框的任务。 但在这种情况下,我总是选择活动/对话框模式。
而且,我没有尝试过,但当线程运行时,甚至可以阻止该活动/对话框旋转,从而加快速度,同时允许调用活动旋转。
I've tried EVERYTHING. Spent days experimenting. I didn't want to block the activity from rotating. My scenario was:
The problem was, when rotating the screen, every solution on the book failed. Even with the AsyncTask class, which is the correct Android way of dealing with this situations. When rotating the screen, the current Context that the starting thread is working with, is gone, and that messes up with the dialog that is showing. The problem was always the Dialog, no matter how many tricks I added to the code (passing new contexts to running threads, retaining thread states through rotations, etc...). The code complexity at the end was always huge and there was always something that could go wrong.
The only solution that worked for me was the Activity/Dialog trick. It's simple and genius and it's all rotation proof:
Instead of creating a Dialog and ask to show it, create an Activity that has been set in the manifest with android:theme="@android:style/Theme.Dialog". So, it just looks like a dialog.
Replace showDialog(DIALOG_ID) with startActivityForResult(yourActivityDialog, yourCode);
Use onActivityResult in the calling Activity to get the results from the executing thread (even the errors) and update the UI.
On your 'ActivityDialog', use threads or AsyncTask to execute long tasks and onRetainNonConfigurationInstance to save "dialog" state when rotating the screen.
This is fast and works fine. I still use dialogs for other tasks and the AsyncTask for something that doesn't require a constant dialog on screen. But with this scenario, I always go for the Activity/Dialog pattern.
And, I didn't try it, but it's even possible to block that Activity/Dialog from rotating, when the thread is running, speeding things up, while allowing the calling Activity to rotate.
如今,有一种更独特的方法来处理这些类型的问题。 典型的方法是:
1. 确保您的数据与 UI 正确分离:
任何后台进程都应该位于保留的
Fragment
中(使用Fragment.setRetainInstance()
设置此值)这将成为您的“持久数据存储”,其中保留您想要保留的任何数据。在方向更改事件之后,此Fragment
仍可通过以其原始状态进行访问。 您应该给它一个标签而不是 ID,因为它没有附加到
View
)。>FragmentManager.findFragmentByTag() 调用(当您创建它时, 处理运行时更改开发指南,了解有关执行操作的信息这是正确的,以及为什么它是最佳选择。
2. 确保您在后台进程和 UI 之间正确且安全地连接:
您必须反转您的链接过程。 目前,您的后台进程将自身附加到
View
- 相反,您的View
应该将自身附加到后台进程。 这更有意义吧?View
的操作依赖于后台进程,而后台进程不依赖于View
。这意味着将链接更改为标准Listener< /代码> 接口。 假设您的进程(无论它是什么类 - 无论是 AsyncTask、Runnable 还是其他)定义了一个 OnProcessFinishedListener,当进程完成时如果存在的话应该调用该监听器。
这个答案是关于如何进行自定义侦听器的简洁描述。
3. 无论何时创建 UI(包括方向更改),都将 UI 链接到数据进程:
现在,您必须担心后台任务与当前
View
结构的接口。 如果您正确处理方向更改(而不是人们总是推荐的configChanges
hack),那么系统将重新创建您的Dialog
。 这很重要,这意味着在方向改变时,所有Dialog
的生命周期方法都会被调用。 因此,在任何这些方法中(onCreateDialog
通常是一个好地方),您可以执行如下调用:请参阅 片段生命周期,用于确定在您的个人实现中最适合设置侦听器的位置。
这是为该问题中提出的一般问题提供稳健且完整的解决方案的通用方法。 根据您的具体情况,此答案中可能缺少一些小部分,但这通常是正确处理方向更改事件的最正确方法。
These days there is a much more distinct way to handle these types of issues. The typical approach is:
1. Ensure your data is properly seperated from the UI:
Anything that is a background process should be in a retained
Fragment
(set this withFragment.setRetainInstance()
. This becomes your 'persistent data storage' where anything data based that you would like retained is kept. After the orientation change event, thisFragment
will still be accessible in its original state through aFragmentManager.findFragmentByTag()
call (when you create it you should give it a tag not an ID as it is not attached to aView
).See the Handling Runtime Changes developed guide for information about doing this correctly and why it is the best option.
2. Ensure you are interfacing correctly and safely between the background processs and your UI:
You must reverse your linking process. At the moment your background process attaches itself to a
View
- instead yourView
should be attaching itself to the background process. It makes more sense right? TheView
's action is dependent on the background process, whereas the background process is not dependent on theView
.This means changing the link to a standardListener
interface. Say your process (whatever class it is - whether it is anAsyncTask
,Runnable
or whatever) defines aOnProcessFinishedListener
, when the process is done it should call that listener if it exists.This answer is a nice concise description of how to do custom listeners.
3. Link your UI into the data process whenever the UI is created (including orientation changes):
Now you must worry about interfacing the background task with whatever your current
View
structure is. If you are handling your orientation changes properly (not theconfigChanges
hack people always recommend), then yourDialog
will be recreated by the system. This is important, it means that on the orientation change, all yourDialog
's lifecycle methods are recalled. So in any of these methods (onCreateDialog
is usually a good place), you could do a call like the following:See the Fragment lifecycle for deciding where setting the listener best fits in your individual implementation.
This is a general approach to providing a robust and complete solution to the generic problem asked in this question. There is probably a few minor pieces missing in this answer depending on your individual scenario, but this is generally the most correct approach for properly handling orientation change events.
我找到了更简单的解决方案来处理方向变化时的线程。 您可以只保留对活动/片段的静态引用,并在对用户界面进行操作之前验证其是否为空。 我建议也使用 try catch:
i have found and easier solution to handle threads when orientation change. You can just keep an static reference to your activity/fragment and verify if its null before acting on the ui. I suggest using a try catch too:
如果您正在努力检测对话框的方向变化事件独立于活动引用,那么此方法效果非常好。 我使用这个是因为我有自己的对话框类,可以在多个不同的 Activity 中显示,所以我并不总是知道它在哪个 Activity 中显示。使用此方法,您不需要更改 AndroidManifest,也不必担心 Activity 引用,并且您不需要自定义对话框(就像我一样)。 但是,您确实需要自定义内容视图,以便可以使用该特定视图检测方向变化。 这是我的示例:
设置
实现 1 - 对话框
实现 2 - AlertDialog.Builder
实现 3 - ProgressDialog / AlertDialog
If you're struggling with detecting orientation change events of a dialog INDEPENDENT OF AN ACTIVITY REFERENCE, this method works excitingly well. I use this because I have my own dialog class that can be shown in multiple different Activities so I don't always know which Activity it's being shown in. With this method you don't need to change the AndroidManifest, worry about Activity references, and you don't need a custom dialog (as I have). You do need, however, a custom content view so you can detect the orientation changes using that particular view. Here's my example:
Setup
Implementation 1 - Dialog
Implementation 2 - AlertDialog.Builder
Implementation 3 - ProgressDialog / AlertDialog
这是我遇到这个问题时的解决方案:
ProgressDialog
不是Fragment
子级,因此我的自定义类“ProgressDialogFragment
”可以扩展DialogFragment
以保留显示配置更改的对话框。有两种方法可以解决此问题:
第一种方法:
让活动利用对话框在清单文件中的配置更改期间保留状态:
Google 不喜欢这种方法。
第二种方法:
在活动的
onCreate()
方法上,您需要通过使用标题和标题再次重建ProgressDialogFragment
来保留您的DialogFragment
。 如果savedInstanceState
不为 null,则消息如下:This is my solution when I faced it:
ProgressDialog
is not aFragment
child, so my custom class "ProgressDialogFragment
" can extendDialogFragment
instead in order to keep the dialog shown for configuration changes.There are 2 approaches to solve this:
First approach:
Make the activity that utilizes the dialog to retain state during config change in manifest file:
This approach is not preferred by Google.
Second approach:
on the activity's
onCreate()
method, you need to retain yourDialogFragment
by rebuilding theProgressDialogFragment
again with the title & message as follows if thesavedInstanceState
is not null:似乎太“快速和肮脏”,不可能是真的,所以请指出缺陷,但我发现有效的是......
在我的 AsyncTask 的 onPostExecute 方法中,我只是将进度对话框的“.dismiss”包装在 try/ 中catch 块(带有空 catch),然后简单地忽略引发的异常。 似乎这样做是错误的,但似乎没有任何不良影响(至少对于我随后所做的事情来说,即启动另一个活动,将我长时间运行的查询的结果作为额外传递)
Seems far too 'quick and dirty' to be true so please point out the flaws but what I found worked was...
Within the onPostExecute method of my AsyncTask, I simply wrapped the '.dismiss' for the progress dialog in a try/catch block (with an empty catch) and then simply ignored the exception that was raised. Seems wrong to do but appears there are no ill effects (at least for what I am doing subsequently which is to start another activity passing in the result of my long running query as an Extra)
最简单、最灵活的解决方案是使用带有静态引用的 AsyncTask到 ProgressBar。 这为方向改变问题提供了封装且可重复使用的解决方案。 该解决方案非常适合各种异步任务,包括互联网下载、与 服务 通信和文件系统扫描。 该解决方案已在多个 Android 版本和手机型号上经过充分测试。 可以在此处找到完整的演示,特别感兴趣的是DownloadFile.java
我提出以下内容作为一个概念示例,
在 Android Activity 中的使用很简单
The simplest and most flexible solution is to use an AsyncTask with a static reference to ProgressBar. This provides an encapsulated and thus reusable solution to orientation change problems. This solution has served me well for varying asyncronous tasks including internet downloads, communicating with Services, and filesystem scans. The solution has been well tested on multiple android versions and phone models. A complete demo can be found here with specific interest in DownloadFile.java
I present the following as a concept example
Usage in an Android Activity is simple
当您改变方向时,Android 会终止该 Activity 并创建新的 Activity。
我建议使用 Rx java 进行改造。 哪个手柄会自动崩溃。
当改造调用时使用这些方法。
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
When you change orientations , Android kill that activity and created new activity .
I suggest to use retrofit with Rx java . which handle crashes automatically .
Use these method when retrofit call.
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())