ListAdapter lifecycle and screen rotation for canceling a AsyncTask

本小妞迷上赌 提交于 2019-12-11 23:06:55

问题


I have a asynctask that I cancel when the view is destoried via onDestoryView(). This problem is I do "downloader.cancel(true);" and it wont cancel. In fact, it will return false. Currently, it references the ListAdapter to add items to it. However when I turn the screen to landscape, the ListAdapter is null during the onPostExecute. I cannot figure out when the ListAdapter becomes null. I have tried both onDestory and onDestoryView to cancel the asynctask before the ListAdapter becomes null but it never works. This is inside of a ListFragment btw.

For the time being, I just check if the adapter is null in the asynctask but this really grinds my gears. I would rather just cancel the task before the ListAdapter is null.

Does anyone know when the ListAdapter is null for a ListFragment during screen rotations?


回答1:


Cancelling an AsyncTask does not kill the Thread. You will see in the docs for Thread that methods like stop and destroy are unimplemented. So once the doInBackground method starts executing, it will run to completion even if the task is cancelled with cancel(true). You will need to code it appropriately.




回答2:


When the screen orientation is changed the default behavior is destroy the Activity and recreate it. So the methods OnDestroy, and OnCreate will be called. You can cancel this behavior adding this line in the activity that of your your Manifest:

android:configChanges="keyboardHidden|orientation"

Like that:

    <activity
        android:name=".YourActivity"
        android:label="@string/app_name"
        android:configChanges="keyboardHidden|orientation" >

You also needs to add the method onConfigurationChanged in your activity class.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig); // tem que ter

    reconfiguraInterface();
}

After that OnDestroy and OnCreate will not be called when orientation changes.



来源:https://stackoverflow.com/questions/9119741/listadapter-lifecycle-and-screen-rotation-for-canceling-a-asynctask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!