开发者

Problem in File Downloading from server in android application

I am using this code of snippet to download mp4 files from server. Normally file get download properly, but sometime my downloading process stops downloading automatically. Progress bar stop incrementing. Is there any kernel process that stop download.

//+++++++++= FUnction Call ++++++++++++++++

DOWNLOAD_FILE_NAME = "demo.mp4";
grabURL("mp4 file server url");  

//+++++++++++++++++++++++++++++++++++++++++

public void grabURL(String url) {  

          new GrabURL().execute(url); 

    }
private class GrabURL extends AsyncTask<String, Void, Void> {  
                  private final HttpClient Cl开发者_开发百科ient = new DefaultHttpClient();  
                  private String Content;  
                  private String Error = null;  
                  private ProgressDialog Dialog = new ProgressDialog(SlideShow.this);  

                  protected void onPreExecute() {  


                   showDialog(DIALOG_PROGRESS);
               mProgressDialog.setProgress(0);

                  }  

          protected Void doInBackground(String... url) {  
              int count;

              try {
                  URL url2 = new URL(url[0]);
                  URLConnection conexion = url2.openConnection();
                  conexion.setUseCaches(true);
                  conexion.connect();

                  // this will be useful so that you can show a tipical 0-100% progress bar
                  int lenghtOfFile = conexion.getContentLength();
                  mProgressDialog.setMax(lenghtOfFile);
                  // downlod the file
                  InputStream input = new BufferedInputStream(url2.openStream());
                  OutputStream output = new FileOutputStream(DOWNLOAD_FILE_NAME);

                  byte data[] = new byte[1024];

                  while ((count = input.read(data)) != -1) {

                      mProgressDialog.incrementProgressBy(data.length);
                          output.write(data, 0, count);
                  }

                  output.close();
                  input.close();
              } catch (Exception e) {}
              return null;
          }  


On mobile device internet connection has to be treated as very unreliable.

Your code shows a downloading method but no connection management. If your internet connection stops for some reason, your code won't be able to relaunch it.

You can use the a broadcast receiver from the ConnectivityManager : http://developer.android.com/reference/android/net/ConnectivityManager.html to be notified when the connection drops and relaunch your download from there when the connection is up again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜