Android:异步任务,HTTP处理程序服务器关闭?

时间:2017-06-21 04:35:17

标签: android android-asynctask

在我的程序中通过HTTP处理程序检查登录部分。但是如果服务器关闭HTTP处理程序会产生错误。我可以检查HTTP处理程序makeServiceCall()方法是成功还是失败?

public class LoginActivity extends AppCompatActivity {

    private EditText et_Username;
    private EditText et_Password;
    private String st_Username;
    private String st_Password;
    private boolean checkCustomer = false;
    private ProgressDialog pDialog;
    private String url;
    private BroadcastReceiver broadcastReceiver = null;

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

        Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
        {
            @Override
            public void uncaughtException (Thread thread, Throwable e) {
                handleUncaughtException (thread, e);
            }
        });
    }

    public void OnLogin(View view){
        st_Username = et_Username.getText().toString();
        st_Password = et_Password.getText().toString();
        if(st_Password.isEmpty() || st_Username.isEmpty()){
            showToast("Fill all!!!");
        } else {
            if (!isNetworkAvailable(this)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.no_network_connection_title);
                builder.setMessage(R.string.no_network_connection_message)
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();
            } else executeAsyncTask();
        }
    }

    public void executeAsyncTask() {
        AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {

            String jsonStr;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                pDialog = new ProgressDialog(LoginActivity.this);
                pDialog.setMessage("Please wait...");
                pDialog.setCancelable(false);
                pDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                HttpHandler sh = new HttpHandler();
                url = "myUrl";
                // Making a request to url and getting response
                String[] st_Username_array = st_Username.split(" ");
                String[] st_Password_array = st_Password.split(" ");
                if (st_Password_array.length > 1 || st_Username_array.length > 1) {
                    checkCustomer = false;
                } else {
                    url += st_Username;

                    url += "/"+st_Password;
                    jsonStr = sh.makeServiceCall(url);

                    if(jsonStr.trim().equals("No")){
                            checkCustomer = false;
                        } else {
                        JSONObject jsonObj = null;
                        try {
                get jsonObject and send data
                              sh2.makeServiceCall(senddataUrl);
                            }

                            checkCustomer = true;

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void msg) {
                Log.v("AsyncTask", "onPostExecute in Login");

                if (pDialog.isShowing()){
                    pDialog.dismiss();
                    if(checkCustomer){

                        Intent intent = new Intent(LoginActivity.this, ThirdActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        showToast("Your user name or password is wrong!");
                        et_Password.setText("");
                    }
                }
            }
        };

        if(Build.VERSION.SDK_INT >= 11/*HONEYCOMB*/) {
            task.executeOnExecutor(Executors.newSingleThreadExecutor());
        } else {
            task.execute();
        }
    }

    public static boolean isNetworkAvailable(Context c) {
        ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }

    public void handleUncaughtException (Thread thread, Throwable e) {
        e.printStackTrace(); // not all Android versions will print the stack trace automatically

        Intent intent = new Intent (this, LoginActivity.class);
        showToast(e.toString());
        startActivity (intent);
        System.exit(1); // kill off the crashed app
    }
}

1 个答案:

答案 0 :(得分:0)

使用此代码查看您的服务器是否正在响应请求。您可以使用服务器的hostnameIP

try {
            SocketAddress sockaddr = new InetSocketAddress(ip, port);
    //      SocketAddress sockaddr = new  InetSocketAddress(String hostname, int port)
            Socket sock = new Socket();

//            int timeoutMs = 1000;   
//            sock.connect(sockaddr, timeoutMs)

            sock.connect(sockaddr);
            exists = true;

            sock.close();

        } catch (Exception e) {
            e.printStackTrace();
        }