I'm sending HTTP requests to server from working in background Service in Android. He works fine just when device is connected to computer through USB cable. If device isn't connected to computer - service still sends requests, but they didn't come to server. If i plug device to computer again - all sended requests coming immediately to server.
I'm using AsyncTask for sending requests.
Web service working good, I'm tested it with hurl.it I can't understand what's the reason.
Edited:
I'm sending requests with ->
URL url = null;
URLConnection connection = null;
InputStream inputStream = null;
String strURL = String.format("%s/%s", serviceURL, params);
try{
url = new URL(strURL);
connection = url.openConnection();
connection.connect();
inputStream = new BufferedInputStream(url.openStream());
}catch(IOException ioe){
ioe.printStackTrace();
}
Working solution
I was really shoked, when i found, that requests to server should be called not just from background thread, but with call-back construction, which provides interfaces.
In my service I'm starting AsyncTask
MyTask task = new MyTask();
task.execute((Void)null);
and implementing interface AsyncTaskHost in service class
...
@Override
public void onTaskStart(){
// sending http request to server using method from above
}
@Override
public void onTaskFinish(){
// doing additional work here, after getting response from request
}
my Interface:
public interface AsyncTaskHost{
public void onTaskStart();
public void onTaskFinish();
}
my async task class:
public class UploadCoordinates extends AsyncTask<Void, Integer, Void> {
private AsyncTaskHost taskHost;
private Context context;
public UploadCoordinates(Context context, AsyncTaskHost taskHost) {
this.taskHost = taskHost;
this.context = context;
}
@Override
protected Void doInBackground(Void... params) {
taskHost.onTaskStart();
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute(Void param) {
if (isCancelled()) {
return;
}
taskHost.onUploadFinish();
}
}
Now all works fine. without interface, async task doesn't want to work without usb cable. i don't know, this is magic for me (or Android OS blocking all requests, ports or something like that).