简体   繁体   English

防止定向变化时破坏后台活动

[英]Stop background activity from being destroyed on orientationchange

So I have an Activity that handles all my web-service calls. 因此,我有一个“活动”来处理我所有的Web服务调用。 Whenever an activity needs information from the internet I start it and it runs the download code while displaying a loader for the user. 每当一项活动需要互联网上的信息时,我都会启动该活动,并在为用户显示加载程序的同时运行下载代码。

My problem is that if the user changes orientation (portrait to landscape or vice versa) the activity that requested the download is destroyed and recreated (as is any other activities in the backstack i assume?). 我的问题是,如果用户更改方向(纵向改为横向,反之亦然),则请求下载的活动将被销毁并重新创建(我认为像在堆栈中的其他活动一样吗?)。 Ive added the android:configChanges="orientation|screenSize" to my loading-activity to ignore the orientation-changes for the loading-activity but first of all it doesnt seem to work (the orientation changes anyway?) and the calling activity is also destroyed and recreated (causing it to start a new loading-activity requesting results). 我已经在我的加载活动中添加了android:configChanges =“ orientation | screenSize”来忽略加载活动的方向更改,但首先它似乎不起作用(方向是否有所改变?),并且调用活动也是销毁并重新创建(使其开始请求结果的新的加载活动)。

What I want to achieve is to stop any orientation-changes while the loading-activity is the active one. 我要实现的是在加载活动处于活动状态时停止任何方向更改。

EDIT: My activity in the manifest: 编辑:我在清单中的活动:

<activity
android:name=".LoadingActivity"
android:theme="@style/LoadingTheme"
android:configChanges="orientation|screenSize" >

And my activity (LoadingActivity) have overriden: 我的活动(LoadingActivity)已被覆盖:

 @Override 
    public void onConfigurationChanged(Configuration newConfig) { 
      //ignore orientation change 
     Log.d("LoadingActivity","Ignoring config change");
      super.onConfigurationChanged(newConfig); 
    } 

I noticed that the LoadingActiviy isnt actually destroyed but only the other Activities in the backstack. 我注意到,LoadingActiviy实际上并没有被销毁,而只有后栈中的其他活动被销毁了。

I solved it by creating a boolean in all activities using LoadingActivity called WaitingForResults, that way when the activity is created, if its true I dont make another call to retrieve data from the server (because LoadingActivity will correctly deliver the result to the re-created activity). 我通过使用LoadingActivity在所有活动中创建一个布尔值(即WaitingForResults)来解决了该问题,那样在创建活动时,如果它为真,我就不会再调用一次从服务器检索数据了(因为LoadingActivity将正确地将结果传递给重新创建的活动活动)。

If you already specified in the manifest that you will handle the orientationChanges, and you don't want the activity to go through the regular life cycle, seems like all you are missing is to override this method in your activity as shown below: 如果您已经在清单中指定了将要处理directionChanges,并且您不希望该活动经历常规的生命周期,那么似乎所缺少的就是在活动中覆盖此方法,如下所示:

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(null);
}

Hope it Helps! 希望能帮助到你!

Regards! 问候!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM