Cannot get image from connection, even with INTERNET permissions
I'm having some problems trying to create a Bitmap from a remote URL. Here is the 开发者_如何学JAVAsnippet:
Bitmap bm = null;
URL aURL = null;
try {
aURL = new URL("http://developer.android.com/assets/images/home/honeycomb-android.png");
} catch (MalformedURLException e) {
System.err.println(e);
}
if(aURL != null){
URLConnection conn = null;
BufferedInputStream bis = null;
InputStream is = null;
try {
conn = aURL.openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
} catch (Exception e) {
System.err.println(e);
} finally {
if(bis != null){
try {
bis.close();
} catch (IOException e) {}
}
if(is != null){
try {
is.close();
} catch (IOException e) {}
}
conn = null;
}
}
I'm receiving an exception in the conn.connect()
line.
It says
java.net.SocketException: Permission denied
.
I've already added the permission in the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" package="mypackage.namehere">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name">
</application>
</manifest>
I can load the image both from my computer browser and the emulator browser. There's no firewall blocking my internet connection. Tried with several URLs, but nothing worked.
Am I opening the connection correctly? Should I use HttpConnection instead?
Give this a try.
Bitmap bm = null;
URL aURL = null;
try {
aURL = new URL("http://developer.android.com/assets/images/home/honeycomb-android.png");
} catch (MalformedURLException e) {
System.err.println(e);
}
if(aURL != null){
HttpURLConnection conn = null;
BufferedInputStream bis = null;
InputStream is = null;
try {
conn = (HttpURLConnection) aURL.openConnection();
is = conn.getInputStream();
bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
} catch (Exception e) {
System.err.println(e);
} finally {
if(bis != null){
try {
bis.close();
} catch (IOException e) {}
}
if(is != null){
try {
is.close();
} catch (IOException e) {}
}
conn = null;
}
}
Buddy easy, you are adding the permissions in the wrong place
...
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
</manifest>
after you close can you see?
精彩评论