如果服务器不可用,如何处理应用程序

时间:2016-04-15 07:31:49

标签: android

在那里。我有一个基于远程服务器的应用程序。如果服务器正在运行我的应用程序是完美的,如果服务器不可用则崩溃。我正在测试localhost中的应用程序,所以我想处理它,我的异步任务代码如下。

    public class UserBackgroundTask extends AsyncTask<String, Void, String> {
    Context context;
    public ProgressDialog progressDialog;

    public UserBackgroundTask(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Verifying Username and Password...");
        progressDialog.show();
    }


    @Override
    protected String doInBackground(String... params) {

        String login_url = "http://10.0.3.2/newRsNepal/Login.php";
        HttpURLConnection httpURLConnection = null;
        String method = params[0];

        if (method.equals("login")) {
            String login_user = params[1];
            String login_password = params[2];

            try {
                URL url = new URL(login_url);
                 httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(login_user, "UTF-8") + "&" +
                        URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(login_password, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                String response = "";
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    response += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {

        if (result.equalsIgnoreCase("1")) {
            progressDialog.dismiss();
            Intent intent = new Intent(getApplicationContext(), InnerActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Add new Flag to start new Activity
            startActivity(intent);
            finish();
        } else {
            progressDialog.dismiss();
            Toast.makeText(context, "Invalid username and Password", Toast.LENGTH_LONG).show();
            textUser.setText("");
            textUser.setText("");
        }
    }

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

2 个答案:

答案 0 :(得分:2)

在PostExecute中使用此代码:

if (result.length>1) {
  Toast.makeText(YourActivity.this,"Your msg", Toast.LENGTH_SHORT).show();
}

    if (result.size>1) {
     Toast.makeText(YourActivity.this,"Your msg",  Toast.LENGTH_SHORT).show();
    }

   if (result==null) {
    }

答案 1 :(得分:0)

将下面的代码放在MainActivity文件中

//this function check internet connection
    private boolean isNetworkAvailable() {
                ConnectivityManager connectivityManager 
                      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                return activeNetworkInfo != null && activeNetworkInfo.isConnected();
            }

//put your code here
if(isNetworkAvailable() == true)
{
        //internet connection available put your code here  
        new UserBackgroundTask().execute();
}
else
{
        //internet connection not available     
}