MainActivity如下:
package cc.testwebsiteicon;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
/**
* Demo描述:
* 获取网址前的网站Icon图片.
* 主要的是利用了谷歌提供的服务来获取facicon图片
*
* 注意权限:
* <uses-permission android:name="android.permission.INTERNET"/>
*
* 参考资料:
* http://blog.chengyunfeng.com/?p=523
* Thank you very much
*/
public class MainActivity extends Activity {
private ImageView mImageView;
private Bitmap mBitmap;
private Thread mThread;
private Handler mHandler;
private final int SUCCESS=9527;
private final String FAVICON_SERVICE="http://www.google.com/s2/favicons?domain=";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init(){
mImageView = (ImageView) findViewById(R.id.imageView);
mThread=new Thread(){
@Override
public void run() {
super.run();
loadFavIcon();
}
};
mThread.start();
mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what==SUCCESS) {
mImageView.setImageBitmap(mBitmap);
}
}
};
}
private void loadFavIcon(){
try {
InputStream inputStream = null;
String favIconPathString = FAVICON_SERVICE+"http://www.ifeng.com/";
URL imageUrl = new URL(favIconPathString);
HttpURLConnection httpURLConnection = (HttpURLConnection) imageUrl.openConnection();
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("GET");
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
mBitmap = BitmapFactory.decodeStream(inputStream);
mHandler.sendEmptyMessage(SUCCESS);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>