1. 在此实例中,重点展示使用Android平台提供的互联网网络访问方式以及图片显示问题.
按照如下的配置以及在开发循序渐进实例1中描述的方法创建整个项目Base:
project Name: ExampleFive
Platform: Android2.0;
Application name: ExampleFive
package name: com.example
Activity: MainActivity
Resource file: main.xml
此Resource文件没有任何资源配置;
在AndroidManifest.xml中选择Permissions->Add...->选择Uses Permission->点击OK,在右边的Attributes for Uses Permission下面的下拉列表中选择android.permission.INTERNET->选择CTRL+S保存结果。
2. 在MainActivity中加入如下的代码显示函数:
private void showImage() {
ImageView iv = new ImageView(this);
iv.setBackgroundColor(0xFFFFFFFF);
iv.setScaleType(ScaleType.FIT_CENTER);
iv.setLayoutParams(new Gallery.LayoutParams(40, 40));
downloadAndShowInternetFile("http://www.twicular.com/images/top_07.png", iv);
this.setContentView(iv);
}
void downloadAndShowInternetFile(String url, ImageView iv) {
URL internetUrl = null;
try {
internetUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) internetUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bmImg = BitmapFactory.decodeStream(is);
iv.setImageBitmap(bmImg);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
3. 在MainActivity中的onCreate()重载函数添加如下的调用代码:
showImage();
4. 运行即可看到首页显示的是一张图片(Twicular公司的LOGO);
本文介绍了一个简单的Android应用实例,展示了如何使用Android平台的网络访问功能从互联网下载图片,并将其显示在ImageView组件上。通过示例代码,读者可以了解具体的实现步骤。

被折叠的 条评论
为什么被折叠?



