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

前端 未结 28 1258
轮回少年
轮回少年 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:49

    I have done it like this:

        package com.palewar;
        import android.app.Activity;
        import android.app.ProgressDialog;
        import android.os.Bundle;
        import android.os.Handler;
        import android.os.Message;
    
        public class ThreadActivity extends Activity {
    
    
            static ProgressDialog dialog;
            private Thread downloadThread;
            final static Handler handler = new Handler() {
    
                @Override
                public void handleMessage(Message msg) {
    
                    super.handleMessage(msg);
    
                    dialog.dismiss();
    
                }
    
            };
    
            protected void onDestroy() {
        super.onDestroy();
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                    dialog = null;
                }
    
            }
    
            /** Called when the activity is first created. */
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
    
                downloadThread = (Thread) getLastNonConfigurationInstance();
                if (downloadThread != null && downloadThread.isAlive()) {
                    dialog = ProgressDialog.show(ThreadActivity.this, "",
                            "Signing in...", false);
                }
    
                dialog = ProgressDialog.show(ThreadActivity.this, "",
                        "Signing in ...", false);
    
                downloadThread = new MyThread();
                downloadThread.start();
                // processThread();
            }
    
            // Save the thread
            @Override
            public Object onRetainNonConfigurationInstance() {
                return downloadThread;
            }
    
    
            static public class MyThread extends Thread {
                @Override
                public void run() {
    
                    try {
                        // Simulate a slow network
                        try {
                            new Thread().sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        handler.sendEmptyMessage(0);
    
                    } finally {
    
                    }
                }
            }
    
        }
    

    You can also try and let me know it works for you or not

提交回复
热议问题