標籤:
一、網路操作
在網路操作中JAVA已經為我提供了一套API用來進行網路操作,在android開發中我們仍可以這套API來做開發。下面通過一個簡單的例子來瞭解一下android下的網路操作。
點擊圖中下載按鈕從伺服器上下載一張圖片下來
二、xml布局檔案
布局檔案採用線性布局,只使用到一個button和一個image
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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" android:orientation="vertical" tools:context="xidian.dy.com.chujia.MainActivity"> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/delete" /> <ImageView android:id="@+id/img" android:layout_width="100dp" android:layout_height="100dp" android:src="@drawable/dog1" /></LinearLayout>
三、MainActivity.java
在代碼中當點擊事件發生後,就通過通過URL來建立一個HttpURLConnection對象來像伺服器建立串連,發起HTTP請求。當請求成功後,表明資料已經在記憶體中。這時,我們應該從記憶體中拿到資料並將其封裝成一個bitmap對象,這個對象是android提供的,專門用來將從互連網上download的圖片直接顯示。這些操作我們都放在子線程中,一個原因是google要求必須這樣,另一方面
package xidian.dy.com.chujia;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class MainActivity extends AppCompatActivity { private static ImageView img; static MainActivity ma; static Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.btn); ma = this; handler = new Handler(){ @Override //此方法在主線程中重新整理UI public void handleMessage(Message msg) { if(img != null){ if(msg.what == 0) img.setImageBitmap((Bitmap)msg.obj); else Toast.makeText(ma,"圖片下載失敗",Toast.LENGTH_SHORT).show(); } } }; if(btn != null) btn.setOnClickListener(new MyLister()); } class MyLister implements View.OnClickListener{ @Override public void onClick(View v) { img = (ImageView) findViewById(R.id.img); new Thread(){ @Override public void run() { try { URL url = new URL("http://192.168.0.119/dog.jpg"); //建立連線物件 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //佈建要求方式 conn.setRequestMethod("GET"); //設定TCP連線逾時 conn.setConnectTimeout(5000); //設定http響應逾時 conn.setReadTimeout(5000); //建立串連 conn.connect(); Message msg = handler.obtainMessage(); if(conn.getResponseCode() == 200){ InputStream is = conn.getInputStream(); Bitmap bm = BitmapFactory.decodeStream(is); msg.what = 0; msg.obj = bm; handler.sendMessage(msg); } else { msg.what = 1; handler.sendMessage(msg); } Toast.makeText(MainActivity.this, "下載失敗", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } }.start(); } }}
android之網路操作(1)