尝试连接到服务器时带有异步任务的进度条

Progressbar with Async Task while trying to connect to server

我想在通过 AsyncTask 的 doInbackground 方法执行后台任务时显示进度对话框 Class,但问题是当我的服务器关闭时(Wamp 服务器关闭)它在尝试时不显示进度对话框与服务器建立连接。 请在这方面提供帮助。

主要Class:

import android.app.AlertDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity{

    Button btnSubmitOrder;
    EditText edDealerID;
    EditText edProductID;
    EditText edQuantity;
    String stDealerID;
    String stProductID;
    String stQuantity;
    String stUnit;
    String stDate;
    String stTime;
    String stStatus;
    ProgressBar edProgress;

    Date currentDate = Calendar.getInstance().getTime();

    DatabaseSQLite objDatabaseSqlite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Date objDate = Calendar.getInstance().getTime();
        SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
        stDate = df.format(objDate);

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
        stTime = sdf.format(objDate);

        final Spinner dropdown = findViewById(R.id.edit_unit);
        String[] items = new String[]{"Box", "Packets"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
        dropdown.setAdapter(adapter);

        objDatabaseSqlite = new DatabaseSQLite(this);

        btnSubmitOrder = findViewById(R.id.btn_submitorder);
        edDealerID = findViewById(R.id.edit_dealerid);
        edProductID = findViewById(R.id.edit_productid);
        edQuantity = findViewById(R.id.edit_quantity);
        edProgress = findViewById(R.id.ed_progress);
        btnSubmitOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stDealerID = edDealerID.getText().toString();
                stProductID = edProductID.getText().toString();
                stQuantity = edQuantity.getText().toString();
                stUnit = dropdown.getSelectedItem().toString();
                stStatus = "Pending";
                BackgroundTask objBackground = new BackgroundTask(MainActivity.this);
                try {
                    String response = objBackground.execute(stDealerID, stProductID, stQuantity, stUnit, stDate, stTime, stStatus).get();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}

后台任务Class:

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by Saffi on 3/17/2016.
 */
public class BackgroundTask extends AsyncTask<String,Void,String> {

    private String response = "";
    private ProgressDialog dialog;
    Context ctx;

    BackgroundTask(Context ctx)
    {
        this.ctx = ctx;
    }

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(ctx);
        dialog.setMessage("Progress start");
        dialog.show();
    }

    protected String doInBackground(String... params) {
        String sendInvoice = "http://10.0.2.2/YounasTraders/SendInvoice.php";
        String dealerId = params[0];
        String productId = params[1];
        String quantity = params[2];
        String unit = params[3];
        String date = params[4];
        String time = params[5];
        String status = params[6];
        try {
            URL objurl = new URL(sendInvoice);
            HttpURLConnection objhttpurlconnection = (HttpURLConnection) objurl.openConnection();
            objhttpurlconnection.setRequestMethod("POST");
            objhttpurlconnection.setDoOutput(true);
            objhttpurlconnection.setDoInput(true);
            OutputStream objos = objhttpurlconnection.getOutputStream();
            BufferedWriter objbuffwrite = new BufferedWriter(new OutputStreamWriter(objos, "UTF-8"));

            String data = URLEncoder.encode("dealer_id", "UTF-8") +"="+URLEncoder.encode(dealerId, "UTF-8")+"&"+
                    URLEncoder.encode("product_id", "UTF-8")+"="+URLEncoder.encode(productId, "UTF-8")+"&"+
                    URLEncoder.encode("quantity", "UTF-8")+"="+URLEncoder.encode(quantity, "UTF-8")+"&"+
                    URLEncoder.encode("unit", "UTF-8")+"="+URLEncoder.encode(unit, "UTF-8")+"&"+
                    URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+"&"+
                    URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")+"&"+
                    URLEncoder.encode("status", "UTF-8")+"="+URLEncoder.encode(status, "UTF-8");
            objbuffwrite.write(data);
            objbuffwrite.flush();
            objbuffwrite.close();
            objos.close();

            InputStream objis = objhttpurlconnection.getInputStream();
            objis.close();
            objhttpurlconnection.disconnect();

            response = "Order Sent Successfully";

            return response;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        response = "Order Not Sent Successfully";
        return response;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        dialog.show();
    }

    @Override
    protected void onPostExecute(String value) {
        dialog.dismiss();
    }
}

问题是您正在使用 .get 方法在主线程上执行任务

第一次更改您的 AsyncTask 任务包括此回调接口以在完成您的 HTTP 请求后调用它

public class BackgroundTask 扩展了 AsyncTask {

    private CallBack callBack;

    public CallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(CallBack callBack) {
        this.callBack = callBack;
    }

    private String response = "";
    private ProgressDialog dialog;
    Context ctx;

    BackgroundTask(Context ctx)
    {
        this.ctx = ctx;
    }

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(ctx);
        dialog.setMessage("Progress start");
        dialog.show();
    }

    protected String doInBackground(String... params) {
        String sendInvoice = "http://10.0.2.2/YounasTraders/SendInvoice.php";
        String dealerId = params[0];
        String productId = params[1];
        String quantity = params[2];
        String unit = params[3];
        String date = params[4];
        String time = params[5];
        String status = params[6];
        try {
            URL objurl = new URL(sendInvoice);
            HttpURLConnection objhttpurlconnection = (HttpURLConnection) objurl.openConnection();
            objhttpurlconnection.setRequestMethod("POST");
            objhttpurlconnection.setDoOutput(true);
            objhttpurlconnection.setDoInput(true);
            OutputStream objos = objhttpurlconnection.getOutputStream();
            BufferedWriter objbuffwrite = new BufferedWriter(new OutputStreamWriter(objos, "UTF-8"));

            String data = URLEncoder.encode("dealer_id", "UTF-8") +"="+URLEncoder.encode(dealerId, "UTF-8")+"&"+
                    URLEncoder.encode("product_id", "UTF-8")+"="+URLEncoder.encode(productId, "UTF-8")+"&"+
                    URLEncoder.encode("quantity", "UTF-8")+"="+URLEncoder.encode(quantity, "UTF-8")+"&"+
                    URLEncoder.encode("unit", "UTF-8")+"="+URLEncoder.encode(unit, "UTF-8")+"&"+
                    URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+"&"+
                    URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")+"&"+
                    URLEncoder.encode("status", "UTF-8")+"="+URLEncoder.encode(status, "UTF-8");
            objbuffwrite.write(data);
            objbuffwrite.flush();
            objbuffwrite.close();
            objos.close();

            InputStream objis = objhttpurlconnection.getInputStream();
            objis.close();
            objhttpurlconnection.disconnect();

            response = "Order Sent Successfully";

            return response;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        response = "Order Not Sent Successfully";
        return response;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        dialog.show();
    }

    @Override
    protected void onPostExecute(String value) {
        dialog.dismiss();
        if(callBack != null)
            callBack.onResult(value);

    }

    public interface CallBack{
        void onResult(String value);
    }
}

第二次更改异步任务的执行,在回调中获取结果

  BackgroundTask objBackground = new BackgroundTask(MainActivity.this);
        objBackground.setCallBack(new BackgroundTask.CallBack() {
            @Override
            public void onResult(String value) {
                //get here your response
            }
        });
        objBackground.execute(stDealerID, stProductID, stQuantity, stUnit, stDate, stTime, stStatus);