Intentservice下载图片,常用来下载广告图

用intentservice下载图片并用sp保存路径,方便自己显示

1.咱自己假设一个开始下载按钮

bt.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        Intent  intent = new Intent(MainActivity.this,MyIntentService.class);
        Bundle bundle=new Bundle();
        bundle.putString("url","https://credit-loan.oss-cn-beijing.aliyuncs.com/Uploads/banners/20190424/1556073054941510.png");
        bundle.putString("path",getFilesDir().getAbsolutePath()+"/image/");
        bundle.putString("name","baidu.png");
        bundle.putString("key","path");
        intent.putExtras(bundle);
        startService(intent);
    }
});

2.创建类继承IntentService

public class MyIntentService extends IntentService {
    private  final  String TAG="MyIntentService";
    private String url ;//文件的网络地址
    private String path ;//文件在本地的目录地址
    private String name;//文件的名字
    private String key;//文件路径存储在SP中的key

    /**
     * 构造方法 必须要
     */
    public MyIntentService() {
        //表示这个线程的名字 可随意
        super("MyIntentService");
    }
    //会自动开启线程下载的
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        url = extras.getString("url");
        path = extras.getString("path");
        name=extras.getString("name");
        key=extras.getString("key");
        if (TextUtils.isEmpty(url)||TextUtils.isEmpty(path)||TextUtils.isEmpty(name)||TextUtils.isEmpty(key)){
            Log.i(TAG,"url,path,name,key不能为空");
            return;
        }
        //如果文件夹目录不存在则创建
        File file = new File(path );
        if (!file.exists())
            file.mkdirs();
        downloadFile(url,new File(path+name));
        FileUtils.deleteFile(new File(path),new File(path+name));
    }

    /**
     * 下载文件到本地文件的放法
     * @param downloadUrl    网络地址
     * @param file  本地文件目录
     */
    private void downloadFile(String downloadUrl, File file) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        InputStream ips = null;
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("GET");
            huc.setReadTimeout(10000);
            huc.setConnectTimeout(3000);
            ips = huc.getInputStream();
            // 拿到服务器返回的响应码
            int hand = huc.getResponseCode();
            if (hand == 200) {

                // 建立一个byte数组作为缓冲区,等下把读取到的数据储存在这个数组
                byte[] buffer = new byte[8192];
                int len = 0;
                while ((len = ips.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                saveFileMsg(file);
            } else {
                Log.i(TAG,"网络连接失败");
            }

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (ips != null) {
                    ips.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存文件路劲到sp中
     * @param file
     */
    private void saveFileMsg(File file){
        if (file==null||!file.exists())
            return;
        SharedPreferences sharedPreferences=getSharedPreferences(TAG,0);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(key,file.getAbsolutePath());
        edit.commit();
    }
}

3.项目中用到的工具类FileUtils

public class FileUtils {

    /**
     * 获取文件的MD5值
     * @param file
     * @return
     */
    public  static String getMD5(File file){
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    /**
     * 获取目录下的所有文件
     * @param dir
     * @return
     */
    public static List<File> listFilesInDir(File dir) {
        if (!dir.isDirectory()||!dir.exists()) return null;
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                list.add(file);
                if (file.isDirectory()) {
                    List<File> fileList = listFilesInDir(file);
                    if (fileList != null) {
                        list.addAll(fileList);
                    }
                }
            }
        }
        return list;
    }

    /**
     * 删除除file以外的同目录下的其他文件
     * @param dir
     * @param file
     */
    public  static  void deleteFile(File dir,File file){
        if (!file.exists()) return;
        List<File> files = listFilesInDir(dir);
        for (File file1 : files) {
            String absolutePath = file1.getAbsolutePath();
            Log.i("sss","delete"+absolutePath);
            if (!file.getAbsolutePath().equals(absolutePath)){
                file1.delete();
            }
        }
    }

}

4.这样就完成了,显示下载的图片

SharedPreferences myIntentService = getSharedPreferences("MyIntentService", 0);
String path = myIntentService.getString("path", "");
if (!TextUtils.isEmpty(path)){
    Bitmap bitmap = BitmapFactory.decodeFile(path);
    img.setImageBitmap(bitmap);
}

记得添加权限,清单文件中注册Service

<service android:name=".MyIntentService"></service>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值