我在屏幕关闭时发出http请求时遇到了不少麻烦。我目前使用的是HttpUrlConnection,方法如下。
class HttpPostRequest extends AsyncTask<String, Void, String> {
private String httpResponse = null;
public String getResponse() {
return httpResponse;
}
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setDoOutput(true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write(params[1]);
writer.flush();
writer.close();
connection.connect();
Log.e("Response", connection.getResponseCode() + "");
Log.e("Url", connection.getRequestMethod());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
connection.disconnect();
// print result
return response.toString();
}
} catch (Exception e) {
Log.e(e.toString(), "Something with request");
return "";
}
return "";
}
}
然而,当我正在编程的应用程序在屏幕上时,这个方法可以完美地工作,但当屏幕关闭时,它却无法工作。如果能听到社区的建议就更好了。谢谢!我有不少问题。
使用Thread来代替AsyncTask,如
Thread t = new Thread({
public void run(){
.....
your code
}
});
t.start();
如果你想在后台调用http请求,你可以使用WorkManager。https:/developer.android.comtopiclibrariesarchitectureworkmanager。