1

複数のデバイスで問題が発生しており、デバイスが一定期間操作されていないと、HttpUrlConnection が期待どおりに動作しません。プロジェクトのターゲット プラットフォームは Android 4.0.3 です。

以下は、HttpUrlConnection の使用例です。

new AsyncRequestDTOBaseItemArray(callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);

実際の AsyncTask

public class AsyncRequestDTOBaseItem extends AsyncTask<String,String,Object> {

HttpURLConnection connection;
InputStream inStream;
IApiCallback callback;

public AsyncRequestDTOBaseItem(IApiCallback callback) {
    this.callback = callback;
}

@Override
protected Object doInBackground(String... uri) {

    try {
        URL url = new URL(uri[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.setInstanceFollowRedirects(false);
        connection.connect();

        String encoding = connection.getContentEncoding();
        // Determine if the stream is compressed and uncompress it if needed.
        if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
            inStream = new GZIPInputStream(connection.getInputStream());
        }  else {
            inStream = connection.getInputStream();
        }

        if (inStream != null) {
           InputStreamReader isr = new InputStreamReader(inStream);
            Gson gson = new Gson();

            try {
                DTOBaseItem item = gson.fromJson(isr, DTOBaseItem.class);
                return item;
            } catch (Exception e) {
                Log.i("AsyncRequestDTOBaseItem", "Exception");
                if (e != null && e.getMessage() != null) {
                    Log.e("AsyncRequestDTOBaseItem", e.getMessage());
                }
            } finally {
                inStream.close();                   
            }
        }   

    } catch (SocketTimeoutException e) {
        Log.i("AsyncRequestDTOBaseItem", "Socket Timeout occured");
    } catch (IOException e) {
        Log.i("AsyncRequestDTOBaseItem","IOException");

        if (e != null && e.getMessage() != null) {
            Log.i("AsyncRequestDTOBaseItem",e.getMessage());
        }

    } finally {
        if (connection != null)
            connection.disconnect();
    }
    return null;
}

@Override
protected void onPostExecute(Object result) {
    callback.Execute(result);
}
}

デバイスが非アクティブでない限り、上記のコードに問題はありません。デバイスが非アクティブである場合、実行される最後のコード行は次のとおりです。

String encoding = connection.getContentEncoding();

また、wifi設定に入り、wifiがスリープしないことを確認しました。最初は、wifi の再接続がこの問題を引き起こしているのではないかと考えました。

4

1 に答える 1

0

サーバーがデータを返送していないことが問題のようです。

connection.setReadTimeout(5000);を追加しました。そして今、問題はなくなったようです。

于 2013-01-21T00:16:54.230 に答える