Ross Stepaniak
Ross Stepaniak

Reputation: 855

android cuts HttpUrlConnection posting location in background after 10 minutes

I implemented a very simple service that runs one thread that repeatedly posts location to the server. It works well but when I unplug the device and send the app to background I see that it stops sending the location after leaving the device locked for 10 minutes. (Samsung galaxy, android 6.0) Any ideas would be appreciated.

public class TrackingService extends Service {
    private MyThread locationThread;
    private volatile boolean isRunning = false;

    @Override
    public void onCreate() {
        super.onCreate();
        locationThread = new Thread();
    }  

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        isRunning = true;
        locationThread.start();

        return START_STICKY;
    }

    class LocationThread extends Thread {
        static final long DELAY = 20000;
        @Override
        public void run(){
            while(isRunning){
                try {
                   updateLocation();
                   Thread.sleep(DELAY);
               } catch (InterruptedException e) {
                   isRunning = false;
                   e.printStackTrace();
            }
        }
    }

    private void updateLocation() {
        String urlString = "https://api.ourdomain.com/updateLatLong";

        String resultToDisplay = "";
        String response = "";

        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(12000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);

            String acc = mPrefs.getAccessToken();
            Map.Entry<String,String> tokenEntry =
                new AbstractMap.SimpleEntry<String, String>("accessToken", acc);
            Map.Entry<String,String> latEntry =
                new AbstractMap.SimpleEntry<String, String>("lat", latitude);
            Map.Entry<String,String> longEntry =
                new AbstractMap.SimpleEntry<String, String>("long", longitude);

            List<Map.Entry<String,String>> params = new ArrayList<>();
            params.add(tokenEntry);
            params.add(latEntry);
            params.add(longEntry);


            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(params));
            writer.flush();
            writer.close();
            os.close();

            int responseCode = urlConnection.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                while ((line=br.readLine()) != null) {
                    response+=line;
                }
            }

            Log.v("GetRegularLatLong", response);

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }  
     }

     @Override
     public void onDestroy() {
        super.onDestroy();
        isRunning = false;          
     }
}

Upvotes: 0

Views: 355

Answers (1)

ApriOri
ApriOri

Reputation: 2688

This may be affected by your code:

 urlConnection.setReadTimeout(10000);

You should close the connection gracefully with a finally block as shown here:

     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     urlConnection.setDoOutput(true);
     urlConnection.setChunkedStreamingMode(0);

     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
     writeStream(out);

     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }

I'd suggest to add a log after

updateLocation();
Thread.sleep(DELAY);

You should also watch the logs to see what kind of exception is thrown after 10 minutes.

Upvotes: 1

Related Questions