java - 带进度对话框的异步任务

标签 java android

我知道有很多关于此问题的答案,但我找不到我真正需要的:

1)当用户点击按钮时,显示一个进度对话框;

2) 执行类 AsyncTask 并等待答案(这是使用 HTTPUrlConnection 的响应);

3) 关闭进度对话框;

我尝试了很多东西,但进度对话框没有“出现”。我的代码:

   public class MainActivity extends Activity implements OnTaskCompleted{
    ..
    private ProgressDialog progressDialog;
    private Button btnLogin;
    ..

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            btnLogin = (Button) findViewById(R.id.btnLogin);

            btnLogin.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    progressDialog = ProgressDialog.show(MainActivity.this,
                            "", "Scanning Please Wait", true);
                    try {
                         String param1 = "testParam1";
                         String param2 = "testParam2";
                                String response = new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2).get(); //this way, my activity waits of the answer
                               Log.d(TAG, "Finished: " + response);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } catch (ExecutionException e) {
                                e.printStackTrace();
                            }
                        } else {
                            // user didn't entered username or password
                            Toast.makeText(getApplicationContext(),
                                    "Done",
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                    }
                }
            });
        }

        public void onTaskCompleted()
        {
            progressDialog.dismiss();
        }



public class SyncHelper extends AsyncTask<Object, Void, String>
{
..
    private OnTaskCompleted listener;
..
        protected String doInBackground(Object... url) {
            String response = "";
            try {
                response = getRequest((String) url[0],(String) url[1], (String) url[2]); //Here I make a HttpURLConnection
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }

        @Override
        protected void onPreExecute() {
        }

        protected void onPostExecute(String result) {
            listener.onTaskCompleted();
        }
}
    public interface OnTaskCompleted{
        void onTaskCompleted();
    }

最佳答案

public class MainActivity extends Activity{
    ..

    private Button btnLogin;
    ..

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            btnLogin = (Button) findViewById(R.id.btnLogin);

            btnLogin.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                                       try {
                         String param1 = "testParam1";
                         String param2 = "testParam2";
                                 new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2); //this way, my activity waits of the answer
                               Log.d(TAG, "Finished: " + response);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } catch (ExecutionException e) {
                                e.printStackTrace();
                            }
                        } else {
                            // user didn't entered username or password
                            Toast.makeText(getApplicationContext(),
                                    "Done",
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                    }
                }
            });
        }





public class SyncHelper extends AsyncTask<String, Void, String>
{


..

    Context context;
    private ProgressDialog pd;
..

    public SyncHelper (Context c)
    {
         context = c;
    } 


@Override
        protected void onPreExecute() {
            pd = new ProgressDialog(context);
            pd.setTitle("Processing...");
            pd.setMessage("Please wait.");
            pd.setCancelable(false);
            pd.setIndeterminate(true);
            pd.show();
        }
        protected String doInBackground(String... url) {
            String response = "";
            try {
                response = getRequest(url[0], url[1], url[2]); //Here I make a HttpURLConnection
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }


        protected void onPostExecute(String result) {

            // here you will be getting the response in String result.
                 if (pd.isShowing()) 
                            pd.dismiss();

        }
}

当你使用get时,使用AsyncTask没有任何意义。因为 get() 会阻塞 UI 线程,也许这就是为什么看不到进度对话框的原因。如果您想将响应发送回MainActivity,请像使用beofre一样使用回调接口(interface)。

关于java - 带进度对话框的异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24226260/

相关文章:

java - Android Scrollview 不包裹子元素

JAVA(发送音频流 一服务器四客户端同机)

android - 从服务访问传感器

Android 模拟器 - Intent.createChooser 在打开 pdf 类型文档时显示 "No application can perform this action"

android - Kotlin 协程 : one single coroutine at a time in single thread

java - Java 中的泛型在定义方法时抛出错误

java - 带有@IdClass注释的类中的可插入对象

android - java.util.zip.ZipException : duplicate entry: android/arch/core/internal/SafeIterableMap. 类

android - 在android中使用私有(private)api有什么缺点?

java - 比较 2 个数组并向主数组的公共(public)元素添加一些文本?