How to handle screen orientation change when progress dialog and background thread active?

前端 未结 28 1803
轮回少年
轮回少年 2020-11-22 07:03

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, exc

28条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 07:53

    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:

     public class DashListFragment extends Fragment {
         private static DashListFragment ACTIVE_INSTANCE;
    
         @Override
         public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            ACTIVE_INSTANCE = this;
    
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    try {
                            if (ACTIVE_INSTANCE != null) {
                                setAdapter(); // this method do something on ui or use context
                            }
                    }
                    catch (Exception e) {}
    
    
                }
            }, 1500l);
    
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
    
            ACTIVE_INSTANCE = null;
        }
    
    
    }
    

提交回复
热议问题