Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android查看網絡圖片例子

Android查看網絡圖片例子

編輯:關於Android編程

1.布局文件




    
    
    
        
        

2.主程序中實現

package com.wzw.netphoto;

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

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	private ImageView ivIcon;
	private EditText etUrl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ivIcon = (ImageView) findViewById(R.id.iv_icon);
		etUrl = (EditText) findViewById(R.id.et_url);
		Button btn=(Button) findViewById(R.id.btn_submit);
		btn.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		String url=etUrl.getText().toString();
		
		Bitmap bit=getImageFromNet(url);
		ivIcon.setImageBitmap(bit);
		
	}
	
	public Bitmap getImageFromNet(String url){
		try {
			
			URL mUrl=new URL(url);//創建URL對象
			HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
			conn.setRequestMethod("GET");
			
			conn.setConnectTimeout(10000);  //設置連接超時時間
			conn.setReadTimeout(5000);		//設置讀取超時時間
			conn.connect();
			int responseCode = conn.getResponseCode();
			if(responseCode==200){
				InputStream is = conn.getInputStream();
				Bitmap bitmap=BitmapFactory.decodeStream(is);
				Toast.makeText(this, "獲取成功", 0).show();
				return bitmap;
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		return null;
	}

}

3.添加網絡訪問權限




    
    

    
        
            
                

                
            
        
    




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