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); } }