Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Widget 開發實戰:手把手做出一個桌面便籤(含完整源碼)

編輯:Android 開發實例

Android 平台對 widget 的支援相當完善,桌面便籤這類小工具寫起來其實不難。本文用「漸進式」的方式,分階段把一個名為 MyNote 的桌面便籤做出來,每一階段都留下可運行的成果。

一、最終成品長什麼樣子

先在桌面長按加入我們的 MyNote 小工具:

圖中的「我的便籤」就是接下來要開發的程式。

點一下便籤,會進入新增紀錄的介面:

輸入內容後,從下方四個圖示中挑一個當作便籤的圖標。例如點第一個,桌面就會多一張便籤:

再點桌面上的便籤,可以重新編輯內容、更換圖標。桌面上能同時放多張便籤,各自獨立儲存、各自獨立修改。

二、開發路線

我們不一次寫完,而是切成幾個階段,每階段都往前推進一步:

  • 第一階段:搭出一個能跑的 widget 骨架,可以成功在桌面建立 widget。
  • 第二階段:改寫 widget 設定 Activity,讓它能建立便籤。
  • 第三階段:改寫 widget 的點擊回應,讓它能修改便籤。

三、第一階段:把骨架搭起來

一般來說,一個 widget 由四個部分組成:AppWidgetProvider 的實作、widget 外觀的版面配置檔、新增 widget 時的設定 Activity(可選),以及 widget 參數設定檔。

a. AppWidgetProvider 的實作

新建 Android 專案 MyNote,讓 MyNote 繼承 AppWidgetProvider,並覆寫 onUpdate 與 onDeleted。前者在 widget 建立或更新時呼叫,後者在 widget 被刪除時呼叫。這個階段先不做任何功能,只記錄日誌以便觀察。

package com.silenceburn;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.util.Log;

public class MyNote extends AppWidgetProvider {

    final String mPerfName = "com.silenceburn.MyColorNoteConf";

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
        final int N = appWidgetIds.length;
        for (int i = 0; i < N; i++) {
            int appWidgetId = appWidgetIds[i];
            Log.i("myLog", "this is [" + appWidgetId + "] onUpdate!");
        }
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        final int N = appWidgetIds.length;
        for (int i = 0; i < N; i++) {
            int appWidgetId = appWidgetIds[i];
            Log.i("myLog", "this is [" + appWidgetId + "] onDelete!");
        }
    }
}

b. widget 外觀版面配置

這個範例的外觀很簡單,一個 ImageView 就夠了,檔名 my_note_widget.xml 放在 layout 目錄下:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/my_widget_img"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/sketchy_paper_008"
    android:clickable="true" />

這裡用了一張外部圖片 sketchy_paper_008.png,取自網路,感謝原作者,可到 dryicons.com 的 sketchy-paper-icons 打包下載(下載後的檔名可能與程式碼中的命名不同,記得自行調整)。

c. 新增 widget 時的設定 Activity(可選)

Android 提供了一個機制:在 widget 參數設定檔中指定一個 Activity,使用者新增 widget 時系統就會自動啟動它,通常用來讓使用者設定顏色、大小等屬性。我們則把它拿來當成「建立便籤」的入口。

這裡先只建立一個名為 MyNoteConf 的 Activity。由於它由系統在新增 widget 時呼叫,我們可以用 getIntent() 取得傳入的 widgetId 並檢查是否合法。最後必須回傳 RESULT_OK 的 Intent 並結束 Activity,系統才會認為設定成功並把 widget 放上桌面;若回傳 RESULT_CANCELED,系統會視為設定失敗並中止建立流程。

package com.silenceburn;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class MyNoteConf extends Activity {

    int mAppWidgetId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("myLog", " on WidgetConf ... ");

        setResult(RESULT_CANCELED);

        // 從 Intent 中取出 widget id
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        // 沒有帶到有效的 widget id 就直接結束
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }

        // 回傳 RESULT_OK,widget 才會被放上桌面
        Intent resultValue = new Intent();
        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        setResult(RESULT_OK, resultValue);
        finish();
    }
}

d. widget 參數設定檔

在 res 下新增 xml 目錄,建立同樣名為 my_note_widget.xml 的參數檔,把版面配置與設定 Activity 串起來:

<appwidget-provider xmlns:android="https://schemas.android.com/apk/res/android"
    android:minWidth="72dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="86400000"
    android:initialLayout="@layout/my_note_widget"
    android:configure="com.silenceburn.MyNoteConf">
</appwidget-provider>

minWidth 與 minHeight 決定 widget 尺寸;若要佔一格(俗稱 1x1),72dp 是 Android 官方推薦的實踐值。initialLayout 關聯版面配置檔,configure 關聯設定 Activity。至於 updatePeriodMillis 是自動刷新週期,基於省電考量一般會設得很大;若真的需要週期性工作,改用 AlarmManager 會合適得多。

四、把骨架跑起來

要讓 widget 出現在桌面上,還得改 AndroidManifest.xml:宣告一個 receiver 過濾 android.appwidget.action.APPWIDGET_UPDATE,並用 metadata 關聯到我們的 provider 設定檔;再宣告一個 Activity 過濾 android.appwidget.action.APPWIDGET_CONFIGURE;最後換上應用程式圖示,它會出現在系統的「選擇 widget」清單裡。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.silenceburn"
    android:versionCode="1"
    android:versionName="1.0">

    <application android:icon="@drawable/sketchy_paper_008"
        android:label="@string/app_name">

        <receiver android:name=".MyNote">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/my_note_widget" />
        </receiver>

        <activity android:name=".MyNoteConf">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
            </intent-filter>
        </activity>

    </application>
</manifest>

到這裡骨架就完成了。執行後在桌面長按,選擇清單裡的 MyNote,會看到設定介面一閃而過(因為我們在 onCreate 裡就 finish 了),接著便籤圖示出現在桌面上。拖動它、丟進垃圾桶,都能在日誌裡看到對應的輸出。

上半場小結:這一半做出一個沒有任何業務功能的 widget 骨架,但它已經是一個可以運行的完整結構。下半場要做的,就是慢慢長出血肉。

五、第二階段:用設定 Activity 實現新增便籤

既然系統保證新增 widget 時一定會呼叫設定 Activity,那就把「新增便籤」交給它。同樣分三小步:版面配置、按鈕點擊、資料儲存。

a. 版面配置

看回第一節的效果圖,這個版面主要由提示文字 TextView、輸入框 EditText、四個 ImageButton 組成。新增 my_note_conf.xml:用垂直 LinearLayout 把三部分組織起來,透過 weight 讓 EditText 自動撐滿剩餘空間;四個按鈕再用一個水平 LinearLayout 排好,並調整 gravity、margin 讓它好看一些。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <TextView android:layout_height="wrap_content"
        android:text="@string/note_title"
        android:layout_width="wrap_content"
        android:padding="10dp"></TextView>

    <LinearLayout android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:layout_weight="1">
        <EditText android:id="@+id/EditText02"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="left"
            android:hint="@string/edithint"></EditText>
    </LinearLayout>

    <LinearLayout android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:layout_weight="2"
        android:gravity="center">
        <ImageButton android:id="@+id/ImageButton01"
            android:layout_width="72dp" android:layout_height="72dp"
            android:src="@drawable/sketchy_paper_003"
            android:layout_margin="3dp"></ImageButton>
        <ImageButton android:id="@+id/ImageButton02"
            android:layout_width="72dp" android:layout_height="72dp"
            android:src="@drawable/sketchy_paper_004"
            android:layout_margin="3dp"></ImageButton>
        <ImageButton android:id="@+id/ImageButton03"
            android:layout_width="72dp" android:layout_height="72dp"
            android:src="@drawable/sketchy_paper_007"
            android:layout_margin="3dp"></ImageButton>
        <ImageButton android:id="@+id/ImageButton04"
            android:layout_width="72dp" android:layout_height="72dp"
            android:src="@drawable/sketchy_paper_011"
            android:layout_margin="3dp"></ImageButton>
    </LinearLayout>
</LinearLayout>

別忘了在設定 Activity 加上 setContentView(R.layout.my_note_conf);。字串定義放在 strings.xml,若要國際化可用 values-zh 一類的資源修飾符,這裡不展開。

b. 按鈕點擊

四個按鈕行為幾乎一樣,因此只寫一個 OnClickListener 綁到全部按鈕上。在 onClick 裡先判斷被點的是哪顆按鈕,據此決定要用哪張圖;接著建立 RemoteViews 關聯到 widget,設定 ImageView 的資源,再取得 AppWidgetManager 對指定 widget 下發更新,設定才會生效。最後把原本在 onCreate 中的 RESULT_OK 與 finish 搬到 onClick 裡。

package com.silenceburn;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RemoteViews;

public class MyNoteConf extends Activity {

    int mAppWidgetId;
    ImageButton mImBtn1, mImBtn2, mImBtn3, mImBtn4;
    final String mPerfName = "com.silenceburn.MyNoteConf";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_note_conf);

        setResult(RESULT_CANCELED);

        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }

        mImBtn1 = (ImageButton) findViewById(R.id.ImageButton01);
        mImBtn2 = (ImageButton) findViewById(R.id.ImageButton02);
        mImBtn3 = (ImageButton) findViewById(R.id.ImageButton03);
        mImBtn4 = (ImageButton) findViewById(R.id.ImageButton04);

        mImBtn1.setOnClickListener(mBtnClick);
        mImBtn2.setOnClickListener(mBtnClick);
        mImBtn3.setOnClickListener(mBtnClick);
        mImBtn4.setOnClickListener(mBtnClick);
    }

    OnClickListener mBtnClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // 1. 把便籤內容存起來
            EditText mTextView = (EditText) MyNoteConf.this.findViewById(R.id.EditText02);
            SharedPreferences.Editor prefs =
                    MyNoteConf.this.getSharedPreferences(mPerfName, 0).edit();
            prefs.putString("DAT" + mAppWidgetId, mTextView.getText().toString());
            prefs.commit();

            // 2. 決定要用哪張圖
            int srcId = R.drawable.sketchy_paper_008;
            switch (v.getId()) {
                case R.id.ImageButton01: srcId = R.drawable.sketchy_paper_003; break;
                case R.id.ImageButton02: srcId = R.drawable.sketchy_paper_004; break;
                case R.id.ImageButton03: srcId = R.drawable.sketchy_paper_007; break;
                case R.id.ImageButton04: srcId = R.drawable.sketchy_paper_011; break;
            }

            // 3. 更新 widget 外觀
            RemoteViews views = new RemoteViews(MyNoteConf.this.getPackageName(),
                    R.layout.my_note_widget);
            views.setImageViewResource(R.id.my_widget_img, srcId);
            AppWidgetManager appWidgetManager =
                    AppWidgetManager.getInstance(MyNoteConf.this);
            appWidgetManager.updateAppWidget(mAppWidgetId, views);

            // 4. 回報成功並關閉
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
            setResult(RESULT_OK, resultValue);
            finish();
        }
    };
}

這時候執行一下,加入 MyNote widget 後會停在設定介面等你輸入內容並挑選圖標,選完桌面上就多一張便籤了。

c. 資料儲存

內容還沒落地,必須持久化。Android 裡最簡單的做法是 SharedPreferences,更好的做法是 SQLite,再更好是用 ContentProvider 包一層。本文側重 widget 開發,就用最省事的 SharedPreferences。

用法很直觀:先用一個特定前綴取得自己的 Preferences 空間(前綴通常用類別的完整名稱,避免與其他程式衝突),再把這個空間想成一個雜湊表,用 putString(key, content) 一組組放進去,最後 commit()。

這裡的關鍵是 key 用 "DAT" + mAppWidgetId。由於 mAppWidgetId 是每個 widget 的唯一標識,這樣就能把不同便籤的內容分開儲存,互不干擾。

六、第三階段:加上點擊回應,實現修改便籤

a. 增加 widget 點擊回應

新增一個 Activity 名為 MyNoteEdit,widget 被點擊時就開啟它。因為是修改內容,版面直接複用 my_note_conf.xml 即可。這個階段先只驗證「點得到」:

package com.silenceburn;

import android.app.Activity;
import android.os.Bundle;

public class MyNoteEdit extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_note_conf);
    }
}

接著回到 MyNoteConf,替 widget 掛上一個 PendingIntent,點擊時就會觸發指定的 Intent:

Intent intent = new Intent(MyNoteConf.this, MyNoteEdit.class);
intent.setAction(mPerfName + mAppWidgetId);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
PendingIntent pendingIntent = PendingIntent.getActivity(MyNoteConf.this, 0, intent, 0);
views.setOnClickPendingIntent(R.id.my_widget_img, pendingIntent);

千萬別漏掉 intent.setAction(mPerfName + mAppWidgetId)。否則每個 widget 拿到的會是同一個 PendingIntent 實例,只有 extraData 不同;依建立方式與 flag 設定,extraData 可能被覆寫或只在第一次寫入,結果我們永遠只能取到第一個(或最後一個)新增 widget 的 Id,這顯然不是我們要的。

最後別忘了在 AndroidManifest.xml 補上 <activity android:name=".MyNoteEdit" />。執行後把 widget 放上桌面點一下,修改視窗就會跳出來,長得和設定介面一模一樣。

b. 修改便籤的 Activity

最後一步:把內容讀出來填回輸入框。既然第五階段存資料時用的 key 是 "DAT" + mAppWidgetId,那麼在 MyNoteEdit 的 onCreate 裡從 Intent 取出 widgetId,就能用同一組 key 把內容讀回來。

Intent t = getIntent();
mAppWidgetId = t.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);

mPref = getSharedPreferences(mPerfName, 0);
String noteContent = mPref.getString("DAT" + mAppWidgetId, "");

mTextView = (TextView) findViewById(R.id.EditText02);
mTextView.setText(noteContent);

四個 ImageButton 的點擊邏輯幾乎可以照抄 MyNoteConf,只要多一步「先寫回 SharedPreferences」再更新 widget 外觀,然後關掉自己:

OnClickListener mBtnClick = new OnClickListener() {
    @Override
    public void onClick(View v) {
        SharedPreferences.Editor prefsEdit = mPref.edit();
        prefsEdit.putString("DAT" + mAppWidgetId, mTextView.getText().toString());
        prefsEdit.commit();

        int srcId = R.drawable.sketchy_paper_008;
        switch (v.getId()) {
            case R.id.ImageButton01: srcId = R.drawable.sketchy_paper_003; break;
            case R.id.ImageButton02: srcId = R.drawable.sketchy_paper_004; break;
            case R.id.ImageButton03: srcId = R.drawable.sketchy_paper_007; break;
            case R.id.ImageButton04: srcId = R.drawable.sketchy_paper_011; break;
        }

        RemoteViews views = new RemoteViews(MyNoteEdit.this.getPackageName(),
                R.layout.my_note_widget);
        views.setImageViewResource(R.id.my_widget_img, srcId);
        AppWidgetManager.getInstance(MyNoteEdit.this)
                .updateAppWidget(mAppWidgetId, views);

        MyNoteEdit.this.finish();
    }
};

至此全部功能到位:桌面加入 MyNote、輸入內容、挑選圖標;之後點桌面便籤可以再度修改內容與更換圖標;多張便籤並存且各自獨立。

七、總結

回頭看整個程式,會發現絕大多數程式碼集中在設定介面與修改介面,反而 AppWidgetProvider 裡只有記錄日誌、清理 Preferences 這類簡單工作。這固然與本範例的需求有關,但也符合 Android 對「降低自動更新頻率」的建議(更新間隔建議至少一小時以上)。所以實務上應該只在真正需要時,才用 RemoteViews 搭配 updateAppWidget() 主動要求 widget 更新。

身為範例程式,它在美化、效能與程式碼規範上都還有明顯改進空間;但作為理解 widget 開發骨架的起點,這些刻意保留的簡陋反而讓流程更清楚。掌握「骨架先行、再逐步長出血肉」的節奏,之後要換成 SQLite、加上多行文字或自訂檢視,都只是在同一副骨架上繼續加料而已。

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