File download with android

谁都会走 提交于 2019-12-20 04:16:20

问题


I am trying to save a file from the web to my Android device, but I do not know how to do it. The URL address opens a blank page and a popup download box with the file that I want to download so I can choose where to save it.

My problem is that I do not know how to manage that box in order to download the file. It is not like I want to download something that is shown on that page because the page is blank. So I cannot use this code :

         Context context = thisClass.this;
         Drawable image = ImageOperations(context,
          "http://android.okhelp.cz/images/adictionary/ad_4.png"
          ,"image.jpg");
         ImageView imgView;
         imgView = (ImageView)findViewById(R.id.idImageView);
         imgView.setImageDrawable(image);

private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
    try {
        InputStream is = (InputStream) this.fetch(url);
        Drawable d = Drawable.createFromStream(is, "src");
        return d;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

public Object fetch(String address) throws MalformedURLException,IOException {
    URL url = new URL(address);
    Object content = url.getContent();
    return content;
}

I would be grateful if someone could point me where to start looking or gave me a solution.


回答1:


I solved it!

           File card2= Environment.getExternalStorageDirectory();
           File dir2= new File (card2.getAbsolutePath()+"/MyFiles");
            dir2.mkdirs();
           new DefaultHttpClient().execute(new HttpGet(your_url_here-this_is_a_string)).getEntity().writeTo(
            new FileOutputStream(new File(dir2,your_file_on_sdcard-this_is_string)));

This is also surrounded by try/catch. And remember to insert the protocol before the address or it won't work! Hope it helps!



来源:https://stackoverflow.com/questions/8645166/file-download-with-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!