Java Android程序连接错误
最终,我的目标是获得一个Android应用程序,该应用程序从URL接收XML文件,对其进行解析,并显示相关信息(好吧,最终目标要复杂得多,但这是当前的目标)。我使用的是李伟(Wei Meng Lee)的“开始Android应用程序开发”中的示例,我已经注意到书中示例代码中的一些错误(特别是一个错误的变量,如果Eclipse没有指出它,我会完全忽略它) 然而,目前该应用程序无法连接到互联网,尽管该应用程序拥有许可、访问权限(3g、4g和wifi都经过测试),并且能够在车载浏览器中访问测试URL 下面是相关的代码片段。我做错什么了吗?(注意:我在模拟器和Galaxy S2上都进行了测试) 我尝试了不同的URL,在使用它们之前检查是否可以在手机浏览器中连接到它们。模拟器也没有任何运气 更新:利用以下内容的异步代码:Java Android程序连接错误,java,android,Java,Android,最终,我的目标是获得一个Android应用程序,该应用程序从URL接收XML文件,对其进行解析,并显示相关信息(好吧,最终目标要复杂得多,但这是当前的目标)。我使用的是李伟(Wei Meng Lee)的“开始Android应用程序开发”中的示例,我已经注意到书中示例代码中的一些错误(特别是一个错误的变量,如果Eclipse没有指出它,我会完全忽略它) 然而,目前该应用程序无法连接到互联网,尽管该应用程序拥有许可、访问权限(3g、4g和wifi都经过测试),并且能够在车载浏览器中访问测试URL 下
private class BackgroundTask extends AsyncTask
<String, Void, Bitmap> {
protected Bitmap doInBackground(String... url){
// download an image
Bitmap bitmap = DownloadImage(url[0]);
return bitmap;
}
}
protected void onPostExecute(Bitmap bitmap) {
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}
您希望对任何需要网络连接的任务使用AsyncTask。您可以按如下方式设置异步:(这将字符串作为参数并返回InputStream)
这是在
异步任务中完成的吗?
private class BackgroundTask extends AsyncTask
<String, Void, Bitmap> {
protected Bitmap doInBackground(String... url){
// download an image
Bitmap bitmap = DownloadImage(url[0]);
return bitmap;
}
}
protected void onPostExecute(Bitmap bitmap) {
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackgroundTask().execute("http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif");
}
public class OpenHttpConnection extends AsyncTask<String, Void, InputStream> {
@Override
protected String doInBackground(String... params) {
String urlstring = params[0];
InputStream in = null;
int response = 01;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("Get");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK){
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
}
OpenHttpConnection connection = new OpenHttpConnection().execute("http://YourURL.com");
InputStream is = connection.get();