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

前端 未结 28 1611
轮回少年
轮回少年 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条回答
  •  孤城傲影
    2020-11-22 07:56

    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.

    public class MainActivity extends Activity {
        private Button mButton;
        private MyTask mTask = null;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            MyTask task = (MyTask) getLastNonConfigurationInstance();
            if(task != null){
                mTask = task;
                mTask.mContext = this;
                mTask.mDialog = ProgressDialog.show(this, "", "", true);        
            }
    
            mButton = (Button) findViewById(R.id.button1);
            mButton.setOnClickListener(new View.OnClickListener(){
                public void onClick(View v){
                    mTask = new MyTask(MainActivity.this);
                    mTask.execute();
                }
            });
        }
    
    
        @Override
        public Object onRetainNonConfigurationInstance() {
            String str = "null";
            if(mTask != null){
                str = mTask.toString();
                mTask.mDialog.dismiss();
            }
            Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
            return mTask;
        }
    
    
    
        private class MyTask extends AsyncTask{
            private ProgressDialog mDialog;
            private MainActivity mContext;
    
    
            public MyTask(MainActivity context){
                super();
                mContext = context;
            }
    
    
            protected void onPreExecute() {
                mDialog = ProgressDialog.show(MainActivity.this, "", "", true);
            }
    
            protected void onPostExecute(Void result) {
                mContext.mTask = null;
                mDialog.dismiss();
            }
    
    
            @Override
            protected Void doInBackground(Void... params) {
                SystemClock.sleep(5000);
                return null;
            }       
        }
    }
    

提交回复
热议问题