I'm not sure how to even put a good title to this question.
I have the following class in my Android app:
class Translator {
public Translator() {
}
public String bingTranslate(String text) throws IOException {
String response;
String textEncoded= URLEncoder.encode(text, "utf-8");
String url = "https://www.bing.com/tdetect";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
//con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "UTF-8");
con.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
outputStreamWriter.write("text="+textEncoded);
outputStreamWriter.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
response=in.readLine();
in.close();
con.disconnect();
return response;
}
}
And I'm calling it like this:
detected = new Translator().bingTranslate(text.substring(0, Math.min(text.length(), 100)));
This works absolutely fine, however after my service runs for a long time (like a day or so), the URL fails to connect throwing me errors failed to connect. Force-stopping the service and restarting it makes the whole think work again.
My service is extending NotificationListenerService so it's always running, and it tries to use Bing to detect the language of some notifications.
The detect string is a local variable and the Translator class is not referenced anywhere else. First I thought it might somehow remain referenced because I was using the Translator class as a field. But even after moving the Translator to a local call the problem still resurface.
What I noticed when the connection fails, the URL throws and error that it failed to connect to: https://www.bing.com/204.79.197.200:443 which isn't really the URL string I used to make the call.
Am I'm missing the obvious or is this potentially a bug in Android?
As a footnote question any suggestion for an alternative to make the http call? I looked at Volley but that works with callbacks and I'm not too keen to make changes to my whole app to accommodate that.
from Android URL wont connect after service is running for a longer period
No comments:
Post a Comment