How to display a loading screen while doing heavy computing in Android?

China☆狼群 提交于 2020-01-17 04:30:46

问题


I am working on a program that searches the users phone for some date, which takes about 2-3 seconds. While it's computing I want to display a loading screen, so the user knows something indeed is happening. However, when I try to display a loading screen before the computations, nothing is displayed on the screen.

This is what I have:

        ProgressDialog loading= new ProgressDialog(this);
        loading.setTitle("Loading");
        loading.setMessage("Please wait...");
        loading.show();

       //search stuff
        loading.dismiss();

In addition to this, I have tried putting the ProgressDialog in a thread like the following,

new Thread(new Runnable(){
            public void run(){
              ProgressDialog loading= new ProgressDialog(this);//error here for "this"
              loading.setTitle("Loading");
              loading.setMessage("Please wait...");
              loading.show();
            }
        });
//search stuff

but it fails due to the "this" keyword, I believe because its referring to an Activity and not a regular class, but I could be wrong...

How can I get the ProgressDialog to display properly?


回答1:


Try to handle it in this way

mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
        new Thread() {
            @Override
            public void run() {

               //Do long operation stuff here search stuff

                try {

                    // code runs in a thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                        }
                    });
                } catch (final Exception ex) {

                }
            }
        }.start();



回答2:


Use async task for heavy task. Put your progress dialog code in onPreExecute method progress dialog dismiss code in onPostExecute method and all your heavy task in doInBackground method.




回答3:


try passing down the context on a new class with your progress bar (this goes on your main activity)

NAME_OF_YOUR_CLASS context = new NAME_OF_YOUR_CLASS(getApplicationContext());

and on your class call the method like this..(this goes on class)

 public Networking(Context c) {
        this.context= c;
    }

dont forget to make context a field (private final Context context;)

hope this helps

also idk if this will work but try to extend AsyncTask and use methods to run your progress bar there.



来源:https://stackoverflow.com/questions/33470526/how-to-display-a-loading-screen-while-doing-heavy-computing-in-android

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