Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

即時股票 App 實作:行情抓取、定時刷新與大額委託提醒

編輯:關於 Android 程式設計

做為 Android 練手專案,股票行情 App 是個相當合適的題目——它同時涵蓋網路請求、定時任務、資料解析、清單呈現、本地儲存與通知推播,幾乎把日常開發會用到的元件都串了一遍。

本文以名為 Mystock 的範例專案說明實作過程,開發工具為 Android Studio(可自 https://developer.android.com/sdk/index.html 下載)。

Android Studio 開啟專案的畫面如下:

1. 版面結構(activity_main.xml)

上方一列放三個 TextView,分別顯示上證指數、深圳成指、創業板指;中間一列是 EditText 與 Button,用來新增股票代碼;下方則用 TableLayout 顯示已加入的股票清單。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="0.33"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/stock_sh_name"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/stock_sh_index"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="12sp"
                android:id="@+id/stock_sh_change"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="0.33"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/stock_sz_name"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/stock_sz_index"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="12sp"
                android:id="@+id/stock_sz_change"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="0.33"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/stock_chuang_name"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/stock_chuang_index"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="12sp"
                android:id="@+id/stock_chuang_change"/>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:maxLength="6"
            android:id="@+id/editText_stockId"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_add_label"
            android:onClick="addStock" />
    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/stock_table"></TableLayout>
    </ScrollView>
</LinearLayout>

App 執行畫面:

2. 抓取行情資料

這裡使用新浪提供的行情接口,它接受以逗號分隔的股票代碼清單,回傳一段以特殊分隔符組成的文字。

public void querySinaStocks(String list) {
    // 建立請求佇列
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "https://hq.sinajs.cn/list=" + list;
    // 例如 https://hq.sinajs.cn/list=sh600000,sh600536

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                updateStockListView(sinaResponseToStocks(response));
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) { }
        });

    queue.add(stringRequest);
}

這裡以 Volley 處理 HTTP 請求,需在 build.gradle 中加入相依:

compile 'com.mcxiaoke.volley:library:1.0.19'

選擇 Volley 的理由是它天生適合「高頻率、小資料量」的請求場景,這正好是即時行情的特性。

3. 定時刷新

用 Timer 每兩秒觸發一次請求:

Timer timer = new Timer("RefreshStocks");
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        refreshStocks();
    }
}, 0, 2000);

private void refreshStocks() {
    String ids = "";
    for (String id : StockIds_) {
        ids += id;
        ids += ",";
    }
    querySinaStocks(ids);
}

4. 退出時保存股票清單

用 SharedPreferences 把清單存成本地設定,下次開啟就能延續:

private void saveStocksToPreferences() {
    String ids = "";
    for (String id : StockIds_) {
        ids += id;
        ids += ",";
    }
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString(StockIdsKey_, ids);
    editor.commit();
}

@Override
public void onDestroy() {
    super.onDestroy();
    saveStocksToPreferences();
}

5. 刪除選取的股票

先在 menu_main.xml 中加入選單項:

<menu xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_delete"
        android:title="@string/action_delete"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>

再於 Activity 中回應點擊並移除對應的資料列:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_delete) {
        if (SelectedStockItems_.isEmpty()) return true;

        for (String selectedId : SelectedStockItems_) {
            StockIds_.remove(selectedId);
            TableLayout table = (TableLayout) findViewById(R.id.stock_table);
            int count = table.getChildCount();
            for (int i = 1; i < count; i++) {
                TableRow row = (TableRow) table.getChildAt(i);
                LinearLayout nameId = (LinearLayout) row.getChildAt(0);
                TextView idText = (TextView) nameId.getChildAt(1);
                if (idText != null && idText.getText().toString() == selectedId) {
                    table.removeView(row);
                    break;
                }
            }
        }
        SelectedStockItems_.clear();
    }
    return super.onOptionsItemSelected(item);
}

畫面如下:

6. 大額委託提醒

當買賣五檔中任一檔的掛單量超過門檻時,發出通知:

{
    String text = "";
    String sBuy = getResources().getString(R.string.stock_buy);
    String sSell = getResources().getString(R.string.stock_sell);

    if (Double.parseDouble(stock.b1_) >= StockLargeTrade_) text += sBuy + "1:" + stock.b1_ + ",";
    if (Double.parseDouble(stock.b2_) >= StockLargeTrade_) text += sBuy + "2:" + stock.b2_ + ",";
    if (Double.parseDouble(stock.b3_) >= StockLargeTrade_) text += sBuy + "3:" + stock.b3_ + ",";
    if (Double.parseDouble(stock.b4_) >= StockLargeTrade_) text += sBuy + "4:" + stock.b4_ + ",";
    if (Double.parseDouble(stock.b5_) >= StockLargeTrade_) text += sBuy + "5:" + stock.b5_ + ",";
    if (Double.parseDouble(stock.s1_) >= StockLargeTrade_) text += sSell + "1:" + stock.s1_ + ",";
    if (Double.parseDouble(stock.s2_) >= StockLargeTrade_) text += sSell + "2:" + stock.s2_ + ",";
    if (Double.parseDouble(stock.s3_) >= StockLargeTrade_) text += sSell + "3:" + stock.s3_ + ",";
    if (Double.parseDouble(stock.s4_) >= StockLargeTrade_) text += sSell + "4:" + stock.s4_ + ",";
    if (Double.parseDouble(stock.s5_) >= StockLargeTrade_) text += sSell + "5:" + stock.s5_ + ",";

    if (text.length() > 0) {
        sendNotifation(Integer.parseInt(sid), stock.name_, text);
    }
}

public void sendNotifation(int id, String title, String text) {
    NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);
    nBuilder.setSmallIcon(R.drawable.ic_launcher);
    nBuilder.setContentTitle(title);
    nBuilder.setContentText(text);
    nBuilder.setVibrate(new long[]{100, 100, 100});
    nBuilder.setLights(Color.RED, 1000, 1000);

    NotificationManager notifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notifyMgr.notify(id, nBuilder.build());
}

通知畫面:

回顧這個專案的架構要點

這個範例把「網路 → 解析 → 更新 UI → 本地保存 → 通知」整條鏈路串了起來,是很典型的資料驅動型 App 結構。若重新實作,有幾處值得調整:

用 TableLayout 動態增刪資料列的做法在項目數量多時效能不佳,改用 RecyclerView 搭配 DiffUtil 會順暢許多。用字串串接組 ID 清單雖然簡單,但用 StringBuilder 或 TextUtils.join() 更清晰。SharedPreferences.commit() 是同步寫入,會阻塞主執行緒,應改用 apply()。而通知部分,Android 8.0 起必須建立 NotificationChannel,Android 13 之後還需執行期請求 POST_NOTIFICATIONS 權限,否則通知根本不會顯示。

另外,新浪行情接口屬於非官方服務,隨時可能變更或停止,且此類資料僅供學習用途,不應作為實際投資決策依據。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved