4

我对此进行了很多搜索,但没有找到答案。

我想下载一个文件(给出 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

4

1 回答 1

0

please check your code network connectivity code. you may checking only for WIFI connectivity , that why you AsyncTask not execute, you may use this

      public  static boolean getNetworkStatus(){
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = manager.getActiveNetworkInfo();
    return netInfo !=null && netInfo.isConnected();
} 
于 2012-09-19T18:11:52.220 回答