編輯:Android 開發實例
需要跟 MySQL、Oracle 這類資料庫打交道時,很多朋友的第一反應是在 Android 端直接載入 JDBC 驅動,然後做增刪改查。這個做法我不建議:一方面手機的運算與電力都遠不如電腦,處理大量資料既慢又耗電;另一方面行動網路流量可是要錢的。比較合理的架構是用 Java、PHP 等後端技術寫好介面或 WebService,把資料庫操作留在伺服器端,Android 只負責呼叫。
本文就以「手機號碼歸屬地查詢」這個公開的 WebService 為例,示範 Android 如何呼叫遠端服務。流程不複雜:發出請求、取得回應、解析後顯示。
把請求訊息存成一個 XML 檔,參數位置先用 $ 佔位,執行時再動態替換。這樣做的好處是請求結構與程式碼分離,之後要改欄位不必動 Java 邏輯。
mobilesoap.xml
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema" xmlns:soap12="https://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<getMobileCodeInfo xmlns="https://WebXml.com.cn/">
<mobileCode>$mobile</mobileCode>
<userID></userID>
</getMobileCodeInfo>
</soap12:Body>
</soap12:Envelope>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="手機號碼" />
<EditText
android:id="@+id/mobileNum"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
<Button
android:id="@+id/btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查詢"
/>
<TextView
android:id="@+id/mobileAddress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
package com.szy.webservice;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xmlpull.v1.XmlPullParser;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText mobileNum;
private TextView mobileAddress;
private static final String TAG = "MainActivity";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mobileNum = (EditText) this.findViewById(R.id.mobileNum);
mobileAddress = (TextView) this.findViewById(R.id.mobileAddress);
Button btnSearch = (Button) this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// 獲取電話號碼
String mobile = mobileNum.getText().toString();
// 讀取xml文件
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml");
try
{
// 顯示電話號碼地理位置,該段代碼不合理,僅供參考
mobileAddress.setText(getMobileAddress(inStream, mobile));
} catch (Exception e)
{
Log.e(TAG, e.toString());
Toast.makeText(MainActivity.this, "查詢失敗", 1).show();
}
}
});
}
/**
* 獲取電話號碼地理位置
*
* @param inStream
* @param mobile
* @return
* @throws Exception
*/
private String getMobileAddress(InputStream inStream, String mobile) throws Exception
{
// 替換xml文件中的電話號碼
String soap = readSoapFile(inStream, mobile);
byte[] data = soap.getBytes();
// 提交Post請求
URL url = new URL("https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5 * 1000);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
if (conn.getResponseCode() == 200)
{
// 解析返回信息
return parseResponseXML(conn.getInputStream());
}
return "Error";
}
private String readSoapFile(InputStream inStream, String mobile) throws Exception
{
// 從流中獲取文件信息
byte[] data = readInputStream(inStream);
String soapxml = new String(data);
// 占位符參數
Map<String, String> params = new HashMap<String, String>();
params.put("mobile", mobile);
// 替換文件中占位符
return replace(soapxml, params);
}
/**
* 讀取流信息
*/
private byte[] readInputStream(InputStream inputStream) throws Exception
{
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1)
{
outSteam.write(buffer, 0, len);
}
outSteam.close();
inputStream.close();
return outSteam.toByteArray();
}
/**
* 替換文件中占位符
*/
private String replace(String xml, Map<String, String> params) throws Exception
{
String result = xml;
if (params != null && !params.isEmpty())
{
for (Map.Entry<String, String> entry : params.entrySet())
{
String name = "\$" + entry.getKey();
Pattern pattern = Pattern.compile(name);
Matcher matcher = pattern.matcher(result);
if (matcher.find())
{
result = matcher.replaceAll(entry.getValue());
}
}
}
return result;
}
/**
* 解析XML文件
*/
private static String parseResponseXML(InputStream inStream) throws Exception
{
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inStream, "UTF-8");
int eventType = parser.getEventType();// 產生第一個事件
while (eventType != XmlPullParser.END_DOCUMENT)
{
// 只要不是文檔結束事件
switch (eventType)
{
case XmlPullParser.START_TAG:
String name = parser.getName();// 獲取解析器當前指向的元素的名稱
if ("getMobileCodeInfoResult".equals(name))
{
return parser.nextText();
}
break;
}
eventType = parser.next();
}
return null;
}
}
需要連網,記得在 AndroidManifest.xml 加上:
<uses-permission android:name="android.permission.INTERNET"/>
整段邏輯拆開來看其實很樸素:readSoapFile() 讀範本並用正則把 $mobile 換成真實號碼,getMobileAddress() 用 HttpURLConnection 以 POST 送出 SOAP 信封,parseResponseXML() 再用 XmlPullParser 把 getMobileCodeInfoResult 節點的文字取出來。
這裡要特別提醒一個實務問題:範例把網路請求直接寫在按鈕的 onClick 裡,在較新的 Android 版本上會因為主執行緒禁止網路操作而直接拋出 NetworkOnMainThreadException。正式專案請把 getMobileAddress() 這段搬到 AsyncTask、Thread 或任何背景執行緒中,再透過 Handler 回寫 UI。
Android 本地化實戰:用資源資料夾做多語系 App
同一支 App,會在不同國家、不同語言環境的裝置上被開啟。要讓各地使用者都覺得順手,App 就必須依語言環境調整文字、數字、日期與檔案格式。這件事在 Android 裡有
Android 登入畫面設計:三次機會錯誤鎖定
登入畫面需要兼顧可用性與安全性。除了帳密輸入,也應限制連續錯誤次數。 版面設計 使用兩個 EditText 分別接收帳號與密碼,密碼欄設定 inputType 為 tex
仿 QQ 空間底部中央加號選單:Android 完整實作解析
網路上搜得到的「仿 QQ 空間底部選單」範例不少,但仔細看會發現很多問題:布局裡塞滿了寫死的魔法數字、不同解析度下位置就歪掉、PopupWindow 的生命週期也沒處理好
打造 3D 翻轉動畫:Rotate3dAnimation 函數剖析
上圖就是最終的翻轉效果。由於 Android 並未提供現成的 3D 翻轉動畫,我們得自己動手實作。先來分析 Animation 與 Transformation 這兩個