如何在安卓中使用图片URL?

5
给定一张图片的Url,我想要在我的安卓应用中将其下载并粘贴到画布上。如何将这张图片检索到我的应用程序中?
请帮忙。
谢谢, de costo.
3个回答

11
不要忘记在AndroidManifest.xml中为应用程序授予权限连接到Web。
<uses-permission android:name="android.permission.INTERNET" />

5

现在可能有一个支持Android的HTTP客户端库,但如果需要更精细的控制,可以使用URL和HttpURLConnection。代码将类似于以下内容:

URL connectURL = new URL(<your URL goes here>);
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection(); 

// do some setup
conn.setDoInput(true); 
conn.setDoOutput(true); 
conn.setUseCaches(false); 
conn.setRequestMethod("GET"); 

// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();

// now fetch the results
String response = getResponse(conn);

如果您的getResponse()返回一堆二进制数据,您可能需要将StringBuffer更改为字节数组,并按较大的增量分块读取。

private String getResponseOrig(HttpURLConnection conn)
{
    InputStream is = null;
    try 
    {
        is = conn.getInputStream(); 
        // scoop up the reply from the server
        int ch; 
        StringBuffer sb = new StringBuffer(); 
        while( ( ch = is.read() ) != -1 ) { 
            sb.append( (char)ch ); 
        } 
        return sb.toString(); 
    }
    catch(Exception e)
    {
       Log.e(TAG, "biffed it getting HTTPResponse");
    }
    finally 
    {
        try {
        if (is != null)
            is.close();
        } catch (Exception e) {}
    }

    return "";
}

由于您提到的图像数据可能很大,因此在Android中,您需要非常努力确保尽快释放内存。所有应用程序只有16mb堆可供使用,而且很快就会用完,如果您不能非常好地归还内存资源,垃圾收集器会让您发疯。


在桌面上运行的模拟器是否允许应用程序连接到互联网?我认为我的模拟器不允许设备连接到互联网。 - Vishnu Pedireddi

5
您可以使用以下代码下载图像:
URLConnection connection = uri.toURL().openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 8 * 1024);
Bitmap bmp = BitmapFactory.decodeStream(bis);
bis.close();
is.close(); 

需要在 AndroidManifest.xml 中添加以下权限:

<uses-permission android:name="android.permission.INTERNET" />

如果您想设置头文件和读取状态代码,请将连接转换为HttpURLConnection。 - ThomasRS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接