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

音樂播放器實戰(八):打造桌面小工具 App Widget(上)

編輯:關於 Android 程式設計

第 8 節 桌面小工具

桌面小工具是可以放置於主畫面、讓使用者快速操控應用的小助手。以我們的音樂小工具為例,使用者不必開啟 App,就能直接在桌面上完成暫停、播放、切歌等操作。在 Android 系統裡,它也被稱為 App Widget。

實作一個 App Widget,大致需要四個步驟:

1. 建立一個繼承自 AppWidgetProvider 的類別,例如 AnddleMusicAppWidget;
2. 在 res/layout 目錄下為小工具定義一個佈局檔,例如 anddle_music_app_widget.xml;
3. 在 res/xml 目錄下建立說明檔,例如 anddle_music_app_widget_info.xml;
4. 在 AndroidManifest.xml 中宣告這個 App Widget。

8.1 建立小工具框架

對使用 Android Studio 的開發者而言,上述四步可以透過視覺化向導輕鬆完成。在專案上按右鍵,選擇 New → Widget → App Widget,就會產生開發用的範本。

在彈出的建立向導中填入各項參數:

為小工具命名為 AnddleMusicAppWidget;允許放置於主畫面;不允許顯示區域動態縮放;佔用 3 格寬、1 格高。這些設定最後會反映在 res/xml/anddle_music_app_widget_info.xml 中。

執行專案後,就能把 App Widget 加入桌面了。

8.2 界面設計

接著修改佈局檔 anddle_music_app_widget.xml,把畫面設計成如下效果:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:padding="@dimen/widget_margin">
    <ImageView
        android:id="@+id/image_thumb"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:scaleType="fitCenter"
        android:src="@mipmap/default_cover" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:id="@+id/music_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:singleLine="true"
            android:text="@string/no_song" />
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <Button android:id="@+id/play_btn2" ... />
            <Button android:id="@+id/pre_btn2" ... />
            <Button android:id="@+id/next_btn2" ... />
        </RelativeLayout>
    </LinearLayout>
</LinearLayout>

再修改 anddle_music_app_widget_info.xml 的 android:previewImage 屬性,讓它指向預覽效果圖。

8.3 重建 AnddleMusicAppWidget

AnddleMusicAppWidget 類別負責小工具的邏輯響應。

8.3.1 AppWidget 原理

繼承 AppWidgetProvider 後,開發者可以選擇性地實作 onUpdate()、onAppWidgetOptionsChanged()、onDeleted()、onEnabled()、onDisabled() 與 onRestored() 等回呼方法:

public class AnddleMusicAppWidget extends AppWidgetProvider {
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { }
    @Override
    public void onEnabled(Context context) { }
    @Override
    public void onDisabled(Context context) { }
    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager mgr, int id, Bundle newOptions) { }
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) { }
    @Override
    public void onRestored(Context context, int[] oldWidgetIds, int[] newWidgetIds) { }
}

桌面上可以同時放置多個相同的小工具,系統會為每一個分配一個 id,以便日後更新或操作時能正確區分。各回呼的觸發時機如下:

當桌面原本沒有小工具、首次加入時,依序觸發 onEnabled() → onUpdate();此後每新增一個,只觸發 onUpdate();系統需要更新顯示時,同樣觸發 onUpdate()。刪除其中一個會觸發 onDeleted();若刪除的是最後一個,則觸發 onDeleted() → onDisabled()。設備開機時,會觸發 onEnabled() → onUpdate()。

在小工具架構中,每一個顯示出來的小工具界面稱為 RemoteViews,透過下列方式建立:

// 第二個參數就是小工具的佈局檔
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.anddle_music_app_widget);

接著用 RemoteViews 提供的設定方法,控制每個元素的呈現,例如某個 TextView 顯示什麼文字、某個 ImageView 顯示什麼圖片、某個 Button 被點擊後觸發什麼操作,最後透過 AppWidgetManager.updateAppWidget() 把界面更新上去:

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
// appWidgetId 由 onUpdate() 傳入,代表某個特定小工具
appWidgetManager.updateAppWidget(appWidgetId, views);

因此,AnddleMusicAppWidget 需要對外提供一個更新介面,讓其他組件能在需要時刷新小工具畫面。

8.3.2 App Widget 的界面元素

下面逐一說明 RemoteViews 對界面元素的操作方式。

設置 TextView 文字

views.setTextViewText(R.id.music_name, musicName);

設置 ImageView 圖片

views.setImageViewBitmap(R.id.image_thumb, thumb);

設置其他屬性

並非所有屬性都有專用的設定函式,RemoteViews 提供了更通用的做法。例如設定 Button 的背景:

// 等同於呼叫 button.setBackgroundResource(R.mipmap.ic_pause)
views.setInt(R.id.play_btn2, "setBackgroundResource", R.mipmap.ic_pause);

Button 的點擊響應

RemoteViews 無法直接設定點擊後的行為,必須透過 PendingIntent 來實現:

Intent preIntent = new Intent(MusicService.ACTION_PLAY_MUSIC_PRE);
preIntent.setComponent(serviceName);
PendingIntent prePendingIntent = PendingIntent.getService(context, 0, preIntent, 0);
views.setOnClickPendingIntent(R.id.pre_btn2, prePendingIntent);

因此真正的播放邏輯,要放在 MusicService 這個回應組件中處理。

8.3.3 AnddleMusicAppWidget 實作

類別繼承 AppWidgetProvider,實作 onUpdate(),並對外提供靜態方法 performUpdates() 作為其他組件刷新界面的統一入口。核心結構如下:

public class AnddleMusicAppWidget extends AppWidgetProvider {
    private static int[] sAppWidgetIds;
    @Override
    public void onUpdate(Context context, AppWidgetManager mgr, int[] appWidgetIds) {
        sAppWidgetIds = appWidgetIds;
        performUpdates(context, context.getString(R.string.no_song), false, null);
    }
    // 對外提供的更新介面:傳入歌名、是否播放中、封面
    public static void performUpdates(Context context, String musicName, boolean isPlaying, Bitmap thumb) {
        if (sAppWidgetIds == null || sAppWidgetIds.length == 0) return;
        AppWidgetManager mgr = AppWidgetManager.getInstance(context);
        for (int appWidgetId : sAppWidgetIds) {
            updateAppWidget(context, mgr, appWidgetId, musicName, isPlaying, thumb);
        }
    }
    private static void updateAppWidget(Context context, AppWidgetManager mgr, int appWidgetId,
                                        String musicName, boolean isPlaying, Bitmap thumb) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.anddle_music_app_widget);
        // 設定歌名
        views.setTextViewText(R.id.music_name, musicName);
        final ComponentName serviceName = new ComponentName(context, MusicService.class);
        // 下一首
        Intent nextIntent = new Intent(MusicService.ACTION_PLAY_MUSIC_NEXT);
        nextIntent.setComponent(serviceName);
        views.setOnClickPendingIntent(R.id.next_btn2,
            PendingIntent.getService(context, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT));
        // 上一首
        Intent preIntent = new Intent(MusicService.ACTION_PLAY_MUSIC_PRE);
        preIntent.setComponent(serviceName);
        views.setOnClickPendingIntent(R.id.pre_btn2,
            PendingIntent.getService(context, 0, preIntent, 0));
        // 播放/暫停
        Intent toggleIntent = new Intent(MusicService.ACTION_PLAY_MUSIC_TOGGLE);
        toggleIntent.setComponent(serviceName);
        views.setOnClickPendingIntent(R.id.play_btn2,
            PendingIntent.getService(context, 0, toggleIntent, 0));
        // 依播放狀態切換圖示
        views.setInt(R.id.play_btn2, "setBackgroundResource",
            isPlaying ? R.mipmap.ic_pause : R.mipmap.ic_play);
        // 封面:有封面用封面,沒有則用預設圖
        if (thumb != null) {
            views.setImageViewBitmap(R.id.image_thumb, thumb);
        } else {
            views.setImageViewResource(R.id.image_thumb, R.mipmap.default_cover);
        }
        mgr.updateAppWidget(appWidgetId, views);
    }
}

透過以上邏輯,三顆按鈕分別以隱性 Intent 喚醒 MusicService 對應的動作,並依當前播放狀態切換播放圖示與封面。下篇我們再串接 Service 端的回應邏輯。

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