兼容Android2.2,用反射方式使用DownloadManager

在Android2.2系统中,直接使用DownloadManager会导致应用崩溃,因为该类在低版本中不存在。通过反射技术,可以实现对DownloadManager的调用,以确保在2.2及以下版本的兼容性,这是Google推荐的向下兼容策略。
摘要由CSDN通过智能技术生成
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推荐的向下兼容的方法。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值