Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android網絡通信方式總結

android網絡通信方式總結

編輯:關於Android編程

1995年1G問世,手機只能進行基本的語音通訊,1996-1997年2G(GSM,CDMA)及其後的GPRS,EDGE等技術的快速發展,手機開始逐漸增加了數據服務功能。2009年開始,3G在全世界開始大規模布置以及蘋果創造性開發新型蘋果手機。手機慢慢的變成互聯網的終端,從而帶動了一個新的時代--移動互聯網時代。因此現代手機通常都支持這些常用網絡設備,如WIFI,NFC,藍牙等。

在Android中幾種網絡編程的方式:

1、針對TCP/IP的Socket、ServerSocket

TCP/IP是一種協議,是一種面向連接的、可靠的協議。Socket僅僅是對TCP、UDP網絡接口的封裝,不涉及上層協議。

示例代碼:

(1)android客戶端

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//客戶端的實現
public class TestSocket extends Activity {
	private TextView text1;
	private Button but1;
	private EditText edit1;
	private final String DEBUG_TAG="mySocketAct";


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        text1=(TextView)findViewById(R.id.text1);
        but1=(Button)findViewById(R.id.but1);
        edit1=(EditText)findViewById(R.id.edit);
        
        but1.setOnClickListener(new Button.OnClickListener()
        {
        	@Override
			public void onClick(View v) {
				Socket socket=null;
				String mesg=edit1.getText().toString()+"\r\n";
				edit1.setText("");
				Log.e("dddd", "sent id");
				
				try { 
					socket=new Socket("172.22.122.1",54321);
					//向服務器發送信息
					PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
					out.println(mesg);
					
					//接受服務器的信息
					BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
					String mstr=br.readLine();
					if(mstr!=null)
					{
						text1.setText(mstr);
					}else
					{
						text1.setText("數據錯誤");
					}
					out.close();
					br.close();
					socket.close();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}catch(Exception e)
				{
					Log.e(DEBUG_TAG,e.toString());
				}
			}        	
        });
    }
}
(2)服務端代碼

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;


public class AndroidServer implements Runnable{
	public void run() {
		try {
			ServerSocket serverSocket=new ServerSocket(54321);
			while(true)
			{
				System.out.println("等待接收用戶連接:");
				//接受客戶端請求
				Socket client=serverSocket.accept();
				try
				{
					//接受客戶端信息
					BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));
					String str=in.readLine();
					System.out.println("read:  "+str);
					//向客戶端發送消息
					PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
					out.println("return	"+str);
					in.close();
					out.close();
				}catch(Exception ex)
				{
					System.out.println(ex.getMessage());
					ex.printStackTrace();
				}
				finally
				{
					client.close();
					System.out.println("close");
				}
			}
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	public static void main(String [] args)
	{
		Thread desktopServerThread=new Thread(new AndroidServer());
		desktopServerThread.start();
	}
}

2、針對UDP的DatagramSocket、DatagramPackage。

對於UDP服務端,首先啟動偵聽服務,然後得到數據包進行處理,組後根據獲得數據包進行反饋。UDP socket沒有連接的概念,因此構造完成的DatagramSocket不會發出向對端的網絡連接請求,在每一個發送的UDP數據包中包含目的地址和端口。因為UDP數據不會在對端進行重新組包,因此一次發送的數據長度必須加以限制。Socket.send(outputPacket);用於發送一個數據包;socket.receive(inputPacket);用於接收一個數據包。

示例代碼:

(1)客戶端代碼

public class TestClient {
	static DatagramSocket socket;

	public TestClient() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 * @param ip
	 *            ip地址
	 * @param port
	 *            端口
	 * @param str
	 *            發送的內容
	 */
	public static String clientUDP(String ip, int port, String str) {
		String result = null;
		while (true) {
			try {

				byte[] outputData = str.getBytes();
				// UDP socket 數據發送
				socket = new DatagramSocket();
				DatagramPacket outputPacket = new DatagramPacket(outputData,
						outputData.length, InetAddress.getByName(ip), port);
				socket.send(outputPacket);

				// udp 數據讀取
				DatagramPacket inputPacket = new DatagramPacket(new byte[512],
						512);
				socket.receive(inputPacket);
				System.out.println(new String(inputPacket.getData(), 0,
						inputPacket.getLength()));
				result = new String(inputPacket.getData(), 0,
						inputPacket.getLength());

			} catch (Exception e) {
				e.printStackTrace();
			}
			if (socket != null) {
				socket.close();
			}

			return result;
		}
	}
}



(2)服務端代碼

package server;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.text.SimpleDateFormat;
import java.util.Date;




public class UDPServer{
    public static void main(String[] args) throws Exception{
            DatagramSocket udpSocket = new DatagramSocket(8080);
            while(true){
                    try{
                            // UDP數據讀取
                            DatagramPacket packet = new DatagramPacket(new byte[512],512);
                            udpSocket.receive(packet);
                            String msg = new String(packet.getData(), 0,packet.getLength());
                            System.out.println(msg);
                            if(msg.equals("exit")){
                                    break;
                            }
                            
                            // UDP數據發送
                            SimpleDateFormat f = new SimpleDateFormat("MMM dd,yyyy kk:mm:ss");
                            String time = "現在的時間是:" + f.format(new Date());
                            System.out.println(time );
                            packet.setData(time.getBytes());
                            udpSocket.send(packet);
                            
                    }catch(Exception e){
                            e.printStackTrace();
                    }
            }
            udpSocket.close();
    }
}



3、針對直接URL的HttpURLConnection

(1)GET方式

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

import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {

	private static String URL_PATH = "http://192.168.0.102:8080/myhttptest/pro1.png";

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

	public static void saveImageToDisk() {
		InputStream inputStream = getInputStream();
		byte[] data = new byte[1024];
		int len = 0;
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream("C:\\test.png");
			while ((len = inputStream.read(data)) != -1) {
				fileOutputStream.write(data, 0, len);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 獲得服務器端的數據,以InputStream形式返回
	 * @return
	 */
	public static InputStream getInputStream() {
		InputStream inputStream = null;
		HttpURLConnection httpURLConnection = null;
		try {
			URL url = new URL(URL_PATH);
			if (url != null) {
				httpURLConnection = (HttpURLConnection) url.openConnection();
				// 設置連接網絡的超時時間
				httpURLConnection.setConnectTimeout(3000);
				httpURLConnection.setDoInput(true);
				// 表示設置本次http請求使用GET方式請求
				httpURLConnection.setRequestMethod("GET");
				int responseCode = httpURLConnection.getResponseCode();
				if (responseCode == 200) {
					// 從服務器獲得一個輸入流
					inputStream = httpURLConnection.getInputStream();
				}
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return inputStream;
	}

	public static void main(String[] args) {
		// 從服務器獲得圖片保存到本地
		saveImageToDisk();
	}
}

(2)POST方式

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {

	// 請求服務器端的url
	private static String PATH = "http://192.168.0.102:8080/myhttptest/servlet/LoginAction";
	private static URL url;

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

	static {
		try {
			url = new URL(PATH);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param params
	 *            填寫的url的參數
	 * @param encode
	 *            字節編碼
	 * @return
	 */
	public static String sendPostMessage(Map params,
			String encode) {
		// 作為StringBuffer初始化的字符串
		StringBuffer buffer = new StringBuffer();
		try {
			if (params != null && !params.isEmpty()) {
				  for (Map.Entry entry : params.entrySet()) {
						// 完成轉碼操作
						buffer.append(entry.getKey()).append("=").append(
								URLEncoder.encode(entry.getValue(), encode))
								.append("&");
					}
				buffer.deleteCharAt(buffer.length() - 1);
			}
			// System.out.println(buffer.toString());
			// 刪除掉最有一個&
			
			System.out.println("-->>"+buffer.toString());
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();
			urlConnection.setConnectTimeout(3000);
			urlConnection.setRequestMethod("POST");
			urlConnection.setDoInput(true);// 表示從服務器獲取數據
			urlConnection.setDoOutput(true);// 表示向服務器寫數據
			// 獲得上傳信息的字節大小以及長度
			byte[] mydata = buffer.toString().getBytes();
			// 表示設置請求體的類型是文本類型
			urlConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			urlConnection.setRequestProperty("Content-Length",
					String.valueOf(mydata.length));
			// 獲得輸出流,向服務器輸出數據
			OutputStream outputStream = urlConnection.getOutputStream();
			outputStream.write(mydata,0,mydata.length);
			outputStream.close();
			// 獲得服務器響應的結果和狀態碼
			int responseCode = urlConnection.getResponseCode();
			if (responseCode == 200) {
				return changeInputStream(urlConnection.getInputStream(), encode);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 將一個輸入流轉換成指定編碼的字符串
	 * 
	 * @param inputStream
	 * @param encode
	 * @return
	 */
	private static String changeInputStream(InputStream inputStream,
			String encode) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if (inputStream != null) {
			try {
				while ((len = inputStream.read(data)) != -1) {
					outputStream.write(data, 0, len);
				}
				result = new String(outputStream.toByteArray(), encode);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map params = new HashMap();
		params.put("username", "admin");
		params.put("password", "1234");
		String result = HttpUtils.sendPostMessage(params, "utf-8");
		System.out.println("--result->>" + result);
	}

}


(3)HttpClient

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

	public static String sendHttpClientPost(String path,
			Map map, String encode) {
		List list = new ArrayList();
		if (map != null && !map.isEmpty()) {
			for (Map.Entry entry : map.entrySet()) {
				list.add(new BasicNameValuePair(entry.getKey(), entry
						.getValue()));
			}
		}
		try {
			// 實現將請求的參數封裝到表單中,請求體重
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
			// 使用Post方式提交數據
			HttpPost httpPost = new HttpPost(path);
			httpPost.setEntity(entity);
			// 指定post請求
			DefaultHttpClient client = new DefaultHttpClient();
			HttpResponse httpResponse = client.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				return changeInputStream(httpResponse.getEntity().getContent(),
						encode);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 將一個輸入流轉換成指定編碼的字符串
	 * 
	 * @param inputStream
	 * @param encode
	 * @return
	 */
	public static String changeInputStream(InputStream inputStream,
			String encode) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if (inputStream != null) {
			try {
				while ((len = inputStream.read(data)) != -1) {
					outputStream.write(data, 0, len);
				}
				result = new String(outputStream.toByteArray(), encode);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String path = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";
		Map params = new HashMap();
		params.put("username", "admin");
		params.put("password", "123");
		String result = HttpUtils.sendHttpClientPost(path, params, "utf-8");
		System.out.println("-->>"+result);
	}

}

4、使用Web Service。Android可以通過開源包如jackson去支持Xmlrpc和Jsonrpc,另外也可以用Ksoap2去實現Webservice

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

/**
 * 在這個幫助類中,根據文檔說明和URL地址
 * 先獲取支持的省份信息
 * 再根據某一個省份獲取城市信息
 * 再根據城市信息獲取天氣情況
 * 
 *
 */
public class WebServiceHelper {
	public static final String TAG = "WebServiceHelper";
	
	// WSDL文檔中的命名空間
	private static final String targetNameSpace = "http://WebXml.com.cn/";
	// WSDL文檔中的URL
	private static final String WSDL = "http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";	
	// 需要調用的方法名(獲得本天氣預報Web Services支持的洲、國內外省份和城市信息)
	private static final String getSupportProvince = "getSupportProvince";
	// 需要調用的方法名(獲得本天氣預報Web Services支持的城市信息,根據省份查詢城市集合:帶參數)
	private static final String getSupportCity = "getSupportCity";
	// 根據城市或地區名稱查詢獲得未來三天內天氣情況、現在的天氣實況、天氣和生活指數
	private static final String getWeatherbyCityName = "getWeatherbyCityName";

	/**
	 * 根據最新的文檔,接口好像變了。。。囧
	 * 獲得州,國內外省份和城市信息 
	 * @return
	 */
	public List getProvince() {
		List provinces = new ArrayList();
	 
		SoapObject soapObject = new SoapObject(targetNameSpace, getSupportProvince);
		// request.addProperty("參數", "參數值");調用的方法參數與參數值(根據具體需要可選可不選)
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(soapObject);
		// envelope.bodyOut=request;
		AndroidHttpTransport httpTranstation = new AndroidHttpTransport(WSDL);
		// 或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
		
		try {
			httpTranstation.call(targetNameSpace + getSupportProvince, envelope);
			Log.i(TAG, targetNameSpace + getSupportProvince);
			
			SoapObject result = (SoapObject) envelope.getResponse();
			// 下面對結果進行解析,結構類似json對象
			Log.i(TAG, ""+result.getPropertyCount());
			int count = result.getPropertyCount();
			for (int index = 0; index < count; index++) {
				provinces.add(result.getProperty(index).toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
		
		return provinces;
	}

	/**
	 * 根據省份或者直轄市獲取天氣預報所支持的城市集合
	 * 比如內蒙古-->【赤峰市、呼市、包頭等。。。】 
	 * @param province 
	 * @return
	 */
	public List getCitys(String province) {
		List citys = new ArrayList();
		
		SoapObject soapObject = new SoapObject(targetNameSpace, getSupportCity);
		soapObject.addProperty("byProvinceName", province);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(soapObject);
		AndroidHttpTransport httpTransport = new AndroidHttpTransport(WSDL);
		
		try {
			httpTransport.call(targetNameSpace + getSupportCity, envelope);
			SoapObject result = (SoapObject) envelope.getResponse();
			int count = result.getPropertyCount();
			for (int index = 0; index < count; index++) {
				citys.add(result.getProperty(index).toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
		return citys;
	}

	/**
	 * 根據城市信息獲取天氣預報信息
	 * @param city
	 * @return
	 **/
	@SuppressWarnings("deprecation")
	public WeatherBean getWeatherByCity(String city) {
		 
		WeatherBean bean = new WeatherBean();
		
		SoapObject soapObject = new SoapObject(targetNameSpace, getWeatherbyCityName);
		city = city.substring(0,city.length()-7);
		Log.i(TAG, "city="+city); 
		soapObject.addProperty("theCityName", city);   // 調用的方法參數與參數值(根據具體需要可選可不選)
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(soapObject);
		envelope.bodyOut = soapObject;
		
		AndroidHttpTransport httpTranstation = new AndroidHttpTransport(WSDL);
		// 或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
		httpTranstation.debug = true;
		
		try {
			httpTranstation.call(targetNameSpace + getWeatherbyCityName, envelope);
			
			SoapObject result = (SoapObject) envelope.getResponse();
			if(result != null){
				Log.i(TAG, "result = " + result);
				
				// 下面對結果進行解析,結構類似json對象
				bean = parserWeather(result);
				
			}else{
				Log.i(TAG, "result = null");
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
		 
		return bean;
	}
	
	/**
	 * 測試用:根據城市名稱獲取天氣情況
	 * @param city
	 */
	public void getWeatherByCityTest(String city){
		try {
			SoapObject msg = new SoapObject(
					"http://WebXml.com.cn/",
					"getWeatherbyCityName");
			
			city = city.substring(0,city.length()-7);
			Log.i(TAG, "city="+city); 
			msg.addProperty("theCityName", city);
			 
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.bodyOut = msg;
			envelope.dotNet = true;

			AndroidHttpTransport sendRequest = new AndroidHttpTransport(
					"http://www.webxml.com.cn/webservices/weatherwebservice.asmx");
			envelope.setOutputSoapObject(msg);
			sendRequest
					.call("http://WebXml.com.cn/getWeatherbyCityName",
							envelope);

			SoapObject result = (SoapObject) envelope.bodyIn;
			SoapObject detail = (SoapObject) result
					.getProperty("getWeatherbyCityNameResult");
			System.out.println(detail + "");

		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 測試用
	 * @param detail
	 */
	private void parseWeather(SoapObject detail) {
		String weatherToday = null,weatherTomorrow = null,weatherAfterday = null;
		int iconToday[] = null,iconTomorrow[] = null,iconAfterday[] = null;
//		String date = detail.getProperty(6).toString();
//		String weatherToday = "今天:" + date.split(" ")[0];
//		Log.i(TAG, weatherToday);
//		weatherToday = weatherToday + "\n天氣:" + date.split(" ")[1];
		weatherToday = weatherToday + "\n氣溫:" + detail.getProperty(5).toString();
		weatherToday = weatherToday + "\n風力:" + detail.getProperty(7).toString() + "\n";
		Log.i(TAG, weatherToday);
		iconToday[0] = parseIcon(detail.getProperty(8).toString());
		iconToday[1] = parseIcon(detail.getProperty(9).toString());
		String weatherCurrent = detail.getProperty(10).toString();
		
//		date = detail.getProperty(13).toString();
//		String weatherTomorrow = "明天:" + date.split(" ")[0];
//		weatherTomorrow = weatherTomorrow + "\n天氣:" + date.split(" ")[1];
		weatherTomorrow = weatherTomorrow + "\n氣溫:" + detail.getProperty(12).toString();
		weatherTomorrow = weatherTomorrow + "\n風力:" + detail.getProperty(14).toString() + "\n";
		iconTomorrow[0] = parseIcon(detail.getProperty(15).toString());
		iconTomorrow[1] = parseIcon(detail.getProperty(16).toString());
		
//		date = detail.getProperty(18).toString();
//		String weatherAfterday = "後天:" + date.split(" ")[0];
//		weatherAfterday = weatherAfterday + "\n天氣:" + date.split(" ")[1];
		weatherAfterday = weatherAfterday + "\n氣溫:" + detail.getProperty(17).toString();
		weatherAfterday = weatherAfterday + "\n風力:" + detail.getProperty(19).toString() + "\n";
		iconAfterday[0] = parseIcon(detail.getProperty(20).toString());
		iconAfterday[1] = parseIcon(detail.getProperty(21).toString());
		} 


	/**
	 * 解析返回的結果 
	 * @param soapObject
	 **/
	protected WeatherBean parserWeather(SoapObject soapObject) {
		WeatherBean bean = new WeatherBean();
		List> list = new ArrayList>();
		Map map = new HashMap();
		List icons = new ArrayList();
		
		// 城市名
		bean.setCityName(soapObject.getProperty(1).toString());
		// 城市簡介
		bean.setCityDescription(soapObject.getProperty(
				soapObject.getPropertyCount() - 1).toString());
		// 天氣實況+建議
		bean.setLiveWeather(soapObject.getProperty(10).toString() + "\n"
				+ soapObject.getProperty(11).toString());
		// 其他數據
		//日期,
		String date = soapObject.getProperty(6).toString();
		
		Log.i(TAG, "");
		// ---------------------------------------------------
		String weatherToday = "今天:" + date.split(" ")[0];
		weatherToday += "\n天氣:" + date.split(" ")[1];
		weatherToday += "\n氣溫:" + soapObject.getProperty(5).toString();
		weatherToday += "\n風力:" + soapObject.getProperty(7).toString();
		weatherToday += "\n";
 
		icons.add(parseIcon(soapObject.getProperty(8).toString()));
		icons.add(parseIcon(soapObject.getProperty(9).toString()));
		map.put("weatherDay", weatherToday);
		map.put("icons", icons);
		list.add(map);
		
		// -------------------------------------------------
		map = new HashMap();
		date = soapObject.getProperty(13).toString();
		String weatherTomorrow = "明天:" + date.split(" ")[0];
		weatherTomorrow += "\n天氣:" + date.split(" ")[1];
		weatherTomorrow += "\n氣溫:" + soapObject.getProperty(12).toString();
		weatherTomorrow += "\n風力:" + soapObject.getProperty(14).toString();
		weatherTomorrow += "\n";
		icons = new ArrayList();
		icons.add(parseIcon(soapObject.getProperty(15).toString()));
		icons.add(parseIcon(soapObject.getProperty(16).toString()));
		map.put("weatherDay", weatherTomorrow);
		map.put("icons", icons);
		list.add(map);
		
		// --------------------------------------------------------------
		map = new HashMap();
		date = soapObject.getProperty(18).toString();
		String weatherAfterTomorrow = "後天:" + date.split(" ")[0];
		weatherAfterTomorrow += "\n天氣:" + date.split(" ")[1];
		weatherAfterTomorrow += "\n氣溫:" + soapObject.getProperty(17).toString();
		weatherAfterTomorrow += "\n風力:" + soapObject.getProperty(19).toString();
		weatherAfterTomorrow += "\n";
		icons = new ArrayList();
		icons.add(parseIcon(soapObject.getProperty(20).toString()));
		icons.add(parseIcon(soapObject.getProperty(21).toString()));
		map.put("weatherDay", weatherAfterTomorrow);
		map.put("icons", icons);
		list.add(map);
		
		// 把解析後的數據放到一個list中
		bean.setList(list); 
		return bean;
	}

	// 解析圖標字符串
	private int parseIcon(String data) {
		// 0.gif,返回名稱0,
		int resID = 32;
		String result = data.substring(0, data.length() - 4).trim();
		// String []icon=data.split(".");
		// String result=icon[0].trim();
		// Log.e("this is the icon", result.trim());
		if (!result.equals("nothing")) {
			resID = Integer.parseInt(result.trim());
		}
		return resID;
		// return ("a_"+data).split(".")[0];
	}
}

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

/**
 * 這個是使用另一種方式獲取信息,主要是書寫代碼的方式不同
 * @author Song Shi Chao
 *
 */
public class WebServiceUtil {
	// 命名空間
	private static final String serviceNameSpace = "http://WebXml.com.cn/";
	// 請求URL
	private static final String serviceURL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
	// 調用方法(獲得支持的城市)
	private static final String getSupportCity = "getSupportCity";
	// 調用城市的方法(需要帶參數)
	private static final String getWeatherbyCityName = "getWeatherbyCityName";
	// 調用省或者直轄市的方法(獲得支持的省份或直轄市)
	private static final String getSupportProvince = "getSupportProvince";

	/**
	 * @return城市列表 
	 */
	public static List getCityList() {
		// 實例化SoapObject對象
		SoapObject request = new SoapObject(serviceNameSpace, getSupportCity);
		// 獲得序列化的Envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.bodyOut = request;
		(new MarshalBase64()).register(envelope);
		// Android傳輸對象
		AndroidHttpTransport transport = new AndroidHttpTransport(serviceURL);
		transport.debug = true;
		// 調用
		try {
			transport.call(serviceNameSpace + getWeatherbyCityName, envelope);
			if (envelope.getResponse() != null) {
				return parse(envelope.bodyIn.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static List getProviceList() {
		// 實例化SoapObject對象
		SoapObject request = new SoapObject(serviceNameSpace,
				getSupportProvince);
		// 獲得序列化的Envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.bodyOut = request;
		(new MarshalBase64()).register(envelope);
		// Android傳輸對象
		AndroidHttpTransport transport = new AndroidHttpTransport(serviceURL);
		transport.debug = true;
		// 調用
		try {
			transport.call(serviceNameSpace + getWeatherbyCityName, envelope);
			
			if (envelope.getResponse() != null) {
				return null;
			}
		} catch (IOException e) { 
			e.printStackTrace();
		} catch (XmlPullParserException e) { 
			e.printStackTrace();
		}
		return null;
	}
 
	/**
	 * @param cityName
	 * @return
	 */
	public static String getWeather(String cityName) {
		return "";
	}

	/**
	 * 解析XML
	 */
	private static List parse(String str) {
		String temp;
		List list = new ArrayList();
		if (str != null && str.length() > 0) {
			int start = str.indexOf("string");
			int end = str.lastIndexOf(";");
			temp = str.substring(start, end - 3);
			String[] test = temp.split(";");
			for (int i = 0; i < test.length; i++) {
				if (i == 0) {
					temp = test[i].substring(7);
				} else {
					temp = test[i].substring(8);
				}
				int index = temp.indexOf(",");
				list.add(temp.substring(0, index));
			}
		}
		return list;
	}

	/**
	 * 獲取天氣
	 * @param soapObject
	 **/
	private void parseWeather(SoapObject soapObject) {
		// String date=soapObject.getProperty(6);
	}
}


/**
 * 封裝天氣情況的JAVA BEAN
 * 
 * @author Song Shi Chao
 *
 */
public class WeatherBean {
	// 城市名
	public String cityName;
	// 城市簡介
	public String cityDescription;
	// 天氣實況+建議
	public String liveWeather;
	
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
	public String getCityDescription() {
		return cityDescription;
	}
	public void setCityDescription(String cityDescription) {
		this.cityDescription = cityDescription;
	}
	public String getLiveWeather() {
		return liveWeather;
	}
	public void setLiveWeather(String liveWeather) {
		this.liveWeather = liveWeather;
	}
	
	public void setList(List> list) { 
		Map map = new HashMap();
		for(int i=0; i

對應界面類

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

public class WeatherInfoActivity extends TabActivity implements
		OnTabChangeListener {
	public static final String TAG = "WeatherInfoActivity";
	WebServiceHelper wsh;
	WeatherBean bean = new WeatherBean();
	TabHost mTabHost;
	String city;

	TextView txt1, txt2, txt3;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.weatherinfo);

		Intent i = this.getIntent();
		if (i != null) {
			Bundle bd = i.getExtras();
			if (bd != null) {
				if (bd.containsKey("city")) {
					city = bd.getString("city");
				}
			}
		}

		mTabHost = getTabHost();
		// 設置容器的背景色
		mTabHost.setBackgroundColor(Color.argb(150, 22, 70, 150));

		mTabHost.addTab(mTabHost
				.newTabSpec("one")
				.setIndicator("天氣", getResources().getDrawable(R.drawable.icon))
				.setContent(R.id.lin1));
		mTabHost.addTab(mTabHost
				.newTabSpec("two")
				.setIndicator("天氣情況",
						getResources().getDrawable(R.drawable.icon))
				.setContent(R.id.textview2));
		mTabHost.addTab(mTabHost
				.newTabSpec("three")
				.setIndicator("城市信息",
						getResources().getDrawable(R.drawable.icon))
				.setContent(R.id.textview3));

		mTabHost.setCurrentTab(0);

		mTabHost.setOnTabChangedListener(this);

		Button btn1 = (Button) this.findViewById(R.id.button1);
		btn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new Thread() {
					public void run() {
						try {
							SoapObject msg = new SoapObject(
									"http://WebXml.com.cn/",
									"getWeatherbyCityName");
							msg.addProperty("theCityName", city);

							SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
									SoapEnvelope.VER11);
							envelope.bodyOut = msg;
							envelope.dotNet = true;

							AndroidHttpTransport sendRequest = new AndroidHttpTransport(
									"http://www.webxml.com.cn/webservices/weatherwebservice.asmx");
							envelope.setOutputSoapObject(msg);
							sendRequest
									.call("http://WebXml.com.cn/getWeatherbyCityName",
											envelope);

							SoapObject result = (SoapObject) envelope.bodyIn;
							SoapObject detail = (SoapObject) result
									.getProperty("getWeatherbyCityNameResult");
							System.out.println(detail + "");

						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}.start();

			}

		});
	}

	public void init() {
		txt1 = (TextView) this.findViewById(R.id.textview1);
		txt2 = (TextView) this.findViewById(R.id.textview2);
		txt3 = (TextView) this.findViewById(R.id.textview3);
	}

	@Override
	public void onTabChanged(String tabId) {
		WebServiceHelper wsh = new WebServiceHelper();

		// 如果是天氣選項卡,就獲取天氣
		if (tabId.equals("one")) {

			// SimpleAdapter adapter = new SimpleAdapter(this, weather_list_map,
			// R.layout.listview_item,
			// new String[]{"weatherDay","icons"},
			// new int[]{R.id.info_weather,R.id.image_weather});
			// mListView_weather.setAdapter(adapter);
			
		}

		// 如果是天氣情況選項卡,就獲取天氣情況
		if (tabId.equals("two")) {
			wsh.getWeatherByCityTest(city);

		}

		// 如果是城市信息選項卡,就獲取城市信息
		if (tabId.equals("three")) {
			bean = wsh.getWeatherByCity(city);
			

			String liveWeather = bean.getLiveWeather(); // 天氣
			String cityDes = bean.getCityDescription();
			String cityInfo = bean.getCityName(); // 城市信息

			Log.i(TAG, "liveWeather = " + liveWeather);
			Log.i(TAG, "cityDes = " + cityDes);
			Log.i(TAG, "cityInfo = " + cityInfo);
			
		}

	}

}

對應xml布局:

 
 
 
 
	<frameLayout 
	android:id="@android:id/tabcontent" 
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent"> 
	
	
	
	 
	
	
	 
	
	 
	
	</frameLayout> 
 
 


import java.util.ArrayList;
import java.util.List;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ProvinceActivity extends Activity {
	public static final String TAG = "ProvinceActivity";
	WebServiceHelper wsh = new WebServiceHelper();
	public ProvinceAdapter provinceAdapter;
	public List provinces = new ArrayList();
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.province);
        
        ListView province = (ListView) this.findViewById(R.id.proviceList);
        
        provinces = wsh.getProvince();
        provinceAdapter = new ProvinceAdapter();
        Log.i(TAG, ""+provinces);
        province.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView parent, View view,
					int position, long id) { 
				Object obj = view.getTag();
				Log.i(TAG, ""+view.getTag());
				if (obj != null) {
					String id1 = obj.toString();
					Log.i(TAG, ""+ obj.toString());
					Intent intent = new Intent(ProvinceActivity.this, CityActivity.class);
					Bundle b = new Bundle();
					b.putString("province", id1);
					intent.putExtras(b);
					startActivity(intent);
				}
				
			}
        	
        });
        province.setAdapter(provinceAdapter);
    }
	
	class ProvinceAdapter extends BaseAdapter {

		@Override
		public int getCount() { 
			return provinces.size();
		}

		@Override
		public Object getItem(int position) { 
			return provinces.get(position);
		}

		@Override
		public long getItemId(int position) { 
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			//下面倆種方法都可以
			// LayoutInflaterinflater=getLayoutInflater();
			//LayoutInflaterinflater=(LayoutInflater)mContext.getSystemServic(LAYOUT_INFLATER_SERVICE);

			LayoutInflater mInflater = getLayoutInflater(); 
			convertView =  mInflater.inflate(R.layout.province_item, null);
			TextView tv = (TextView) convertView.findViewById(R.id.proviceText);
			tv.setText(provinces.get(position));
			convertView.setTag(tv.getText());
		 
			return convertView;
		}
		
	}
}

對應xml:




	
	


import java.util.ArrayList;
import java.util.List;

import com.parabola.main.ProvinceActivity.ProvinceAdapter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class CityActivity extends Activity { 
	public static final String TAG = "CityActivity";
	String city = null;
	WebServiceHelper wsh = new WebServiceHelper();
	List citys = new ArrayList();
	CityAdapter cityAdapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.city);
        
        ListView cityList = (ListView) this.findViewById(R.id.cityList);
        
        Intent i = this.getIntent();
        if(i != null){
        	Bundle bd = i.getExtras();
        	if(bd != null){
        		if(bd.containsKey("province")){
        			city = bd.getString("province");
        		}
        	}
        }
        
        citys = wsh.getCitys(city);
        cityAdapter = new CityAdapter();
         
        cityList.setOnItemClickListener(new OnItemClickListener(){ 
			@Override
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				Object obj = view.getTag(); 
				if (obj != null) {
					String id1 = obj.toString();
					Log.i(TAG, ""+ obj.toString());
					Intent intent = new Intent(CityActivity.this, WeatherInfoActivity.class);
					Bundle b = new Bundle();
					b.putString("city", id1);
					intent.putExtras(b);
					startActivity(intent); 
				}
			}
		});
        
        cityList.setAdapter(cityAdapter);
         
    }
    
    class CityAdapter extends BaseAdapter {

		@Override
		public int getCount() { 
			return citys.size();
		}

		@Override
		public Object getItem(int position) { 
			return citys.get(position);
		}

		@Override
		public long getItemId(int position) { 
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) { 
			LayoutInflater mInflater = getLayoutInflater(); 
			convertView =  mInflater.inflate(R.layout.province_item, null);
			TextView tv = (TextView) convertView.findViewById(R.id.proviceText);
			tv.setText(citys.get(position));
			convertView.setTag(tv.getText());
			return convertView;
		}
    	
    }
}

對應XML:



	
	
	
	



5、直接使用WebView視圖組件顯示網頁。基於WebView 進行開發,Google已經提供了一個基於chrome-lite的Web浏覽器,直接就可以進行上網浏覽網頁。




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