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

Android 桌面 Widget 時鐘完整實作教學

編輯:關於 Android 程式設計

桌面小工具(App Widget)和普通 Activity 差別很大:它的畫面由 RemoteViews 描述,必須透過 AppWidgetProvider 接收更新廣播,而且更新頻率受系統限制。以下用一個每秒刷新時間的時鐘,把整個流程走一遍。

步驟一:在 AndroidManifest.xml 註冊

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.widget"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

        <service android:name=".TimerService"></service>

    </application>
</manifest>

步驟二:建立 res/xml/timewidget_info.xml

<?xml version="1.0" encoding="UTF-8"?>
<appwidget-provider xmlns:android="https://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/time_appwidget"
    android:minHeight="40dp"
    android:minWidth="40dp"
    android:updatePeriodMillis="0" />

這裡把 updatePeriodMillis 設為 0,代表不依賴系統的定時更新機制,改由自己的 Service 控制節奏——因為系統對這個值有下限限制(最短約 30 分鐘),拿來做時鐘完全不可行。

步驟三:Widget 的版面 res/layout/time_appwidget.xml

<?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"
    android:background="@drawable/rectangle" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="current time" />

</LinearLayout>

步驟四(選用):美化用的 res/drawable/rectangle.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- 設置弧度 -->
    <corners android:radius="9dp" />

    <gradient
        android:angle="270"
        android:startColor="#B3F0FF"
        android:endColor="#5EADF4" />

    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />

    <stroke
        android:width="6dp"
        android:dashWidth="10dp"
        android:dashGap="1dp"
        android:color="#0000FF" />

</shape>

步驟五:Provider 的處理邏輯

package com.example.widget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;

public class TimeWidgetProvider extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    // 當某個 Widget 被刪除時呼叫
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    }

    // 第一次往桌面添加同類型 Widget 時呼叫,之後再加不會觸發
    public void onEnabled(Context context) {
        context.startService(new Intent(context, TimerService.class));
    }

    // 從桌面刪除最後一個同類型 Widget 時呼叫
    public void onDisabled(Context context) {
        context.stopService(new Intent(context, TimerService.class));
    }
}

把 Service 的啟動與停止綁在 onEnabled() / onDisabled() 上,是這裡最關鍵的設計:桌面上還有這個時鐘,Service 就活著;最後一個被移除,Service 自動收工,不會留下無用的背景程序。

步驟六:用 Service 每分鐘...不,每秒更新

package com.example.widget;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;

public class TimerService extends Service {

    private Timer timer;

    @Override
    public void onCreate() {
        super.onCreate();
        timer = new Timer();
        timer.schedule(new MyTimerTask(), 0, 1000);
    }

    private final class MyTimerTask extends TimerTask {

        @SuppressLint("SimpleDateFormat")
        @Override
        public void run() {
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
            String time = sdf.format(new Date());

            // 取得 Widget 管理器
            AppWidgetManager widgetManager =
                    AppWidgetManager.getInstance(getApplicationContext());

            // 對應目前 Widget 的遠程視圖
            RemoteViews remoteView =
                    new RemoteViews(getPackageName(), R.layout.time_appwidget);
            remoteView.setTextViewText(R.id.textView, time);

            // 點擊 Widget 時的行為:
            // remoteView.setOnClickPendingIntent(viewId, pendingIntent)

            ComponentName componentName = new ComponentName(
                    getApplicationContext(), TimeWidgetProvider.class);
            widgetManager.updateAppWidget(componentName, remoteView);
        }
    }

    @Override
    public void onDestroy() {
        timer.cancel();
        timer = null;
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

要點回顧

  • Widget 的 UI 是 RemoteViews,只能使用支援的版面與控制項,不能直接抓 View 來操作。
  • 更新一律透過 AppWidgetManager.updateAppWidget() 送出,並以 ComponentName 指定目標 Provider。
  • 計時任務記得在 onDestroy() 中 cancel(),否則會造成資源洩漏。
  • 若需要互動效果,改用 PendingIntent 綁到 setOnClickPendingIntent()。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved