给定一张图片的Url,我想要在我的安卓应用中将其下载并粘贴到画布上。如何将这张图片检索到我的应用程序中?
请帮忙。
谢谢, de costo.
请帮忙。
谢谢, de costo.
<uses-permission android:name="android.permission.INTERNET" />
现在可能有一个支持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堆可供使用,而且很快就会用完,如果您不能非常好地归还内存资源,垃圾收集器会让您发疯。
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" />