如何下载文件并在Android中显示进度?

时间:2012-12-09 12:29:59

标签: android concurrency download

  1. 我正在尝试在android中下载文件并显示进度 在进度条中下载

    1. 在textview中显示下载速度
    2. 在textview中显示文件的大小
    3. ,同时下载文件

      我能够同时显示进度条,但在for循环中, 在我运行代码的那一刻,我给出了错误: NullPointerExceptoin 。但是没有说它在哪一行也给了我 FileNotFoundException 。我不知道我做错了什么。 我是Android新手,所以如果有人可以提供帮助,那就太棒了。这是代码。我在清单文件中提供了permisions。

      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
           <uses-permission android:name="android.permission.INTERNET"></uses-permission>
           <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
           <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
      

      这是活动,我只使用此活动。

      public class DownloadActivity extends Activity implements OnClickListener {
      
          TextView view1;
          TextView view2;
          TextView view3;
          ProgressBar bar;
          Button startButton;
          String contents;
      
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_download);
              startButton = (Button) findViewById(R.id.button1);
              bar = (ProgressBar) findViewById(R.id.progressBar1);
              startButton.setOnClickListener((OnClickListener) this);
      //        contents = urlToString("https://www.dropbox.com/home/Music/FOX%20-%20Pokazn%D0%BE%CC%81%20(2012)");
              contents = "http://sdlc-esd.sun.com/ESD6/JSCDL/jdk/7u9-b05/jre-7u9-windows-i586.exe?AuthParam=1355055216_89a14482cb59e95946db732dc4341468&GroupName=JSC&FilePath=/ESD6/JSCDL/jdk/7u9-b05/jre-7u9-windows-i586.exe&File=jre-7u9-windows-i586.exe&BHost=javadl.sun.com";
              urlToString(contents);
      //        http://ipv4.download.thinkbroadband.com/10MB.zip
      //        http://sdlc-esd.sun.com/ESD6/JSCDL/jdk/7u9-b05/jre-7u9-windows-i586.exe?AuthParam=1355055216_89a14482cb59e95946db732dc4341468&GroupName=JSC&FilePath=/ESD6/JSCDL/jdk/7u9-b05/jre-7u9-windows-i586.exe&File=jre-7u9-windows-i586.exe&BHost=javadl.sun.com
          }
      
      
          public void onClick(View view) {
      
              // detect the view that was "clicked"
              switch (view.getId()) {
              case R.id.button1:
                  new LongOperation().execute(1000 + "");
                  break;
              }
          }
      
          private class LongOperation extends AsyncTask<String, Integer, String> {
      
      
              @Override
              protected String doInBackground(String... sUrl) {
                  try {
                      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(contents);
      
                      byte data[] = new byte[1024];
                      long total = 0;
                      int count;
                      while ((count = input.read(data)) != -1) 
                      {
                          total += count;
                          // publishing the progress.... triggers the onProgressUpdate!
                          publishProgress((int) (total * 100 / fileLength));
      
                          output.write(data, 0, count);
                      }
      
                      output.flush();
                      output.close();
                      input.close();
                  } catch (Exception e) {
                  }
      
                  for (int i = 0; i < 100; i++) {
                      try {
      
      
                          Thread.sleep(500);
                           publishProgress(i+1);
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                  }
                  return "URL:" + contents;
              }
      
              @Override
              protected void onPostExecute(String result) {
                  TextView txt = (TextView) findViewById(R.id.textView1);
                  txt.setText(result);
              }
      
              @Override
                protected void onProgressUpdate(Integer... values) {
                 // TODO Auto-generated method stub
                  bar.setProgress(values[0]);
                  view1 = (TextView) findViewById(R.id.textView1);
                  view2 = (TextView) findViewById(R.id.textView2);
                  view3 = (TextView) findViewById(R.id.textView3);
      
      
                  view1.setText("URL: " +  contents);
                  view2.setText("File Size: "  + "x");
                  view3.setText("Transfer Rate: "  + "y" );
                }
          }
      
      
      
      //  Log.v("********", getLinkRate());
      
          private String urlToString(String address) {
              HttpURLConnection con = null;
              URL url;
              InputStream is = null;
              try {
                  url = new URL(address);
                  con = (HttpURLConnection) url.openConnection();
                  con.setReadTimeout(10000);
                  con.setConnectTimeout(15000);
                  con.setRequestMethod("GET");
                  con.connect();
                  is = con.getInputStream();
              } catch (IOException e) {
                  e.printStackTrace();
              }
      
              BufferedReader reader = null;
              StringBuilder sb = new StringBuilder();
              try {
                  reader = new BufferedReader(new InputStreamReader(is));
                  String line = "";
                  while ((line = reader.readLine()) != null) {
                      sb.append(line);
      
                      Log.d("*******", line);
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              } finally {
                  if (reader != null) {
                      try {
                          reader.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
                  if (is != null) {
                      try {
                          is.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
      
              return sb.toString();
          }
      }
      

      logcat的:

      12-09 12:53:57.608: D/*******(824): Ty���mk�B$1�-2
      12-09 12:53:57.648: D/dalvikvm(824): GC_FOR_MALLOC freed 202K, 62% free 7797K/20487K, external 1625K/2137K, paused 31ms
      12-09 12:53:57.648: I/dalvikvm-heap(824): Forcing collection of SoftReferences for 7981588-byte allocation
      12-09 12:53:57.669: D/dalvikvm(824): GC_FOR_MALLOC freed 1K, 62% free 7796K/20487K, external 1625K/2137K, paused 26ms
      12-09 12:53:57.669: E/dalvikvm-heap(824): Out of memory on a 7981588-byte allocation.
      12-09 12:53:57.669: I/dalvikvm(824): "main" prio=5 tid=1 RUNNABLE
      12-09 12:53:57.678: I/dalvikvm(824):   | group="main" sCount=0 dsCount=0 obj=0x4001f1a8 self=0xce48
      12-09 12:53:57.678: I/dalvikvm(824):   | sysTid=824 nice=0 sched=0/0 cgrp=default handle=-1345006528
      12-09 12:53:57.678: I/dalvikvm(824):   | schedstat=( 6672852716 8933397811 8674 )
      12-09 12:53:57.678: I/dalvikvm(824):   at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:~95)
      12-09 12:53:57.678: I/dalvikvm(824):   at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:153)
      12-09 12:53:57.678: I/dalvikvm(824):   at java.lang.StringBuilder.append(StringBuilder.java:217)
      12-09 12:53:57.678: I/dalvikvm(824):   at tees.ac.uk.L1087591.DownloadActivity.urlToString(DownloadActivity.java:156)
      12-09 12:53:57.678: I/dalvikvm(824):   at tees.ac.uk.L1087591.DownloadActivity.onClick(DownloadActivity.java:54)
      12-09 12:53:57.678: I/dalvikvm(824):   at android.view.View.performClick(View.java:2485)
      12-09 12:53:57.678: I/dalvikvm(824):   at android.view.View$PerformClick.run(View.java:9080)
      12-09 12:53:57.678: I/dalvikvm(824):   at android.os.Handler.handleCallback(Handler.java:587)
      12-09 12:53:57.678: I/dalvikvm(824):   at android.os.Handler.dispatchMessage(Handler.java:92)
      12-09 12:53:57.678: I/dalvikvm(824):   at android.os.Looper.loop(Looper.java:123)
      12-09 12:53:57.678: I/dalvikvm(824):   at android.app.ActivityThread.main(ActivityThread.java:3683)
      12-09 12:53:57.678: I/dalvikvm(824):   at java.lang.reflect.Method.invokeNative(Native Method)
      12-09 12:53:57.678: I/dalvikvm(824):   at java.lang.reflect.Method.invoke(Method.java:507)
      12-09 12:53:57.678: I/dalvikvm(824):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
      12-09 12:53:57.678: I/dalvikvm(824):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
      12-09 12:53:57.678: I/dalvikvm(824):   at dalvik.system.NativeStart.main(Native Method)
      12-09 12:53:57.688: D/AndroidRuntime(824): Shutting down VM
      12-09 12:53:57.688: W/dalvikvm(824): threadid=1: thread exiting with uncaught exception (group=0x40015560)
      12-09 12:53:57.688: E/AndroidRuntime(824): FATAL EXCEPTION: main
      12-09 12:53:57.688: E/AndroidRuntime(824): java.lang.OutOfMemoryError
      12-09 12:53:57.688: E/AndroidRuntime(824):  at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:153)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at java.lang.StringBuilder.append(StringBuilder.java:217)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at tees.ac.uk.L1087591.DownloadActivity.urlToString(DownloadActivity.java:156)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at tees.ac.uk.L1087591.DownloadActivity.onClick(DownloadActivity.java:54)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at android.view.View.performClick(View.java:2485)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at android.view.View$PerformClick.run(View.java:9080)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at android.os.Handler.handleCallback(Handler.java:587)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at android.os.Handler.dispatchMessage(Handler.java:92)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at android.os.Looper.loop(Looper.java:123)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at android.app.ActivityThread.main(ActivityThread.java:3683)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at java.lang.reflect.Method.invokeNative(Native Method)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at java.lang.reflect.Method.invoke(Method.java:507)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
      12-09 12:53:57.688: E/AndroidRuntime(824):  at dalvik.system.NativeStart.main(Native Method)
      12-09 12:53:59.688: I/Process(824): Sending signal. PID: 824 SIG: 9
      

4 个答案:

答案 0 :(得分:1)

您必须调试活动以找出抛出NullPointerException的行。

答案 1 :(得分:1)

在您的OnCreate函数中,您正在使用一个名为urlToString的方法来创建HTTPURLConnection,如果您在4.0以上运行它,那么您的代码将崩溃,因为HHTP连接应该在后台线程中而不是在主线程上处理

答案 2 :(得分:1)

检查您运行的代码是否实际通过try{}catch(){}阻止,然后继续执行其余代码,因为如果找不到文件,则应停止AsyncTask并显示错误消息

您正在调用您的AsyncTask

new LongOperation().execute(1000 + "");

所以你传递1000 + ""作为url参数?当您像这样声明AsyncTAsk时

private class LongOperation extends AsyncTask<String, Integer, String>

你假设传递String作为参数,你得到Integer作为onProgressUpdate()的进度,最后获得AsyncTask结果的String

此外,您在onCreate()呼叫

的主线程上无法建立网络
urlToString(contents);

答案 3 :(得分:1)

您正在使用“new LongOperation()。execute(1000 +”“)”启动AsyncTask, 所以字符串“1000”传递给doInBackground方法,然后你启动了一个字符串为“1000”的URLConnection,但“1000”是一个无效的url。 也许这就是错误。