編輯:關於 Android 程式設計
要把 Widget 放到桌面有兩種途徑:長按桌面空白處,或者從 Widget 預覽 App 中挑選。原生系統在 4.0 以下使用長按方式,4.0 以上則是打開 WIDGETS 分頁。
首先在 manifest 中註冊一個繼承 AppWidgetProvider 的 receiver,並用 meta-data 指向描述檔:
<receiver android:name="com.stone.ui.TimerWidgetProvider">
<intent-filter>
<!-- 自定義 action -->
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/timer_widget_provider" />
</receiver>
其中 android:resource 指向的 timer_widget_provider.xml 用來描述這個 Widget 的各種屬性:
<?xml version="1.0" encoding="utf-8"?> <!-- 計算 size 的公式:(70*n) - 30,n 為佔幾格,這裡是 3x1 minResizeWidth / minResizeHeight : 可被調整的最小寬高,若大於 minWidth/minHeight 則忽略 label : 選擇部件時看到的標籤 icon : 選擇部件時看到的圖示 updatePeriodMillis : 更新時間間隔 previewImage : 選擇部件時展示的圖像,3.0 以上使用 initialLayout : 布局檔 resizeMode : 調整 size 的模式 configure : 若需要在啟動前先開啟一個 Activity 做設定,在此填入完整類名 widgetCategory : widget 可添加的位置,keyguard(鎖屏)| home_screen(桌面) autoAdvanceViewId : 與集合部件搭配,指定自動推進的 item 容器 集合部件:3.0 後才有,包含 ListView、GridView、StackView、AdapterViewFlipper -->
這裡有個重要限制必須先知道:Widget 的布局只能使用 FrameLayout、LinearLayout、RelativeLayout 三種根容器,控件也只能用 RemoteViews 支援清單裡的那些,而且不支援它們的子類。原因是 Widget 的檢視實際上是跨進程渲染的,並不是在 App 自己的進程裡建立。
<?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="horizontal"
android:background="@drawable/widget_background" >
<TextView
android:id="@+id/counter"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="00:00"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearance" />
<ImageView
android:id="@+id/start_stop"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:scaleType="center"
android:src="@android:drawable/ic_media_play" />
</LinearLayout>
package com.stone.ui;
import java.util.Arrays;
import com.stone.R;
import com.stone.service.TimerWidgetService;
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.text.format.DateUtils;
import android.widget.RemoteViews;
/**
* AppWidgetProvider 必須能接收 android.appwidget.action.APPWIDGET_UPDATE 廣播
*/
public class TimerWidgetProvider extends AppWidgetProvider {
/** 更新部件時呼叫,第一次添加部件時也會呼叫 */
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
// 用 PendingIntent 包住 Service,onReceive 依收到的廣播決定如何更新
Intent intent = new Intent(context, TimerWidgetService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.timer_widget);
rv.setOnClickPendingIntent(R.id.start_stop, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, rv);
}
/** 部件從 host 中刪除 */
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
}
/** 第一次建立時呼叫,之後再建立不會呼叫 */
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
}
/** 最後一個部件實例被刪除時呼叫,用於清除 onEnabled 中執行的操作 */
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
// 接收在其他元件、Activity 或 Service 中送出的廣播
if (intent.getAction().equals("com.stone.action.start")) {
long time = intent.getLongExtra("time", 0);
updateWidget(context, time);
}
}
private void updateWidget(Context context, long time) {
// RemoteViews 專門用來操作跨進程的 View
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.timer_widget);
rv.setTextViewText(R.id.counter, DateUtils.formatElapsedTime(time / 1000));
AppWidgetManager am = AppWidgetManager.getInstance(context);
int[] appWidgetIds = am.getAppWidgetIds(new ComponentName(context, TimerWidgetProvider.class));
am.updateAppWidget(appWidgetIds, rv); // 更新所有實例
}
}
這裡有幾個容易搞混的生命週期重點:onUpdate() 每次更新都會呼叫,第一次添加時也會;onEnabled() 只在「第一個」實例建立時呼叫一次;onDisabled() 則在「最後一個」實例被移除時呼叫。因此成對的資源配置(例如註冊與反註冊)應該放在 onEnabled / onDisabled 裡,而不是 onUpdate。
package com.stone.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class TimerWidgetService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 在這裡進行計時等實際工作,然後送出廣播通知 Widget 更新
sendBroadcast(new Intent("com.stone.action.start")
.putExtra("time", System.currentTimeMillis()));
return Service.START_STICKY;
}
}
這個小隊列把整個 Widget 資料流的閉環說清楚了:使用者點擊 → PendingIntent 啟動 Service → Service 處理後發出自定義廣播 → Provider 的 onReceive 攔截 → 透過 RemoteViews 更新文字 → AppWidgetManager 推送到桌面。任何需要「定時更新 Widget 內容」的需求,都可以沿著這條鏈路去擴充。
Android 探索 Bottom Sheets 的使用
自 Android Support Library 23.2 版本推出後,我們可以看到一些新特性,例如 AppCompat DayNight 主題、BottomSheet
跟我學Android之八:ActionBar與菜單
本章內容 第1節 菜單概述第2節 選項菜單和子菜單第3節 上下文菜單第4節 使用XML定義菜單第5節 ActionBar的作用 本章目標 了解各版本菜單的特征;掌握創建選
Android 實戰:手把手畫出圓形水波紋 LoadingView
本文一步步示範如何畫一個圓形水波紋的 loading 檢視。這類效果應用場景很多,例如顯示記憶體佔用百分比、下載進度等。 先備知識 貝塞爾曲線:用來畫出平滑的水波曲線
自製安全鍵盤:用 KeyboardView 打造字母、數字、符號三合一輸入盤
一直知道 Android 有 KeyboardView 這個元件可以做自訂鍵盤,只是過去沒派上用場。某天看到某銀行 App 的密碼輸入鍵盤,配色與排版都很講究,於是決定動