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

Android AppWidget 進階範例:動手做一個擲骰子的桌面小工具

編輯:關於 Android 程式設計

繼 AppWidget 基礎篇之後,這次做一個「進階版」的小練習來驗收學習成果——一個點一下就擲骰子的桌面 Widget。

先看成品的樣子:

提醒一下,drawable 資料夾裡要先放進六張骰子點數圖,我是從網路上找的素材。

第一步:建立 appwidget_info.xml

在 res 目錄下新增一個名為 xml 的資料夾(名字可自訂),並在其中建立 appwidget_info.xml,用來向系統宣告這個元件的基本資訊。

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

第二步:配置 Widget 的外觀

app_widget_layout.xml,一個 ImageView 顯示骰子、一個 Button 觸發擲骰:

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

    <ImageView
        android:id="@+id/imageview_widget"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/button_widget"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="搖一搖"
        android:textColor="#6663c6" />
</LinearLayout>

第三步:撰寫 WidgetProvider

package com.summer.mywidget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

public class WidgetProvider extends AppWidgetProvider {

    private static final String MY_UPDATE_ACTION = "com.summer.APP_WIDGET_ACTION";

    /* 隨機取得一張骰子圖的資源 id */
    private static int getRandomPicture() {
        int[] pictureArray = new int[]{R.drawable.dice_1, R.drawable.dice_2, R.drawable.dice_3,
                R.drawable.dice_4, R.drawable.dice_5, R.drawable.dice_6};
        int RandomNumber = (int) ((Math.random() * 100) % 6);
        return pictureArray[RandomNumber];
    }

    /* 接收 action,用分支區分自訂 action 與系統 action */
    @Override
    public void onReceive(Context context, Intent intent) {
        String RESPONSEACTION = intent.getAction();
        Log.i("Summer", "------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + RESPONSEACTION);
        if (MY_UPDATE_ACTION.equals(RESPONSEACTION)) {
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget_layout);
            remoteViews.setImageViewResource(R.id.imageview_widget, getRandomPicture());
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            ComponentName componentName = new ComponentName(context, WidgetProvider.class);
            appWidgetManager.updateAppWidget(componentName, remoteViews);
        } else {
            super.onReceive(context, intent);
        }
    }

    /* 用迴圈處理桌面上放了多個相同 Widget 的情況 */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        for (int i = 0; i < appWidgetIds.length; i++) {
            Intent intent = new Intent();
            intent.setAction(MY_UPDATE_ACTION);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, -1, intent, 0);
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget_layout);
            remoteViews.setOnClickPendingIntent(R.id.button_widget, pendingIntent);
            appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
        System.out.println("my app widget ----------------------------->>>>>>>onDeleted");
    }

    @Override
    public void onEnabled(Context context) {
        System.out.println("my app widget ----------------------------->>>>>>>onEnabled");
        super.onEnabled(context);
    }

    @Override
    public void onDisabled(Context context) {
        System.out.println("my app widget ----------------------------->>>>>>>onDisabled");
        super.onDisabled(context);
    }
}

這裡有兩個重點:getRandomPicture() 負責隨機挑一張骰子圖;onReceive() 則攔下自訂的 broadcast action,判斷是「擲骰」還是系統訊息,前者就更新圖片、後者交給父類處理。

第四步:在 Manifest 中宣告

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

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.summer.mywidget.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="com.summer.mywidget.WidgetProvider">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <intent-filter>
                <action android:name="com.summer.APP_WIDGET_ACTION"></action>
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/appwidget_info">
            </meta-data>
        </receiver>
    </application>
</manifest>

注意這裡有兩個 intent-filter:一個接收系統的 APPWIDGET_UPDATE,另一個接收我們自訂的 action,兩者缺一不可。

第五步:執行與添加

跑起來之後,手動在桌面加入這個 Widget,你就擁有一顆自己的骰子了。

總結

這個小程式的邏輯並不複雜,但要寫順手,得對廣播機制與 PendingIntent 有基本認識。想再進一步的話,可以在每次擲骰時加上翻轉動畫,讓手感更好(RemoteViews 有提供相關方法)。程式碼難免還有不足之處,歡迎大家一起討論。

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