废话就不多说了直接看下怎么实现
1.添加相关的权限,设备API大于6.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" />
//设备API大于6.0 时,主动申请权限
private void requestPermission(Activity context) {
if (Build.VERSION .SDK _INT >= Build.VERSION _CODES.M ) {
if (ContextCompat.checkSelfPermission (context, Manifest.permission .WRITE _EXTERNAL_STORAGE)
!= PackageManager.PERMISSION _GRANTED) {
ActivityCompat.requestPermissions (context, new String[]{Manifest.permission .WRITE _EXTERNAL_STORAGE,
Manifest.permission .READ _EXTERNAL_STORAGE}, 0 )
}
}
}
2.连接服务器获取文件
/**
* 从服务器下载文件
* @param path 下载文件的地址
* @param FileName 文件名字
*/
public static void downLoad (final String path, final String FileName) {
new Thread(new Runnable() {
@Override
public void run () {
try {
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(5000 );
con.setConnectTimeout(5000 );
con.setRequestProperty("Charset" , "UTF-8" );
con.setRequestMethod("GET" );
if (con.getResponseCode() == 200 ) {
InputStream is = con.getInputStream();
FileOutputStream fileOutputStream = null ;
if (is != null ) {
FileUtils fileUtils = new FileUtils();
fileOutputStream = new FileOutputStream(fileUtils.createFile(FileName));
byte [] buf = new byte [1024 ];
int ch;
while ((ch = is.read(buf)) != -1 ) {
fileOutputStream.write(buf, 0 , ch);
}
}
if (fileOutputStream != null ) {
fileOutputStream.flush();
fileOutputStream.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
3.创建文件保存路径
public class FileUtils {
private String path = Environment.getExternalStorageDirectory().toString() + "/shidoe" ;
public FileUtils () {
File file = new File(path);
/**
*如果文件夹不存在就创建
*/
if (!file.exists()) {
file.mkdirs();
}
}
/**
* 创建一个文件
* @param FileName 文件名
* @return
*/
public File createFile (String FileName) {
return new File(path, FileName);
}
}
4.下载示例
downLoad("http://www.shidoe.com/shidoe/Edition/upfile/04.png" , "che.png" ) ;
5.动态获取需要保存文件的文件名
String s = "http://www.shidoe.com/shidoe/Edition/upfile/04.png" ;
int i = s.lastIndexOf("/" );
String FileName= s.substring(i + 1 );
6.加载刚下载好的图片显示在界面上还是非常easy的
private void loadImage () {
String path = Environment.getExternalStorageDirectory().toString() + "/shidoe" ;
try {
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(new File(path, "che.png" )));
iv.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
如果帮到了你就帮忙顶一下吧