Based on the information that Volley can also perform synchronous processing, the following sources were executed.
app/build.gradle
dependencies {
implementation 'com.android.volley:volley:1.1.1'
}
MyActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "https://example.com/";
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, future, future);
RequestQueue queue = Volley.newRequestQueue(MyActivity.this);
queue.add(stringRequest);
try {
String result = future.get(10000, TimeUnit.MILLISECONDS);
Log.d(TAG, result);
} catch (Exception e) {
e.printStackTrace();
}
}
I get a java.util.concurrent.TimeoutException. I can't see the cause because I can only tell that the exception was thrown by reading Logcat.
Since Android3.0, NetworkOnMainThreadException occurs when synchronizing process is executed in UI thread. Apparently Volley doesn't fall and times out.
When I rewrote it as follows using AsyncTask, I was able to get it normally.
MyActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsyncTask() {
@Override
protected Object doInBackground(Object[] objects) {
String url = "https://example.com/";
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, future, future);
RequestQueue queue = Volley.newRequestQueue(MyActivity.this);
queue.add(stringRequest);
try {
String result = future.get(10000, TimeUnit.MILLISECONDS);
Log.d(TAG, result);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
Recommended Posts