android在10分钟后剪切HttpUrlConnection在后台发布位置

时间:2017-08-08 20:50:52

标签: android multithreading service httpurlconnection

我实现了一个非常简单的服务,它运行一个重复将位置发布到服务器的线程。它运行良好,但当我拔下设备并将应用程序发送到后台时,我发现它在设备锁定10分钟后停止发送位置。 (三星galaxy,android 6.0)任何想法都会受到赞赏。

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;          
     }
}

1 个答案:

答案 0 :(得分:1)

这可能会受到您的代码的影响:

 urlConnection.setReadTimeout(10000);

您应该使用finally 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();
   }

我建议在

后添加日志
updateLocation();
Thread.sleep(DELAY);

您还应该观察日志,看看10分钟后会抛出什么样的异常。