Android 下载指定url

 

 

/**
     * 下载APK
     **/
    private void downloadApk() {
//        String apkUrl = "http://192.168.1.1/downloadtest.apk";
        String apkUrl = "http://apk-cdn.zhangxinhulian.com/com.zxhl.weather-guanwang-1.0.6_106_jiagu.apk";
        Uri uri = Uri.parse(apkUrl);
        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        // 设置允许使用的网络类型,这里是移动网络和wifi都可以
        request.setAllowedNetworkTypes(request.NETWORK_MOBILE | request.NETWORK_WIFI);
        //设置是否允许漫游
        request.setAllowedOverRoaming(false);
        //设置文件类型
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(apkUrl));
        request.setMimeType(mimeString);
        //在通知栏中显示
        request.setNotificationVisibility(request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle("download...");
        request.setVisibleInDownloadsUi(true);
        //sdcard目录下的download文件夹
//        SDCardUtils.deleteFile(qq_otherList.get(i).getPath());
        String installPath="sdcard/download/"+pathFile+".apk";
        if (fileIsExists(installPath)){
            SDCardUtils.deleteFile(installPath);
        }
        request.setDestinationInExternalPublicDir("/sdcard/download/", pathFile + ".apk");
        // 将下载请求放入队列

        cachedThreadPool.submit(new Runnable() {
            @Override
            public void run() {
                downloadManager.enqueue(request);
            }
        });
    }


    /**
     * 判断文件是否存在
     * */
    public boolean fileIsExists(String strFile) {
        try {
            File f=new File(strFile);
            if(!f.exists()) {
                return false;
            }
        }
        catch (Exception e) {
            return false;
        }
        return true;
    }


    /**
     * 删除文件
     * @param path
     */
    public static void deleteFile(String path){
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }

 

 

你可能感兴趣的:(Android 下载指定url)