我正在尝试开发Android应用程序。每次应用程序启动时,都必须从服务器获取一些详细信息。我使用了asynctask
,我在android中的onCreate
方法中调用它。它在服务器运行时非常有效,但是当服务器没有运行时,我不希望我的应用程序挂起等待超时并发现服务器没有运行。什么是更好的实施方式?在我目前的方法中,应用程序一直停留,直到超时发生。
答案 0 :(得分:0)
您可以使用以下代码
为HttpURLConnection
添加提示
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
完整源代码如下。干杯:)
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Test().execute();
}
//AsyncTask
class Test extends AsyncTask < String, Void, String > {
@Override
protected String doInBackground(String...params) {
InputStream in = null;
String queryResult = "";
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//add parameters
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));
try {
//write OutputStream
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
queryResult = readStream( in );
} finally {
urlConnection.disconnect();
}
return queryResult;
}
private String readStream(InputStream iStream) throws IOException {
//Buffered reader allows us to read line by line
try (BufferedReader bReader =
new BufferedReader(new InputStreamReader(iStream))) {
StringBuilder builder = new StringBuilder();
String line;
while ((line = bReader.readLine()) != null) { //Read till end
builder.append(line);
}
return builder.toString();
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
protected void onPostExecute(String data) {
// do further things
Toast toast = Toast.makeText(getApplicationContext(), data,
Toast.LENGTH_SHORT);
toast.show();
}
}
}
答案 1 :(得分:0)
使用下面一行代码:
try {
URL url = new URL("http://192.168.1.1");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(5 * 1000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
// condition for connection is fine , 200 = "OK"
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
答案 2 :(得分:0)
当我更改为asyncTask.execute().get();
时,我正在使用asyncTask.execute()
它工作正常