Android-文件下载、浏览图片
程序员文章站
2022-03-11 21:49:54
实现一个输入url可以查看图片及文件下载的小功能文章目录布局文件NetActivity类布局文件
实现一个输入url可以查看图片及文件下载的小功能
文章目录
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.br.NetActivity">
<!-- centerCrop属性 拉伸图片填满imageView
如果原图大于imageView的大小,则按比例缩小并居中 -->
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/ll"
android:id="@+id/iv"
android:scaleType="centerCrop" />
<LinearLayout
android:id="@+id/ll"
android:orientation="vertical"
android:layout_marginBottom="5dp"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textUri"
android:layout_margin="5dp"
android:layout_weight="1"
android:hint="请输入图片的url"
android:ems="10"
android:id="@+id/et"/>
<Button
android:text="浏览"
android:layout_weight="4"
android:onClick="click"
android:layout_width="wrap_content"
android:layout_height="wrap_content" tools:ignore="OnClick"/>
<Button
android:hint="下载"
android:onClick="down"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="1"/>
<Button
android:text="多线程下载"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/mb" android:layout_weight="1"/>
</LinearLayout>
</RelativeLayout>
NetActivity类
package com.br;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class NetActivity extends AppCompatActivity {
protected static final int CHANGE_UI = 1;
protected static final int ERROR = 2;
private EditText editText;
private ImageView imageView;
private Button down;
//主线程创建消息处理器
private Handler handler = new Handler(){
public void handleMessage(android.os.Message message){
Log.i("handleMessage","handleMessage方法里");
if(message.what == CHANGE_UI){
Bitmap bitmap = (Bitmap) message.obj;
//显示图片
imageView.setImageBitmap(bitmap);
}else if(message.what ==ERROR){
Toast.makeText(NetActivity.this,"图片显示错误",Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_net);
imageView = findViewById(R.id.iv);
editText = findViewById(R.id.et);
}
public void click(View view) {
final String path = editText.getText().toString().trim();
if(TextUtils.isEmpty(path)){
Toast.makeText(NetActivity.this,"图片路径不能为空",Toast.LENGTH_SHORT).show();
}
else{
new Thread(){
private HttpURLConnection conn;
private Bitmap bitmap;
//子线程请求网络,Android4.0后访问网络不能放在主线程中
@Override
public void run() {
try {
//创建url对象
URL url = new URL(path);
//根据url发送http请求
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET"); //请求方式为大写
conn.setConnectTimeout(5000); //设置超时时间
int code = conn.getResponseCode(); //获取请求状态码
//请求成功
if(code==200){
//获取输入流
InputStream is = conn.getInputStream();
//将流 转换成bitmap对象
bitmap = BitmapFactory.decodeStream(is);
Message msg = new Message();
msg.what = CHANGE_UI;
msg.obj = bitmap;
handler.sendMessage(msg);
is.close();
}
else { //请求失败
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
}catch (Exception e){
e.printStackTrace();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
conn.disconnect(); //关闭连接
}
}.start();
}
}
public void down(View view) {
final String path = editText.getText().toString().trim();
if(TextUtils.isEmpty(path)){
Toast.makeText(NetActivity.this,"图片路径不能为空",Toast.LENGTH_SHORT).show();
return;
}
//异步操作一定要开辟线程
new Thread(){
@Override
public void run() {
InputStream is = null;
try {
URL url = new URL(path);
//根据url发送http请求
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); //请求方式为大写
conn.setConnectTimeout(5000); //设置超时时间
int contentLength = conn.getContentLength();
Log.i("文件的大小",contentLength+"");
//获取输入流
is = conn.getInputStream();
}catch (Exception e){
}
// 在存储卡下创建文件(sdcard文件夹中)
String files = Environment.getExternalStorageDirectory()+"/";
//path.substring(path.lastIndexOf("."));截取文件后缀名
String fileName = files + "4"+ path.substring(path.lastIndexOf("."));
File file =new File(fileName);
byte[] b = new byte[1024];
try {
OutputStream os = new FileOutputStream(file);
int len=0;
//写入数据
while ((len=is.read(b)) != -1){
os.write(b,0,len);
}
Log.i("msg","文件下载成功");
os.close();
is.close();
}catch (IOException e){
Log.i("msg","文件下载错误");
e.printStackTrace();
}
}
}.start();
}
public void mulDown(View view) {
}
}
最后在AndroidManifest.xml加入这三个权限,若Android6.0以上需动态申请权限
<!-- 网络请求权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- 写入文件权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 读取文件权限 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
本文地址:https://blog.csdn.net/m0_46267375/article/details/110203009
推荐阅读