services下载

package com.bawei.day1;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MyIntentService extends IntentService {



    public MyIntentService() {
        super("MyIntentService");
    }



    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i("---ssss","onHandleIntent:" + "你好");
        try {
            URL url = new URL("https://img1.baidu.com/it/u=1960110688,1786190632&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);
            connection.connect();
            if (connection.getResponseCode() == 200){
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                //判断SD卡准备好没有,MEDIA_MOUNTED代表准备好了
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                    //获取SD卡路径
                    File path = Environment.getExternalStorageDirectory();
                    //新建文件
                    File file = new File(path,"ai.jpg");
                    //文件输出流
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    while ((len = inputStream.read()) != -1){
                        //把读取到数据输出到sd卡路径
                        fileOutputStream.write(buffer,0,len);
                    }
                }
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}

//动态注册权限

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        requestPermissions(new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        },101);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值