Skip to content
Back to skills

Mobile Widgets

ASecurity

Use when the user asks about home screen widgets, WidgetKit, timelines, Live Activities, Dynamic Island, App Intents widgets, Android App Widgets or Jetpack Glance. Produces widget extensions, refresh strategy and deep links into the app. Not for in-app UI components (use ios or android).

  • 46 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added November 27, 2026
ai-agentsgojavaswiftkotlinreacttestingapi

Works with

  • cursor
  • cli
  • api

Security analysis

A100/100

Pro scans all 7 files and shows the line behind each finding

Scanned November 27, 2026

npx -y skills add j4flmao/agent-skills --skill mobile-widgets --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Mobile Widgets?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Mobile Widgets
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/j4flmao-mobile-widgets/badge)](https://www.skillsdirectory.com/skills/j4flmao-mobile-widgets)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: mobile-widgets
description: >
  Use when the user asks about home screen widgets, WidgetKit, timelines, Live
  Activities, Dynamic Island, App Intents widgets, Android App Widgets or
  Jetpack Glance. Produces widget extensions, refresh strategy and deep links
  into the app. Not for in-app UI components (use ios or android).
version: "1.0.0"
author: "j4flmao"
license: "MIT"
last_verified: "2026-11-17"
compatibility:
  claude-code: true
  cursor: true
  codex: true
  windsurf: true
tags: [mobile, widgets, phase-10]
---

# Mobile Widgets Skill

## Purpose
Build glanceable, performant widget experiences across iOS and Android with proper timeline management, refresh strategies, and platform-specific best practices.

## Agent Protocol

### Trigger
User mentions widgets, iOS WidgetKit, Android App Widgets, Live Activities, complications, watchOS complications, Wear OS tiles, widget timeline, widget families, widget configuration, widget deep linking, widget refresh, or widget testing.

### Input Context
- Platform target (iOS, Android, or both)
- Widget types (static, dynamic, configurable, Live Activity, complication)
- Widget families/sizes needed (small, medium, large, extra large)
- Data sources and update frequency
- Deep linking targets
- Refresh strategy (timeline-based, push, periodic)
- Configuration/ customization needs

### Output Artifact
SKILL.md adherence document plus implemented widget extensions, timeline providers, configuration UI, deep link handling, and refresh logic.

### Response Format
No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.

### Completion Criteria
- [ ] Widget extension created for target platform(s)
- [ ] Timeline provider implemented with proper reload strategy
- [ ] All widget families (small, medium, large) supported with appropriate layouts
- [ ] Widget configuration/intent handling implemented
- [ ] Deep linking from widget taps to app content
- [ ] Refresh strategy optimized for battery life (minimal background fetches)
- [ ] Widget previews/snapshots for gallery
- [ ] Live Activity (iOS) or complication (watchOS/Wear OS) if required
- [ ] Widget testing with different data states (empty, loading, error, populated)
- [ ] Accessibility support (VoiceOver, TalkBack, dynamic type)

### Max Response Length
4096 tokens

## Workflow

1. **iOS WidgetKit Timeline Provider**: Define how your widget provides content over time.

```swift
import WidgetKit
import SwiftUI

struct TaskProvider: TimelineProvider {
  typealias Entry = TaskEntry

  func placeholder(in context: Context) -> TaskEntry {
    TaskEntry(date: Date(), items: TaskItem.previewData)
  }

  func getSnapshot(in context: Context, completion: @escaping (TaskEntry) -> Void) {
    let entry = TaskEntry(date: Date(), items: loadCurrentItems())
    completion(entry)
  }

  func getTimeline(in context: Context, completion: @escaping (Timeline<TaskEntry>) -> Void) {
    let entries: [TaskEntry] = generateEntries()
    let nextUpdate = Calendar.current.date(byAdding: .minute, value: 15, to: Date())!
    let timeline = Timeline(entries: entries, policy: .after(nextUpdate))
    completion(timeline)
  }

  private func generateEntries() -> [TaskEntry] {
    let now = Date()
    let items = loadCurrentItems()
    var entries: [TaskEntry] = []

    for minuteOffset in stride(from: 0, to: 60, by: 15) {
      let entryDate = Calendar.current.date(byAdding: .minute, value: minuteOffset, to: now)!
      entries.append(TaskEntry(date: entryDate, items: items))
    }

    return entries
  }
}
```

2. **Widget View & Entry**: SwiftUI views adapted to widget families.

```swift
struct TaskEntry: TimelineEntry {
  let date: Date
  let items: [TaskItem]
}

struct TaskWidgetEntryView: View {
  var entry: TaskProvider.Entry
  @Environment(\.widgetFamily) var family

  var body: some View {
    switch family {
    case .systemSmall:
      SmallTaskView(items: entry.items)
    case .systemMedium:
      MediumTaskView(items: entry.items)
    case .systemLarge:
      LargeTaskView(items: entry.items)
    default:
      MediumTaskView(items: entry.items)
    }
  }
}

struct SmallTaskView: View {
  let items: [TaskItem]

  var body: some View {
    VStack(alignment: .leading, spacing: 4) {
      Text("To-Do").font(.headline).foregroundColor(.secondary)
      ForEach(items.prefix(3)) { item in
        HStack(spacing: 4) {
          Image(systemName: item.isCompleted ? "checkmark.circle.fill" : "circle")
            .foregroundColor(item.isCompleted ? .green : .gray)
            .font(.caption)
          Text(item.title).font(.caption).lineLimit(1)
        }
      }
      if items.count > 3 {
        Text("+\(items.count - 3) more").font(.caption2).foregroundColor(.secondary)
      }
    }
    .padding()
    .widgetURL(URL(string: "myapp://tasks"))
  }
}
```

3. **Widget Configuration with App Intents**: User-configurable widgets via `AppIntentConfiguration` and `WidgetConfigurationIntent` (iOS 17+; the older SiriKit `.intentdefinition` path is legacy).

```swift
import AppIntents

struct SelectListIntent: WidgetConfigurationIntent {
  static let title: LocalizedStringResource = "Select List"
  static let description = IntentDescription("Choose which to-do list to display.")

  @Parameter(title: "List")
  var list: ListEntity?

  static var parameterSummary: some ParameterSummary {
    Summary("Show items from \(\.$list)")
  }
}

struct ListEntity: AppEntity {
  let id: String
  let name: String

  static var typeDisplayRepresentation: TypeDisplayRepresentation = "List"
  static var defaultQuery = ListQuery()

  var displayRepresentation: DisplayRepresentation {
    DisplayRepresentation(title: "\(name)")
  }
}

struct ListQuery: EntityStringQuery {
  func entities(matching string: String) async throws -> [ListEntity] {
    return await ListStore.shared.lists.filter { $0.name.contains(string) }
  }

  func suggestedEntities() async throws -> [ListEntity] {
    return await ListStore.shared.lists
  }

  func defaultResult() async -> ListEntity? {
    return await ListStore.shared.lists.first
  }
}
```

4. **Live Activities (iOS 16.1+)**: Dynamic, real-time updates on Lock Screen and Dynamic Island.

```swift
import ActivityKit

struct DeliveryActivityAttributes: ActivityAttributes {
  public struct ContentState: Codable, Hashable {
    var driverName: String
    var estimatedMinutes: Int
    var status: DeliveryStatus
    var lastUpdate: Date
  }

  var orderId: String
  var restaurantName: String
}

enum DeliveryStatus: String, Codable, Hashable {
  case preparing
  case pickedUp
  case inTransit
  case delivered
}

func startDeliveryActivity(orderId: String, restaurantName: String) {
  let attributes = DeliveryActivityAttributes(orderId: orderId, restaurantName: restaurantName)
  let state = DeliveryActivityAttributes.ContentState(
    driverName: "",
    estimatedMinutes: 0,
    status: .preparing,
    lastUpdate: Date()
  )

  do {
    let activity = try Activity<DeliveryActivityAttributes>.request(
      attributes: attributes,
      content: ActivityContent(state: state, staleDate: nil),
      pushType: .token
    )
    print("Started Live Activity: \(activity.id)")
  } catch {
    print("Failed to start Live Activity: \(error)")
  }
}

func updateDeliveryActivity(activityId: String, state: DeliveryActivityAttributes.ContentState) {
  Task {
    let activity = Activity<DeliveryActivityAttributes>.activities.first { $0.id == activityId }
    await activity?.update(
      ActivityContent(state: state, staleDate: Date().addingTimeInterval(30 * 60))
    )
  }
}

// Live Activity SwiftUI view
struct DeliveryLiveActivityView: View {
  let context: ActivityViewContext<DeliveryActivityAttributes>

  var body: some View {
    HStack {
      VStack(alignment: .leading) {
        Text(context.attributes.restaurantName).font(.headline)
        Text(context.state.driverName).font(.caption).foregroundColor(.secondary)
      }
      Spacer()
      VStack(alignment: .trailing) {
        Text("\(context.state.estimatedMinutes) min").font(.title2).bold()
        Text(context.state.status.rawValue).font(.caption).foregroundColor(.blue)
      }
    }
    .padding()
    .activitySystemActionForegroundColor(.indigo)
  }
}
```

5. **Android App Widgets**: RemoteViews with configuration activity.

```kotlin
// TaskWidgetProvider.kt
class TaskWidgetProvider : AppWidgetProvider() {
  override fun onUpdate(
    context: Context,
    appWidgetManager: AppWidgetManager,
    appWidgetIds: IntArray
  ) {
    for (appWidgetId in appWidgetIds) {
      updateAppWidget(context, appWidgetManager, appWidgetId)
    }
  }

  override fun onDeleted(context: Context, appWidgetIds: IntArray) {
    for (appWidgetId in appWidgetIds) {
      TaskWidgetConfig.removeWidget(context, appWidgetId)
    }
  }

  override fun onEnabled(context: Context) {
    // Prepare for first widget instance
  }

  override fun onDisabled(context: Context) {
    // Clean up when last widget removed
  }

  companion object {
    internal fun updateAppWidget(
      context: Context,
      appWidgetManager: AppWidgetManager,
      appWidgetId: Int
    ) {
      val listId = TaskWidgetConfig.loadListPref(context, appWidgetId)
      val items = TaskRepository.getItems(listId)

      val views = RemoteViews(context.packageName, R.layout.task_widget)
      views.setTextViewText(R.id.widget_title, getListName(listId))

      val rv = RemoteViews(context.packageName, R.layout.task_widget_item)
      views.removeAllViews(R.id.widget_list_container)

      items.take(5).forEach { item ->
        val itemView = RemoteViews(context.packageName, R.layout.task_widget_item)
        itemView.setTextViewText(R.id.item_text, item.title)
        itemView.setInt(R.id.item_checkbox, "setChecked", if (item.isCompleted) 1 else 0)

        val fillInIntent = Intent(context, MainActivity::class.java).apply {
          action = Intent.ACTION_VIEW
          data = Uri.parse("myapp://task/${item.id}")
        }
        val pendingIntent = PendingIntent.getActivity(
          context, item.id.toInt(), fillInIntent,
          PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        itemView.setOnClickPendingIntent(R.id.item_container, pendingIntent)
        views.addView(R.id.widget_list_container, itemView)
      }

      val configIntent = Intent(context, TaskWidgetConfigureActivity::class.java).apply {
        putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
      }
      val configPendingIntent = PendingIntent.getActivity(
        context, appWidgetId, configIntent,
        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
      )
      views.setOnClickPendingIntent(R.id.widget_settings, configPendingIntent)

      appWidgetManager.updateAppWidget(appWidgetId, views)
    }
  }
}

// Widget layout: res/layout/task_widget.xml
// <LinearLayout
//   xmlns:android="http://schemas.android.com/apk/res/android"
//   android:layout_width="match_parent"
//   android:layout_height="match_parent"
//   android:orientation="vertical"
//   android:padding="@dimen/widget_margin">
//   <LinearLayout android:orientation="horizontal" android:layout_width="match_parent">
//     <TextView android:id="@+id/widget_title" .../>
//     <ImageButton android:id="@+id/widget_settings" .../>
//   </LinearLayout>
//   <LinearLayout android:id="@+id/widget_list_container" android:orientation="vertical" .../>
// </LinearLayout>
```

6. **Widget Refresh Strategies**: Balance freshness with battery life.

```swift
// iOS: TimelineReloadPolicy (WidgetKit) — returned with each Timeline
// .after(date)  request the next timeline at or after a date (system may delay)
// .atEnd        request a new timeline after the last entry
// .never        reload only when the app calls WidgetCenter.reloadTimelines

// iOS Background refresh via push
func handleWidgetPush(token: String, data: [String: Any]) {
  let newEntry = TaskEntry(date: Date(), items: parseItems(from: data))
  WidgetCenter.shared.reloadTimelines(ofKind: "TaskWidget")
}

// Android periodic refresh
class TaskWidgetProvider : AppWidgetProvider() {
  override fun onUpdate(...) {
    // Scheduled via AlarmManager or WorkManager
    val workRequest = PeriodicWorkRequestBuilder<WidgetRefreshWorker>(
      15, TimeUnit.MINUTES
    ).build()
    WorkManager.getInstance(context).enqueueUniquePeriodicWork(
      "widget_refresh",
      ExistingPeriodicWorkPolicy.KEEP,
      workRequest
    )
  }
}
```

7. **Widget Deep Linking**: Navigate to specific app screens on tap.

```swift
// iOS: widgetURL for the entire widget
// widgetUrl(URL(string: "myapp://dashboard"))

// iOS: Link for specific areas within widget
Link(destination: URL(string: "myapp://task/\(item.id)")!) {
  Text(item.title)
}

// Android: PendingIntent with custom URI
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("myapp://task/$itemId"))
val pendingIntent = PendingIntent.getActivity(context, requestCode, intent, flags)
views.setOnClickPendingIntent(R.id.item_container, pendingIntent)
```

8. **Widget Testing**: Preview with different data states.

```swift
// iOS widget previews
struct TaskWidget_Previews: PreviewProvider {
  static var previews: some View {
    Group {
      TaskWidgetEntryView(entry: TaskEntry(date: Date(), items: TaskItem.previewData))
        .previewContext(WidgetPreviewContext(family: .systemSmall))

      TaskWidgetEntryView(entry: TaskEntry(date: Date(), items: TaskItem.previewData))
        .previewContext(WidgetPreviewContext(family: .systemMedium))

      TaskWidgetEntryView(entry: TaskEntry(date: Date(), items: []))
        .previewContext(WidgetPreviewContext(family: .systemSmall))

      TaskWidgetEntryView(entry: TaskEntry(date: Date(), items: TaskItem.previewErrorData))
        .previewContext(WidgetPreviewContext(family: .systemLarge))
    }
  }
}
```

## Rules

1. Never perform network calls in widget views — fetch in the timeline provider (iOS `getTimeline`/`timeline(for:in:)`) or a background worker (Android), then render cached data.
2. Always provide a placeholder view for loading states.
3. Keep the widget extension small: extensions run under a tight memory limit (tens of MB), so downsample images and keep assets minimal.
4. Support only the widget families whose layout fits your content (`supportedFamilies`), and design each one deliberately.
5. Never use infinite timelines — always provide a finite set of entries.
6. Always test widgets with system Dark Mode and Accent Color.
7. Never use custom fonts not bundled in widget extension target.
8. Always provide snapshot data for widget gallery preview.
9. Never hardcode refresh intervals — respect user's battery settings.
10. Always implement tap targets with minimum 44pt touch area.
11. Never use UIWebView/WKWebView inside widgets (not supported).
12. Always provide accessibility labels for VoiceOver/TalkBack.
13. Never store large datasets in UserDefaults for widget access — use shared container.
14. Always handle empty state gracefully (no data view, not blank).
15. Keep widget animations to the system-provided content transitions; widgets do not run custom animation loops.
16. Always implement configurable widgets when user personalization is needed.
17. Never use UIKit/AppKit inside iOS widgets — SwiftUI only.
18. Always test widgets with different Dynamic Type sizes.
19. Respect the iOS reload budget (the system allows a limited number of reloads per day, typically every 15–60 minutes for a frequently viewed widget); use app-triggered `reloadTimelines` after real data changes instead of short timers. Android `updatePeriodMillis` is clamped to a 30-minute minimum.
20. Always remove widget data when all widget instances are deleted.

## References
  - references/android-app-widgets.md — Android App Widgets
  - references/complications.md — Complications (Watch Widgets)
  - references/ios-widgetkit.md — iOS WidgetKit
  - references/mobile-widgets-advanced.md — Mobile Widgets Advanced Topics
  - references/mobile-widgets-fundamentals.md — Mobile Widgets Fundamentals
  - references/widget-refresh.md — Widget Refresh Strategy
## Handoff
- `mobile/mobile-localization` — Widget string localization and RTL support
- `design/visual-design` — widget visual design and brand consistency
- `mobile/react-native` — bridging app data to native widget extensions from React Native

Files in this skill

  • SKILL.md16.1 KB
  • references/android-app-widgets.md14.9 KB
  • references/complications.md15.4 KB
  • references/ios-widgetkit.md12.3 KB
  • references/mobile-widgets-advanced.md6.3 KB
  • references/mobile-widgets-fundamentals.md6 KB
  • references/widget-refresh.md12.3 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.