public class DownloadUtil {
public static void DownloadFile(Context context,String url,String path){
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
String file = Environment.getExternalStorageDirectory().getPath() +path;
File files = new File(file);
if (files == null || !files.exists()) {
files.mkdir();
}
String fileName = url.substring(url.lastIndexOf("/") + 1);
fileName = URLDecoder.decode(fileName);
try {
Object downManager = context.getSystemService("download");
Class down = Class.forName("android.app.DownloadManager$Request");
if (downManager != null && down != null) {
Object downInstance = down.getConstructor(Uri.class).newInstance(Uri.parse(url));
down.getDeclaredMethod("setShowRunningNotification", boolean.class).invoke(downInstance, true);
down.getDeclaredMethod("setVisibleInDownloadsUi", boolean.class).invoke(downInstance, true);
down.getDeclaredMethod("setDestinationInExternalPublicDir", String.class, String.class).invoke(downInstance, path+"/",fileName);
Class.forName("android.app.DownloadManager").getDeclaredMethod("enqueue",downInstance.getClass()).invoke(downManager, downInstance);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
注解的NewAPI只是保证编译不报错而已,不保证能够在2.2系统上正确的跑起来,事实上如果直接在2.2系统上跑带DownloadManager的程序会直接Crash。
以及不要做梦以为用个if判断就可以了,因为2.2上根本没这个类,光是import就报错了。
使用反射方法可以保证这个下载在2.2以下版本跑可以不崩溃,也是Google推荐的向下兼容的方法。