【发布时间】:2012-09-12 01:57:20
【问题描述】:
我对此进行了很多搜索,但没有找到答案。
我想下载一个文件(提供 url、目的地和文件名)。 我有一个扩展 AsyncTast 类的类。 它适用于 Wi-Fi 连接,但不适用于移动数据(G、3g、H)! 我不知道为什么,我要疯了。
有人遇到过我相同或类似的问题吗?谢谢!
我在下面发布我的代码。 谢谢
public class AsyncDownloader extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
try {
Log.v("Downloader", "Source: " + sUrl[0]);
Log.v("Downloader", "Destin: " +sUrl[1]+"/" + sUrl[2]);
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(sUrl[1]+"/" + sUrl[2]);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
}
从主活动..
AsyncDownloader downloader = new AsyncDownloader();
downloader.execute("http://....", "...destination...", "...filename...");
有时我在目标目录中找到了该文件,但它没有完全下载或者它是 0 kB..
在 AndroidManifest.xml 我有:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE" />
我用这个函数来检查连接(看起来效果不错):
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null &&
cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
LogCat(很长 - 完整):http://pastebin.com/EL4DREwB LogCat(简短的、必不可少的 - 开始-完成应用运行时):http://pastebin.com/wPYDQH3P
【问题讨论】:
-
当您说“它不适用于移动数据”时,您是否有堆栈跟踪,或者您能描述什么不起作用?
-
在调用 asynctask 之前是否检查用户是否已连接到互联网?
-
我已经改进了我的问题,我附上了完整的 logcat
-
如果我在使用 3G 时打印“总”进度,则值为 NEGATIVE!!!当我使用 Wi-Fi 时,它会从 1 增长到 100。为什么?!
-
我正在寻找错误,我发现使用移动连接 (3g),程序到达 AsyncDownloader.class 的第 29 行 (InputStream input = new BufferedInputStream(url.openStream()); ) 并且不会继续!看起来正在加载或等待..
标签: android file download android-asynctask