在 AppWidget 中,事件大致可分為三類:開啟 Activity、啟動 Service、發送按鈕 Action。由於 AppWidget 的互動主要透過 RemoteViews 與 PendingIntent 完成,因此事件處理需要依賴廣播或 Intent 機制。
先建立一個 Intent 指向目標 Activity,若有需要傳遞資料,可使用 putExtra。接著用 PendingIntent.getActivity 建立 PendingIntent,並透過 RemoteViews 的 setOnClickPendingIntent 綁定按鈕事件。最後呼叫 AppWidgetManager 的 updateAppWidget 更新介面。
若要啟動 Service,可建立具有指定 action 的 Intent,再用 PendingIntent.getService 建立 PendingIntent,同樣透過 setOnClickPendingIntent 綁定到 RemoteViews 的按鈕上。
若在 onUpdate 中更新,可直接使用 AppWidgetManager 更新所有 AppWidget ID;若在 Service 等非 onUpdate 環境中更新,則需要先取得 RemoteViews、ComponentName 與 AppWidgetManager,再呼叫 updateAppWidget。