在那裏。我有一個基於遠程服務器的應用程序。我的應用程序工作完美,如果服務器正在運行,並崩潰,如果服務器不可用。我測試應用程序在本地主機,所以我想處理它,我的異步任務代碼如下。如何處理應用程序,如果服務器不可用
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);
}
}
就可以獲取數據.. – Mohit