我在我的Moto360 smartwtach上创建了一个小应用程序来播放从Web服务器下载的音频内容。我使用以下代码段从给定的URL下载内容。
@Override
protected String doInBackground(String... sUrl) {
Log.d(TAG, "Downloading file !!!");
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Error on http connection !! ");
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
Log.e(TAG, "exception : " + e);
return e.toString();
} finally {
try {
if (output != null) {
Log.d(TAG, "download finished!");
output.close();
}
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
但是我得到了超时连接:
08-06 16:22:06.345 17925-17941/com.example.ile14017.moto360 E/DownloadTask﹕ exception : java.net.ConnectException: failed to connect to api.europe1.fr/85.116.42.56 (port 80): connect failed: ETIMEDOUT (Connection timed out)
我尝试更改连接超时值(setConnectTimeout方法),但结果是一样的。要下载的文件大小约为2Mo。
答案 0 :(得分:1)
您的手表(通过BT)是否已连接到手机?如果是这样,那么即使在手表上设置了wifi,您的手表也没有wifi连接来使用URLConnection进行网络通话。您需要考虑这种情况并使用手机为您进行下载,然后使用ChannelApi将文件传输到您的手表。