Run progress bar while switching Activity

后端 未结 4 1645
死守一世寂寞
死守一世寂寞 2020-12-20 08:16

im stuck in a situation where i am switching from activity 1 to activity 2. i am using Thread.sleep(5000) to start another activity after 5 seconds But the progress bar whic

4条回答
  •  一个人的身影
    2020-12-20 08:52

    Change your OnClickListener for this. This will not block your main thread, as you are doing (that explains why your application freezes for 5 seconds):

    next.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            new AsyncTask()
            {
                ProgressDialog pd;
    
                @Override
                protected Boolean doInBackground(Integer... params)
                {
                    pd = new ProgressDialog(Activity1.this);
                    pd.setTitle("Loading Activity");
                    pd.setMessage("Please Wait ...");
                    pd.setMax(params[0]);
                    pd.setIndeterminate(false);
                    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    
                    publishProgress(0L);
    
                    long start = System.currentTimeMillis();
                    long waitTime = params[0] * 1000;
                    try
                    {
                        while (System.currentTimeMillis() - start < waitTime)
                        {
                            Thread.sleep(500);
                            publishProgress(System.currentTimeMillis() - start);
                        }
                    }
                    catch (Exception e)
                    {
                        return false;
                    }
    
                    return true;
                }
    
                @Override
                protected void onProgressUpdate(Long... values)
                {
                    if (values[0] == 0)
                    {
                        pd.show();
                    }
                    else
                    {
                        pd.setProgress((int) (values[0] / 1000));
                    }
                }
    
                @Override
                protected void onPostExecute(Boolean result)
                {
                    pd.dismiss();
                    Intent myIntent = new Intent(view.getContext(), activity2.class);
                    startActivityForResult(myIntent, 0);
                }
            }.execute(5);
        });
    

提交回复
热议问题