如果我尝试从网站下载图像(使用http连接),如果在我的Android服务中执行下载,则没有问题,而如果我尝试从活动中下载文件的相同方法,则会发生此错误:
11-08 13:27:36.800: W/System.err(8010): android.os.NetworkOnMainThreadException
11-08 13:27:36.800: W/System.err(8010): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
11-08 13:27:36.800: W/System.err(8010): at java.net.InetAddress.lookupHostByName(InetAddress.java:477)
11-08 13:27:36.800: W/System.err(8010): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277)
11-08 13:27:36.800: W/System.err(8010): at java.net.InetAddress.getAllByName(InetAddress.java:249)
11-08 13:27:36.800: W/System.err(8010): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
11-08 13:27:36.800: W/System.err(8010): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
11-08 13:27:36.800: W/System.err(8010): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:304)
11-08 13:27:36.800: W/System.err(8010): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
11-08 13:27:36.800: W/System.err(8010): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:292)
11-08 13:27:36.800: W/System.err(8010): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:274)
11-08 13:27:36.800: W/System.err(8010): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1038)
11-08 13:27:36.800: W/System.err(8010): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHeaderField(HttpURLConnectionImpl.java:481)
11-08 13:27:36.800: W/System.err(8010): at java.net.URLConnection.getHeaderFieldInt(URLConnection.java:572)
11-08 13:27:36.800: W/System.err(8010): at java.net.URLConnection.getContentLength(URLConnection.java:335)
我以这种方式解决了从Activity调用我的下载方法的问题:
new Thread(new Runnable() {
public void run() {
downloadFile(imagePath);
}
}).start();
答案 0 :(得分:2)
Cehck这个
NetworkOnMainThreadException :应用程序尝试在其主线程上执行网络操作时引发的异常。
你应该在asynctask上调用sendfeedback方法然后只有上面的代码才能工作。由于网络服务器花费了大量时间来响应主线程变得反应迟钝。要避免它,你应该在另一个线程上调用它。因此asynctask更好。
http://android-developers.blogspot.in/2009/05/painless-threading.html
答案 1 :(得分:0)
尝试此代码从网上下载图片。
String myfeed="your url";
URL url;
try {
url = new URL(myfeed);
InputStream content = (InputStream)url.getContent();
d = Drawable.createFromStream(content , "src");
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
String path = Images.Media.insertImage(getContentResolver(),bitmap,mImageName, null);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在您的活动中添加此内容
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);