下载文件用的AsyncTask [英] Download file with AsyncTask
问题描述
我想下载一个文件的AsyncTask,但不工作,没有错误消息或什么,只是不下载的文件......我尝试一切,但它似乎未进入的,而任何人...知道什么可以是问题?我在我的手机进行测试,该网址是确定了。
类DownloadFileFromURL扩展的AsyncTask<字符串,字符串,字符串> { / **
*启动后台线程之前
* * /
@覆盖
在preExecute保护无效(){
super.on preExecute();
的System.out.println(开始下载);
} / **
在后台线程下载*文件
* * /
@覆盖
保护字符串doInBackground(字符串... f_url){
诠释计数;
尝试{
。字符串根= Environment.getExternalStorageDirectory()的toString(); 的System.out.println(下载);
网址URL =新的URL(f_url [0]); URLConnection的连接如= url.openConnection();
conection.connect();
//获取文件的长度
INT lenghtOfFile = conection.getContentLength(); //输入流中读取文件 - 具有8K缓冲
InputStream的输入=新的BufferedInputStream(url.openStream(),8192); //输出流写入文件 OutputStream的输出=新的FileOutputStream(根+/ downloadedfile.jpg);
字节的数据[] =新的字节[1024]; 总长= 0;
而((计数= input.read(数据))!= - 1){
总+ =计数; //将数据写入到文件
output.write(数据0,计); } //冲洗输出
output.flush(); //关闭流
output.close();
input.close(); }赶上(例外五){
Log.e(错误,e.getMessage());
} 返回null;
} / **
*在完成后台任务之后
* ** /
@覆盖
保护无效onPostExecute(字符串FILE_URL){
的System.out.println(已下载);
}}
我只是跑你code,这对我来说工作正常。图像被下载到SD卡。
只是要注意,一定要拥有这些权限在AndroidManifest.xml中设置:
<使用许可权的android:NAME =android.permission.INTERNET对/><使用许可权的android:NAME =android.permission.WRITE_EXTERNAL_STORAGE/>
下面是我得到的日志(请注意,我添加了一个 ProgressDialog
)
03-21 16:53:46.422 21017-21017 / com.imagedownload.danielnugent.imagedownload D /活动:#1 setTransGradationModeColor假
03-21 16:53:56.211 21017-21017 / com.imagedownload.danielnugent.imagedownload D /活动:#1 setTransGradationModeColor假
03-21 16:54:06.441 21017-21017 / com.imagedownload.danielnugent.imagedownload I / System.out的:开始下载
03-21 16:54:06.441 21017-21017 / com.imagedownload.danielnugent.imagedownload D /对话框:checkMirrorLinkEnabled回报:假的
03-21 16:54:06.441 21017-21017 / com.imagedownload.danielnugent.imagedownload D /对话框:允许展示
03-21 16:54:06.461 21017-25126 / com.imagedownload.danielnugent.imagedownload I / System.out的:下载
03-21 16:54:06.461 21017-21017 / com.imagedownload.danielnugent.imagedownload D /活动:#1 setTransGradationModeColor假
03-21 16:54:06.481 21017-21017 / com.imagedownload.danielnugent.imagedownload D /进度:updateDrawableBounds:左= 0
03-21 16:54:06.481 21017-21017 / com.imagedownload.danielnugent.imagedownload D /进度:updateDrawableBounds:顶部= 0
03-21 16:54:06.491 21017-21017 / com.imagedownload.danielnugent.imagedownload D /进度:updateDrawableBounds:右= 144
03-21 16:54:06.491 21017-21017 / com.imagedownload.danielnugent.imagedownload D /进度:updateDrawableBounds:底部= 144
03-21 16:54:1159.6 21017-21017 / com.imagedownload.danielnugent.imagedownload I / System.out的:下载
以防万一,这将是有用的,这里是全MainActivity.java code为我工作。 (URL是一个占位符):
进口android.app.ProgressDialog;
进口android.os.AsyncTask;
进口android.os.Environment;
进口android.support.v7.app.ActionBarActivity;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.Menu;
进口android.view.MenuItem;进口java.io.BufferedInputStream中;
进口java.io.FileOutputStream中;
进口的java.io.InputStream;
进口java.io.OutputStream中;
进口的java.net.URL;
进口java.net.URLConnection中;
公共类MainActivity扩展ActionBarActivity { 私人ProgressDialog pDialog; @覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main); 新DownloadFileFromURL()执行(http://www.example.com/IMG.jpg);
}
@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
//充气菜单;如果是present这增加了项目操作栏。
。getMenuInflater()膨胀(R.menu.menu_main,菜单);
返回true;
} @覆盖
公共布尔onOptionsItemSelected(菜单项项){
//处理动作栏项目点击这里。操作栏会
//自动处理上点击主页/向上按钮,只要
//你在AndroidManifest.xml中指定一个父活动。
INT ID = item.getItemId(); // noinspection SimplifiableIfStatement
如果(ID == R.id.action_settings){
返回true;
} 返回super.onOptionsItemSelected(项目);
} 类DownloadFileFromURL扩展的AsyncTask<字符串,字符串,字符串> { / **
*启动后台线程之前
* * /
@覆盖
在preExecute保护无效(){
super.on preExecute();
的System.out.println(开始下载); pDialog =新ProgressDialog(MainActivity.this);
pDialog.setMessage(正在加载...请稍候...);
pDialog.setIndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
} / **
在后台线程下载*文件
* * /
@覆盖
保护字符串doInBackground(字符串... f_url){
诠释计数;
尝试{
。字符串根= Environment.getExternalStorageDirectory()的toString(); 的System.out.println(下载);
网址URL =新的URL(f_url [0]); URLConnection的连接如= url.openConnection();
conection.connect();
//获取文件的长度
INT lenghtOfFile = conection.getContentLength(); //输入流中读取文件 - 具有8K缓冲
InputStream的输入=新的BufferedInputStream(url.openStream(),8192); //输出流写入文件 OutputStream的输出=新的FileOutputStream(根+/ downloadedfile.jpg);
字节的数据[] =新的字节[1024]; 总长= 0;
而((计数= input.read(数据))!= - 1){
总+ =计数; //将数据写入到文件
output.write(数据0,计); } //冲洗输出
output.flush(); //关闭流
output.close();
input.close(); }赶上(例外五){
Log.e(错误,e.getMessage());
} 返回null;
} / **
*在完成后台任务之后
* ** /
@覆盖
保护无效onPostExecute(字符串FILE_URL){
的System.out.println(已下载); pDialog.dismiss();
} }}
I am trying to download a file with asyncTask but is not working, there is no error messages or nothing, just dont download the file... i try everything but it appears that is not entering on the while... anybody know what can be the problem? I tested on my mobile, the url is ok too.
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Starting download");
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString();
System.out.println("Downloading");
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(root+"/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* After completing background task
* **/
@Override
protected void onPostExecute(String file_url) {
System.out.println("Downloaded");
}
}
I just ran your code, and it works fine for me. The image was downloaded to the sdcard.
Just to note, make sure you have these permissions set in your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here are the logs I got (note that I added a ProgressDialog
):
03-21 16:53:46.422 21017-21017/com.imagedownload.danielnugent.imagedownload D/Activity﹕ #1 setTransGradationModeColor false
03-21 16:53:56.211 21017-21017/com.imagedownload.danielnugent.imagedownload D/Activity﹕ #1 setTransGradationModeColor false
03-21 16:54:06.441 21017-21017/com.imagedownload.danielnugent.imagedownload I/System.out﹕ Starting download
03-21 16:54:06.441 21017-21017/com.imagedownload.danielnugent.imagedownload D/Dialog﹕ checkMirrorLinkEnabled returns : false
03-21 16:54:06.441 21017-21017/com.imagedownload.danielnugent.imagedownload D/Dialog﹕ showing allowed
03-21 16:54:06.461 21017-25126/com.imagedownload.danielnugent.imagedownload I/System.out﹕ Downloading
03-21 16:54:06.461 21017-21017/com.imagedownload.danielnugent.imagedownload D/Activity﹕ #1 setTransGradationModeColor false
03-21 16:54:06.481 21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: left = 0
03-21 16:54:06.481 21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: top = 0
03-21 16:54:06.491 21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: right = 144
03-21 16:54:06.491 21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: bottom = 144
03-21 16:54:11.596 21017-21017/com.imagedownload.danielnugent.imagedownload I/System.out﹕ Downloaded
Just in case this will be useful, here is the full MainActivity.java code that worked for me. (url is a placeholder):
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends ActionBarActivity {
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadFileFromURL().execute("http://www.example.com/IMG.jpg");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Starting download");
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString();
System.out.println("Downloading");
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(root+"/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* After completing background task
* **/
@Override
protected void onPostExecute(String file_url) {
System.out.println("Downloaded");
pDialog.dismiss();
}
}
}
这篇关于下载文件用的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!