Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android--消息機制--handler--getImageFromUrl--網絡上獲取圖片

Android--消息機制--handler--getImageFromUrl--網絡上獲取圖片

編輯:關於Android編程


package com.jiangge.imageviewer;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
	ImageView imageView;
	EditText editPath;
	Handler hadHandler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageView = (ImageView) findViewById(R.id.image_view);
		editPath = (EditText) findViewById(R.id.it_path);
		hadHandler = new Handler();
	}

	public void click(View view){
		final String path = editPath.getText().toString().trim();
		if (TextUtils.isEmpty(path)) {
			Toast.makeText(this,"路徑不能為空", Toast.LENGTH_LONG).show();
			return;
		}
		new Thread(){
			public void run(){
				try {
					URL url = new URL(path);
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.setRequestMethod("GET");
					conn.setConnectTimeout(5000);
//					conn.setReadTimeout();
					conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
					int code = conn.getResponseCode();
					System.out.println("===>>>" + code);
					if (code == 200) {
						InputStream is = conn.getInputStream();
						final Bitmap bitmap = BitmapFactory.decodeStream(is);
						hadHandler.post(new Runnable() {
							
							@Override
							public void run() {
								imageView.setImageBitmap(bitmap);
							}
						});
						
					}else {
						Toast.makeText(MainActivity.this,"獲取圖片失敗", Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(MainActivity.this,"獲取圖片失敗", Toast.LENGTH_LONG).show();
				}
			}
		}.start();
		
	}
}


布局文件:



    

    
    

    



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved