Communitygithub.com

curiositech/android-背景任務專家

專精於 Android 背景任務,涵蓋 WorkManager、前景服務、低電耗模式與電池最佳化。

android-背景任務專家 是什麼?

這項技能專為 Android 開發者設計,提供處理背景任務的完整知識體系,包含 WorkManager、前景服務 (Foreground Service)、低電耗模式 (Doze Mode)、App 待機以及電池最佳化等核心領域。它不僅涵蓋各種技術的選擇決策樹(例如何時使用 WorkManager、前景服務或協程),還提供可立即使用的程式碼範例,如帶有重試與進度回報的 CoroutineWorker 實作、含限制條件的工作鍊排程。此外,該技能列出常見的反模式(例如使用 AlarmManager 處理可延遲工作、未宣告前景服務類型),以及一份完整的品質檢查清單,協助開發者避開陷阱,寫出高效率、友善電池續航的 Android 背景任務。適用平台包含 Android 開發環境(Android Studio、IntelliJ IDEA),以及任何可執行 Kotlin 程式碼的 AI 編碼助理。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/curiositech/windags-skills/tree/HEAD/skills/android-background-task-specialist

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Android 背景任務專家

專精於 Android 背景執行,涵蓋 WorkManager、前景服務、低電耗模式處理與電池高效處理。

觸發條件

啟用於: "WorkManager"、"Android 背景任務"、"前景服務"、"低電耗模式"、"電池最佳化"、"定期工作"、"背景同步"、"JobScheduler"、"Android 背景處理"

不適用於: iOS 背景任務 → swiftui-data-flow-expert | React Native 背景任務 → mobile-offline-sync-architect | UI 架構 → jetpack-compose-navigation-expert

快速入門

  1. 選擇正確的 API — 可延遲工作使用 WorkManager,使用者可見的持續性任務使用前景服務,短暫非同步工作使用協程
  2. 定義工作者 — 繼承 CoroutineWorker 並使用暫停函數來實現簡潔的非同步程式碼
  3. 設定限制條件 — 網路類型、電量、儲存空間需求
  4. 處理低電耗模式與 App 待機 — 使用 WorkManager(而非 AlarmManager)進行相容於低電耗模式的排程
  5. 透過 adb 進行測試 — 強制進入低電耗模式,並驗證工作是否在滿足限制條件時執行

核心能力

領域技術
可延遲工作WorkManager 2.10, OneTimeWorkRequest, PeriodicWorkRequest
前景執行前景服務類型 (dataSync, location, mediaPlayback, shortService)
限制條件NetworkType, BatteryNotLow, StorageNotLow, DeviceIdle
工作鏈WorkContinuation, 平行鏈, 唯一工作策略
測試TestWorkerBuilder, TestListenableWorkerBuilder, WorkManagerTestInitHelper

架構模式

WorkManager 決策樹

任務是否由使用者發起且需要完成?
  ├─ 是 → 任務時間短(< 10 分鐘)?
  │   ├─ 是 → 前景服務(shortService 類型)
  │   └─ 否 → 前景服務(dataSync, location 等)
  │
  └─ 否 → 任務是否可延遲?
      ├─ 是 → WorkManager
      │   ├─ 一次性? → OneTimeWorkRequest
      │   └─ 定期性? → PeriodicWorkRequest(最小間隔 15 分鐘)
      │
      └─ 否 → 是否在應用程式可見時執行?
          ├─ 是 → CoroutineScope(viewModelScope 或 lifecycleScope)
          └─ 否 → 你大概還是需要 WorkManager

帶重試與進度回報的 CoroutineWorker

@HiltWorker
class SyncWorker @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted params: WorkerParameters,
    private val syncRepository: SyncRepository,
    private val notificationHelper: NotificationHelper,
) : CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        // 回報進度供 UI 觀察
        setProgress(workDataOf("progress" to 0))

        return try {
            val pendingItems = syncRepository.getPendingChanges()

            pendingItems.forEachIndexed { index, item ->
                syncRepository.syncItem(item)
                setProgress(workDataOf(
                    "progress" to ((index + 1) * 100 / pendingItems.size)
                ))
            }

            Result.success(workDataOf("synced" to pendingItems.size))
        } catch (e: IOException) {
            if (runAttemptCount < 3) {
                Result.retry()  // 預設採用指數退避
            } else {
                Result.failure(workDataOf("error" to e.message))
            }
        }
    }

    override suspend fun getForegroundInfo(): ForegroundInfo {
        return ForegroundInfo(
            NOTIFICATION_ID,
            notificationHelper.createSyncNotification()
        )
    }
}

附帶限制條件與工作鏈的排程

// 每 1 小時排程一次定期同步(最小 15 分鐘)
val syncRequest = PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.HOURS)
    .setConstraints(
        Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .setRequiresBatteryNotLow(true)
            .build()
    )
    .setBackoffCriteria(
        BackoffPolicy.EXPONENTIAL,
        WorkRequest.MIN_BACKOFF_MILLIS,
        TimeUnit.MILLISECONDS
    )
    .addTag("sync")
    .build()

WorkManager.getInstance(context).enqueueUniquePeriodicWork(
    "periodic-sync",
    ExistingPeriodicWorkPolicy.KEEP,  // 若已排程則不重新啟動
    syncRequest
)

// 鏈結:下載 → 處理 → 上傳(依序)
WorkManager.getInstance(context)
    .beginWith(downloadWork)
    .then(processWork)
    .then(uploadWork)
    .enqueue()

反模式

  1. 使用 AlarmManager 處理可延遲工作 — AlarmManager 的鬧鐘不相容於低電耗模式且耗電。請改用尊重低電耗模式、App 待機與省電模式的 WorkManager。
  2. 沒有前景通知的背景服務 — Android 12+ 會終止背景服務。請使用前景服務並正確宣告類型,或使用 WorkManager。
  3. 定期工作間隔低於 15 分鐘 — WorkManager 強制要求最小間隔為 15 分鐘。若需要更頻繁的工作,請使用前景服務或具備生命週期感知能力的協程。
  4. 未宣告前景服務類型 — Android 14+ 要求在 Manifest 中明確宣告 foregroundServiceType。省略會導致 SecurityException。
  5. 忽略工作觀察 — 啟動工作卻未向使用者顯示進度。請透過 getWorkInfoByIdLiveData() 或 getWorkInfoByIdFlow() 觀察 WorkInfo 以更新 UI。

品質檢查清單

[ ] 使用 WorkManager 處理可延遲背景任務(非 AlarmManager)
[ ] 在 AndroidManifest 中以正確類型宣告前景服務
[ ] 已設定限制條件(網路、電量、儲存空間)
[ ] 針對暫時性失敗設定含退避策略的重試機制
[ ] 為定期/一次性工作設定唯一工作策略
[ ] 工作進度可從 UI 觀察
[ ] 已透過 adb 測試低電耗模式:`adb shell dumpsys deviceidle force-idle`
[ ] 已測試電池最佳化:`adb shell am set-inactive <package> true`
[ ] 已使用 TestWorkerBuilder 測試工作者
[ ] 已為前景服務通知建立通知頻道
[ ] 工作鏈能妥善處理部分失敗情況
[ ] 背景工作尊重使用者的省電模式偏好

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

curiositech/windags-skills

Expert in 2000s-era music visualization (Milkdrop, AVS, Geiss) and modern WebGL implementations. Specializes in Butterchurn integration, Web Audio API AnalyserNode FFT data, GLSL shaders for audio-reactive visuals, and psychedelic generative art. Activate on "Milkdrop", "music visualization", "WebGL visualizer", "Butterchurn", "audio reactive", "FFT visualization", "spectrum analyzer". NOT for simple bar charts/waveforms (use basic canvas), video editing, or non-audio visuals.

curiositech/windags-skills

Expert legal research agent for finding and scraping expungement data state by state. Knows authoritative sources, URL patterns, Firecrawl configuration, and 2026 legal landscape.

curiositech/windags-skills

Expert in 3D computer vision labeling tools, workflows, and AI-assisted annotation for LiDAR, point clouds, and sensor fusion. Covers SAM4D/Point-SAM, human-in-the-loop architectures, and vertical-specific training strategies. Activate on '3D labeling', 'point cloud annotation', 'LiDAR labeling', 'SAM 3D', 'SAM4D', 'sensor fusion annotation', '3D bounding box', 'semantic segmentation point cloud'. NOT for 2D image labeling (use clip-aware-embeddings), general ML training (use ml-engineer), video annotation without 3D (use computer-vision-pipeline), or VLM prompt engineering (use prompt-engineer).

curiositech/windags-skills

Implement WCAG 2.2 AA/AAA compliance with automated testing, keyboard navigation, screen reader support, and focus management. Activate on: accessibility audit, WCAG compliance, keyboard navigation, screen reader, aria attributes, axe-core, focus trap. NOT for: design-level accessibility review (use design-accessibility-auditor), color contrast only (use css-in-js-architect).

curiositech/windags-skills

Time-blind friendly planning, executive function support, and daily structure for ADHD brains. Specializes in realistic time estimation, dopamine-aware task design, and building systems that actually work for neurodivergent minds.

curiositech/windags-skills

Designs digital experiences for ADHD brains using neuroscience research and UX principles. Expert in reducing cognitive load, time blindness solutions, dopamine-driven engagement, and compassionate design patterns. Activate on 'ADHD design', 'cognitive load', 'accessibility', 'neurodivergent UX', 'time blindness', 'dopamine-driven', 'executive function'. NOT for general accessibility (WCAG only), neurotypical UX design, or simple UI styling without ADHD context.

curiositech/windags-skills

>- Apply crisis decision-making research to agent routing, uncertainty triage, and coordination failure analysis in time-pressured systems. Use when diagnosing handoff failures, analytical paralysis, or expert judgment under incomplete information. NOT for routine coding, simple CRUD design, or static single-agent tasks with complete information.

curiositech/windags-skills

Extend and modify the admin dashboard, developer portal, and operations console. Use when adding new admin tabs, metrics, monitoring features, or internal tools. Activates for dashboard development, analytics, user management, and internal tooling.

curiositech/windags-skills

Conversation patterns and interaction protocols for multi-agent systems. Covers request/response, pub/sub, blackboard, delegation chains, debate, critique, consensus, fan-out/fan-in, supervisor-worker, and peer negotiation. Deep analysis of AutoGen conversation patterns, CrewAI delegation, LangGraph state passing, and FIPA-ACL performatives. Teaches how to design what agents say to each other and in what order. Activate on: "agent conversation", "agent protocol", "multi-agent debate", "agent delegation", "supervisor worker pattern", "agent voting", "consensus protocol", "fan-out fan-in", "agent negotiation", "blackboard pattern", "agent dialogue", "conversation topology", "agent handoff". NOT for: wire format or serialization (use agent-interchange-formats), orchestration infrastructure (use agentic-infrastructure-2026), single agent behavior (use agentic-patterns).

curiositech/windags-skills

Meta-agent for creating new custom agents, skills, and MCP integrations. Expert in agent design, MCP development, skill architecture, and rapid prototyping. Activate on 'create agent', 'new skill', 'MCP server', 'custom tool', 'agent design'. NOT for using existing agents (invoke them directly), general coding (use language-specific skills), or infrastructure setup (use deployment-engineer).

curiositech/windags-skills

AI-powered calendar management and agent-based scheduling coordination. Covers calendar APIs (Google Calendar, CalDAV/iCal), AI scheduling assistants (Reclaim, Clockwise, Motion, Cal.com), building custom calendar agents with MCP, multi-calendar merging, timezone management, focus block protection, meeting fatigue detection, and agent-to-agent meeting negotiation protocols. Activate on: "calendar agent", "AI scheduling", "calendar coordination", "meeting scheduling", "calendar API", "focus time protection", "calendar optimization", "Google Calendar MCP", "Reclaim", "Clockwise", "Motion", "Cal.com", "smart scheduling", "calendar-aware agent", "timezone scheduling", "agent negotiation meetings". NOT for: manual calendar UI component design (use form-validation-architect), project management scheduling or Gantt charts (use project-management-guru-adhd), general time-tracking or pomodoro apps (use adhd-daily-planner for time-awareness), building the agent itself from scratch (use agent-creator).

curiositech/windags-skills

Build and adopt production AI agent infrastructure in 2026. Covers framework selection (LangGraph, CrewAI, AutoGen, MCP), orchestration patterns, evaluation, observability, memory systems, and tool use. Also covers the SOCIAL dimension: how to sell agent infrastructure internally, change management, measuring ROI, building trust in autonomous systems, and scaling adoption across teams. Activate on: "agent infrastructure", "agent framework comparison", "which agent framework", "sell AI tools internally", "agent adoption", "agent observability", "agent evaluation", "MCP architecture", "agentic mesh", "enterprise AI agents", "AI change management", "agent ROI". NOT for: building specific agents (use ai-engineer), designing agent behavior patterns (use agentic-patterns), prompt tuning (use prompt-engineer).

curiositech/windags-skills

Fundamental patterns for effective agentic behavior. Teaches decomposition, tool orchestration, error recovery, context management, quality self-assessment, and knowing when to stop. Model-agnostic principles that make any agent more effective regardless of domain. Activate on: "how should I structure this agent", "agentic workflow", "agent patterns", "multi-step task", "tool orchestration", "/agentic-patterns", "decompose this", "agent best practices", "chain of actions", "when should the agent stop", "agent loop design". NOT for: creating agent infrastructure (use agent-creator), building DAGs (use windags-architect), specific tool implementation.

curiositech/windags-skills

Automated discovery and matching of agent skills for dynamic task routing and capability assessment

curiositech/windags-skills

Cryptographic security for agentic systems — zero-trust agent networking, signed message envelopes (JWS/JWE), capability-based security (ocaps), Merkle tree audit trails, WASM sandboxing, and formal verification. Covers CLI dev tool security, mTLS between agents, permission boundaries (least privilege for AI agents), and supply chain security for skills/plugins. Activate on: "agent security", "zero trust agents", "secure agent communication", "capability-based security", "ocap", "signed messages between agents", "agent audit trail", "sandbox agent execution", "agent permissions", "mTLS agents", "cryptographic verification", "agent supply chain", "OWASP agentic", "prove agent did X", "tamper-proof agent logs". NOT for: application-level SAST scanning (use security-auditor), network firewall rules (use infrastructure), SOC2/HIPAA compliance (organizational), or prompt injection defense (use prompt-engineer).

curiositech/windags-skills

Data structures and serialization formats for agent-to-agent communication. Covers message envelopes, structured output schemas, capability declarations, task handoff payloads, error/retry signaling, and context windows as data structures. Deep comparison of A2A protocol, MCP, OpenAI function calling, and LangChain message types. Teaches when to use rigid schemas vs free-form with validation, typed vs untyped, streaming vs batch. Activate on: "agent message format", "agent communication schema", "agent-to-agent protocol", "A2A protocol", "MCP message format", "structured output for agents", "agent interop", "interchange format", "agent serialization", "task handoff format", "capability declaration". NOT for: what agents say to each other (use agent-conversation-protocols), orchestration topology (use multi-agent-coordination), building agent infrastructure (use agentic-infrastructure-2026).

curiositech/windags-skills

Logic-based agent programming language implementing BDI architecture for practical autonomous agent development

curiositech/windags-skills

>- Design AgentSpeak(L)-style BDI agents with context-guarded plans, selection functions, and intention stacks. Use for interruptible autonomy, agent policy, and multi-agent orchestration in dynamic environments. NOT for simple rule engines, static planners, or centralized workflows.

curiositech/windags-skills

Foundational concurrent computation model where actors communicate exclusively through asynchronous message passing

curiositech/windags-skills

license: Apache-2.0 NOT for unrelated tasks outside this domain.

相關技能