android下载文件简单代码
时间: 2023-11-05 14:03:10 浏览: 137
欢迎!以下是一个简单的Android下载文件的代码示例:
首先,在AndroidManifest.xml文件中添加网络权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
然后,在Activity中创建一个异步任务类来处理下载:
```java
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("下载文件");
progressDialog.setMessage("正在下载,请稍候...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
String fileUrl = params[0];
String savePath = Environment.getExternalStorageDirectory().getPath() + "/downloaded_file.jpg";
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
totalBytesRead += bytesRead;
publishProgress((int) ((totalBytesRead * 100) / fileLength));
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
connection.disconnect();
} catch (Exception e) {
Log.e("DownloadTask", e.getMessage());
return "下载失败";
}
return "下载成功";
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
progressDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}
```
最后,在需要下载文件的地方调用AsyncTask执行下载任务:
```java
String fileUrl = "http://example.com/file.jpg";
new DownloadTask().execute(fileUrl);
```
以上代码实现了一个可以下载文件的简单Android应用。它使用了一个异步任务类来执行网络请求并将文件保存到设备的指定路径中。显示了一个进度对话框来显示下载进度,并在下载完成后显示一个Toast消息。请注意,这个示例仅供参考,实际应用可能需要进一步处理异常、权限检查等。
阅读全文