2010年7月1日星期四

從網絡加載圖像視圖(ImageView)

從網絡加載圖像視圖(ImageView)

修改清單文件(AndroidManifest.xml), 添加 Internet訪問權限, <uses-permission android:name="android.permission.INTERNET" />.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.AndroidImage"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidImage"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>


仍沿用上文"從內部文件 夾加載圖像視圖(ImageView)"中main.xml

AndroidImage.java
package com.AndroidImage;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidImage extends Activity {

private String imageFileURL = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhuy2cXRN6hyphenhyphenA6L1PYzdV77gMWfNPpMp0HzE1a6Qh3cvF3ibtUSv2UYr5F6YyT2Dzmo78479nzaN51dShCy0yJB2HRdHn3krcTuTL2eBeHClUSzyNjUZz9kmZkRVmJ1t17yU89Lz_JlqrzV/s150/androidbiancheng.png";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ImageView myImageView = (ImageView)findViewById(R.id.imageview);

try {
URL url = new URL(imageFileURL);
URLConnection conn = url.openConnection();

HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();

if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();

Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
myImageView.setImageBitmap(bitmap);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


相關文章:
從內部文件夾加載圖像視圖(ImageView)
從SD Card加載圖像視圖(ImageView)
利用BitmapFactory.Options的inSampleSize對bitmap進行優化

沒有留言:

發佈留言