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

Android桌面小工具AppWidget開發入門:從建立到與應用互動

編輯:關於 Android 程式設計

AppWidget 就是我們長按桌面後加入的那種小視窗,讓使用者不必開啟 App 就能完成一些輕量操作。本文分兩部分說明:如何建立一個簡單的 AppWidget,以及如何讓它與應用程式雙向互動。

先看最終成果與專案結構,建立整體印象:

一、建立一個簡單的 AppWidget

第一步:撰寫描述檔

在 res 下新增一個名為 xml 的目錄,並在其中建立 appwidget01.xml:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
  xmlns:android="https://schemas.android.com/apk/res/android"
  android:minWidth="294dp"
  android:minHeight="72dp"
  android:updatePeriodMillis="86400000"
  android:initialLayout="@layout/appwidgetlayout" >
</appwidget-provider>

這個檔案描述的是小工具本身的屬性:最小寬高、更新間隔、初始版面配置等。不過光有描述檔還不夠——我們看到的小工具都是有介面元素的,這些元素要另外定義在 layout 底下。

第二步:定義版面配置

在 layout 目錄建立 appwidgetlayout.xml,寫法與一般 Activity 的版面配置完全相同。這裡只放一個文字與一個按鈕做示範:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:id="@+id/txtapp"
        android:text="test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ffffff"></TextView>
    <Button android:id="@+id/btnSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"></Button>
</LinearLayout>

第三步:處理事件

既然有小工具上有按鈕,就需要有人處理它的點擊事件。這些邏輯放在一個繼承 AppWidgetProvider 的類別裡,未來所有小工具上的控制項事件都在這裡處理:

public class AppWidget extends AppWidgetProvider {

    private final String broadCastString = "com.qlf.appWidgetUpdate";

    /** 刪除某個 AppWidget 時呼叫 */
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    }

    /** 最後一個 AppWidget 被刪除時呼叫 */
    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
    }

    /** AppWidget 第一次被建立時呼叫 */
    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
    }

    /** 接收廣播 */
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
    }

    /** 到達更新時間,或使用者在桌面新增小工具時呼叫 */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
    }
}

第四步:在 Manifest 中註冊

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.qlf.widget" android:versionCode="1" android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="AppWidget">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"></action>
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/appwidget01" />
        </receiver>
    </application>
    <uses-sdk android:minSdkVersion="8" />
</manifest>

關鍵點有三個:receiver 的 android:name 就是剛才那個處理事件的類別;intent-filter 中的 action 是系統內建的更新廣播動作;meta-data 則是固定寫法,其中 android:resource 指向剛才建立的描述檔,系統才知道要去哪裡讀取初始化資訊。

二、讓 AppWidget 與應用互動

前面建立的小工具還不具備互動能力,這就要請出 RemoteViews。之所以需要它,是因為 AppWidget 運行在與應用不同的進程中(實際上是托管在 Launcher 進程裡),我們無法像平常那樣直接 findViewById 取得控制項:

RemoteViews remoteViews =
        new RemoteViews(context.getPackageName(), R.layout.appwidgetlayout);

remoteViews.setOnClickPendingIntent(R.id.btnSend, pendingIntent);   // 為按鈕綁定事件

這裡又出現一個陌生角色:PendingIntent。一般程式的點擊事件是在實作 OnClickListener 的類別裡完成的,但 AppWidget 不在我們的進程中,自然訪問不到那些程式碼。PendingIntent 就是為了解決這個問題而生。

如果把 Intent 想成一封信,那麼 PendingIntent 就是一封封好口的信。這封信透過 setOnClickPendingIntent() 「郵寄」到 AppWidget,使用者點擊按鈕時,系統知道該拆開它並執行裡面的內容——這樣就避免了直接從遠程進程執行本地程式碼。

// 建立 Intent,說明這封信要做什麼:發送一個廣播
Intent intent = new Intent();
intent.setAction(broadCastString);

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

剩下的工作,就是在 onUpdate 中把上述邏輯串起來:

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                     int[] appWidgetIds) {
    Intent intent = new Intent();
    intent.setAction(broadCastString);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    RemoteViews remoteViews =
            new RemoteViews(context.getPackageName(), R.layout.appwidgetlayout);

    remoteViews.setOnClickPendingIntent(R.id.btnSend, pendingIntent);
    appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}

至於接收來自其他應用或其他元件的廣播,則由 onReceive 負責。同樣因為進程隔離的限制,更新時一樣得透過遠程物件操作:

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(broadCastString)) {
        // 只能透過遠程物件設定小工具中的控制項狀態
        RemoteViews remoteViews =
                new RemoteViews(context.getPackageName(), R.layout.appwidgetlayout);

        remoteViews.setTextViewText(R.id.btnSend, "hihi");

        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        ComponentName componentName = new ComponentName(context, AppWidget.class);
        appWidgetManager.updateAppWidget(componentName, remoteViews);
    }
    super.onReceive(context, intent);
}

歸納起來就是一句話:AppWidget 上的所有操作,都必須借助遠程物件完成。

按下按鈕之前:

按下之後:

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