gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 08:06:30 27 4
gpt4 key购买 nike

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

    1. 在 TextView 中显示下载速度
    2. 在 TextView 中显示文件的大小

    下载文件时

我已经能够并发显示进度条了,但是在for循环中,在我运行代码时出现错误:NullPointerExceptoin。但没有说明在哪一行它也给了我 FileNotFoundException。而且我不知道我做错了什么。 我是 Android 的新手,所以如果有人能提供帮助那就太好了。这是代码。我已在 list 文件中提供权限。

<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>

这是 Activity ,我只使用这个 Activity 。

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();
}
}

日志:

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

最佳答案

检查您正在运行的代码是否真的通过了 try{}catch(){} block ,然后才继续执行其余代码,因为如果找不到文件,您应该停止 AsyncTask 并显示错误信息

你正在这样调用你的 AsyncTask

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

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

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

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

此外,您不能在调用 onCreate() 的主线程上建立网络

urlToString(contents);

关于android - 如何在 Android 中下载文件并显示进度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13787380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com