从url下载图像并将其显示到真实的设备库android?

时间:2014-04-05 07:32:51

标签: android memory internal

使用此代码从内部存储中的url下载图像。它工作正常,并在模拟器中显示图像但在真实设备上调试时,它给出了空的帮助......

File fileWithinMyDir = getApplicationContext().getFilesDir();
downloadImage(url1, fileWithinMyDir.getAbsolutePath()+MODE_WORLD_READABLE + "/" +"image1.jpg");

public boolean downloadImage(String URL,String fileName){

        try 
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            URL url = new URL(URL);
            File file = new File(fileName);
            URLConnection ucon = url.openConnection();
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) 
            {
                baf.append((byte) current);
            }

            FileOutputStream fos = new FileOutputStream(file,true);
            fos.write(baf.toByteArray());
            fos.close();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

1 个答案:

答案 0 :(得分:0)

如果您的设备使用USB线连接,请运行App&从USB电缆上取下设备并进行检查。我跳它会工作。 并且它将无法使用以下代码

        String serverURL1 = "enter your image url";
                        new imageFile().execute(serverURL1);


public class imageFile extends AsyncTask<String,Void,Void>
{
    private Context context;    
    public void setContext(Context contextf)
    {
        context = contextf;
    }
    protected Void doInBackground(String... arg0) 
    {
        try
        {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.connect();    
            File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"SD card path");
            FileOutputStream f = new FileOutputStream(myFile);
            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;

            while ( (len1 = in.read(buffer)) > 0 )
            {
                f.write(buffer,0, len1);    
            }
            f.close();

            }
        catch (Exception e)
        {
            Log.e("imageFile", "Update error! " + e.getMessage());
        }
        return null;
    }}  
//Animation class focus on windows button change 
public void onWindowFocusChanged(boolean hasFocus)
{
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) 
    {
        frameAnimation.start();
    }
    else 
    {
        frameAnimation.stop();
    }
}