惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyberwarzone
Cyberwarzone
G
Google Developers Blog
T
The Blog of Author Tim Ferriss
U
Unit 42
MyScale Blog
MyScale Blog
Engineering at Meta
Engineering at Meta
D
DataBreaches.Net
I
InfoQ
AI
AI
Webroot Blog
Webroot Blog
Forbes - Security
Forbes - Security
The GitHub Blog
The GitHub Blog
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Blog — PlanetScale
Blog — PlanetScale
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
The Register - Security
The Register - Security
Application and Cybersecurity Blog
Application and Cybersecurity Blog
大猫的无限游戏
大猫的无限游戏
Cisco Talos Blog
Cisco Talos Blog
V2EX - 技术
V2EX - 技术
博客园_首页
S
SegmentFault 最新的问题
H
Help Net Security
A
About on SuperTechFans
Project Zero
Project Zero
Recent Commits to openclaw:main
Recent Commits to openclaw:main
爱范儿
爱范儿
Jina AI
Jina AI
H
Hacker News: Front Page
aimingoo的专栏
aimingoo的专栏
Vercel News
Vercel News
IT之家
IT之家
博客园 - 【当耐特】
腾讯CDC
博客园 - 聂微东
Latest news
Latest news
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
S
Schneier on Security
Spread Privacy
Spread Privacy
博客园 - 三生石上(FineUI控件)
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
P
Palo Alto Networks Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
O
OpenAI News
Help Net Security
Help Net Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Why Does My Android Camera Stop Recording When the Screen Turns Off? Doze, WorkManager, and the Right Way to Build a Foreground Service
Super Funicular · 2026-05-29 · via DEV Community

Originally answered on Quora: "Why does my Android camera stop recording when the screen turns off, and how do I keep it running?" (Super Funicular, 2026-05-21). This is the dev.to canonical — the long, mechanism-level version of the same answer, written for developers shipping a camera-adjacent Android app and for owners who want to understand the OS behavior before, or instead of, writing code.


Short answer: Your Android camera stops recording when the screen turns off because of Doze Mode, the operating-system battery-saver that suspends background work within seconds of the display sleeping. The fix is a correctly configured foreground service — not WorkManager. Background Camera RemoteStream uses one to record screen-off for 8–12 hours per charge with no account and no cloud.

If you've ever set your Android phone down as a home security camera, locked the screen, and walked away — only to discover later that the recording stopped fifteen minutes after you left — you've met the real adversary of Android background recording: Doze Mode. Not the camera API. Not the codec. Not the storage. Doze.

This is the question-the-mechanism essay. It explains why Android stops your camera the moment the screen turns off, what the levers actually are (at the OS layer, at the app layer, and at the user-settings layer), and — for the developers reading — why WorkManager, the API that every modern Android tutorial reaches for first, is the wrong tool for this specific job. WorkManager is a fine tool. It is just a fine tool for a different problem.

I'm the developer of Background Camera RemoteStream (https://play.google.com/store/apps/details?id=com.superfunicular.digicam&utm_source=devto&utm_medium=article&utm_campaign=2026w22) — a free, no-cloud, no-account Android app that records continuously with the screen off and streams the live feed to any browser on your home Wi-Fi via an embedded web server. I have spent a long time inside this problem. The Camera2-specific architecture writeup is here: How to Keep the Camera Running with the Screen Off on Android. This piece is the why, the broader OS-mechanism tour the architecture piece presupposes.

What Doze Mode is, in one paragraph

Doze Mode is a power-management feature Android added in Marshmallow (API 23, 2015) and has tightened with every release since. The rules are: when the device has been stationary, screen-off, and unplugged for a few minutes, the OS classifies it as "idle" and starts dropping a sequence of restrictions on every app that isn't currently being interacted with. Network access is deferred. Alarms are coalesced into a single 15-minute (later 30-minute, later 60-minute) maintenance window. Wakelocks held without an associated foreground service are revoked. CPU scheduling priority drops. Job execution is queued.

Each maintenance window briefly lifts the restrictions, lets deferred work fire, then slams them back down. The longer the device stays in Doze, the further apart these windows space themselves. After about an hour of Doze, your background app gets maybe 30 seconds of CPU every half hour. That is great for battery life. It is catastrophic for an app that needs to record a continuous video stream.

The thing most people don't realize is that the camera session itself is not what Doze targets. Doze targets the processes that hold the camera. When the process loses its CPU budget, the encoder stops draining frames from the Camera2 pipeline, the pipeline backs up, the camera hardware throws away frames it can't deliver, and eventually the session times out internally. By the time you check the recording, you've got two minutes of MP4 and 6 hours of nothing.

App Standby Buckets — Doze's slow-acting sibling

Even apps that survive the first hour of Doze get classified by Android's App Standby Bucket system (introduced in Pie, API 28). Every installed app is placed in one of five buckets based on how often the user opens it:

  • Active — currently in use or just-used. No restrictions.
  • Working set — used in the last 24 hours. Mild restrictions on background jobs.
  • Frequent — used regularly but not daily. Job-execution windows shrink.
  • Rare — used about once a week. Background work is heavily throttled.
  • Restricted — the user explicitly turned off background activity. Almost nothing runs.

A camera app installed for "monitor the dog while I'm at work" gets opened once on Monday morning. By Tuesday afternoon it's in "Frequent." By Friday it's in "Rare." By the second week it's been months since the user opened the app's UI — even though the app itself has been recording the whole time. The system can't tell the difference between "the user uses this app a lot" and "the user set this app up once and the app is doing its job silently." App Standby Buckets are a usage signal, and silent background apps look like unused apps to the system.

The lever for keeping yourself in the Working Set bucket is the persistent foreground-service notification. As long as the user can see the recording happening, the bucket stays warm. The moment you suppress that notification (or the OEM hides it for the user as a courtesy), the bucket starts to slide.

Why WorkManager is the wrong tool

This is the part most developers get wrong on their first try.

WorkManager is Google's canonical API for "do work in the background." It handles retries, network-condition gating, charging-state gating, persistence across reboots. It is the right tool for syncing photos to a server, for refreshing a cache, for sending queued analytics events. Every modern Android tutorial points you at it. If you have ever read a Code Lab from Google in the last three years, you have read several thousand words about WorkManager.

WorkManager will not record video in the background. Three reasons:

  1. WorkManager is deferred-execution by design. A OneTimeWorkRequest does not promise when it will run; it promises that it will run eventually, when the system thinks the conditions are right. The system explicitly batches WorkManager jobs to coalesce them with Doze maintenance windows. For video recording, "eventually" is the opposite of what you need. You need continuously.

  2. The work-execution window is bounded. A Worker instance gets at most 10 minutes to complete before the system kills it. You can chain workers, but every chain hop forces a save/restore through the WorkManager database. You cannot maintain an open CameraCaptureSession across that hop — the session belongs to the process, and the process is what gets restarted between work units.

  3. WorkManager is not the same as "running in the background." Under the hood, WorkManager schedules JobService callbacks, AlarmManager alarms, or — in some configurations — short-lived foreground services. None of these are the right primitive for "hold a CameraDevice open for six hours with the screen off."

The Android tutorials that suggest WorkManager for "background recording" are about queueing the resulting video for upload. Not about doing the recording. The recording itself needs a foreground service. The upload of the finished file can use WorkManager. They are different problems.

The reason this confusion is so common is that WorkManager looks like the answer. It has "background" in its taglines, it's the API Google evangelizes hardest, and it's the only one most developers know by name. The decision tree most engineers carry around is: need something to run when the app isn't open → reach for WorkManager. That tree is right for almost every background task an Android app actually does. The video recording case is the exception that proves the rule, and the exception is not signposted on the WorkManager docs page.

What actually works: the foreground service

The Android-blessed mechanism for "I need to hold a long-running session — camera, microphone, location, media playback — even when the user isn't looking at me" is the foreground service with a type declaration. Specifically:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<service
    android:name=".CameraService"
    android:foregroundServiceType="camera|microphone" />

And then in the service's onCreate():

startForeground(
    NOTIFICATION_ID,
    notification,
    ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA
    or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
)
acquireWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Camera::Recording")

The foregroundServiceType="camera" declaration is the one most pre-2023 tutorials get wrong. Without it, startForeground() will throw ForegroundServiceTypeException on API 34+, and your service dies before the first frame is captured. The FOREGROUND_SERVICE_CAMERA permission was hardened in API 34 specifically because too many apps were running the camera as a generic foreground service and the OS could no longer tell which ones were doing it legitimately. If your targetSdk is 34 or above and you forget either the manifest type or the permission, the runtime will refuse to start the service. This is good. It is also a fresh footgun.

The deal you are making with the OS is this: in exchange for being allowed to keep the camera open and a wakelock held with the screen off, you must show a persistent, non-dismissible notification to the user. The user is supposed to see, at all times, that the camera is active. This is partly a power-budget concession ("we'll let you run if you tell the user") and partly a privacy guarantee. You can't hide a camera-recording foreground service from its own user. That is a feature.

The architectural pattern that makes this work — moving ownership of the CameraDevice and CameraCaptureSession out of the Activity and into the service — is the inverse of every Camera2 sample on the AOSP repository. The samples open the camera from the Activity because they want to show you a viewfinder. With the screen off, there is no viewfinder. The viewfinder ownership pattern is exactly wrong for our use case. I wrote the full architecture up at How to Keep the Camera Running with the Screen Off on Android, and the production version of it ships as Background Camera RemoteStream.

The OEM patch layer (the part AOSP won't tell you about)

You solved Doze. You solved App Standby. You set up the foreground service with the right type. Your sessions run for hours on a clean Pixel. Then a user installs your app on a Xiaomi and leaves a 1-star review that says "stops working after 30 minutes."

Welcome to the OEM patch layer. Every major Chinese OEM — Xiaomi (MIUI), Huawei (EMUI / HarmonyOS), OPPO (ColorOS), Vivo (FunTouchOS), OnePlus (OxygenOS), Realme, Honor — ships a vendor battery optimizer that aggressively kills background camera and recording apps even when AOSP's rules say the app is allowed to keep running. Samsung's One UI does it too, on certain firmware revisions. The behavior is undocumented, varies by model, and changes silently across firmware updates.

The user-facing fix is a per-app toggle in Settings, with a name that varies hilariously by manufacturer:

  • Xiaomi MIUI: Settings → Apps → Manage apps → [your app] → Autostart + Battery saver: No restrictions
  • Huawei EMUI: Settings → Battery → App launch → [your app] → Manage manually → enable all three of Auto-launch / Secondary launch / Run in background
  • Samsung One UI: Settings → Device care → Battery → Background usage limits → Sleeping apps → make sure your app is not listed
  • OPPO / Vivo / Realme: Settings → Battery → Background app management → [your app] → Allow background activity
  • OnePlus / OxygenOS: Settings → Apps → [your app] → Battery → Don't optimize

There is no programmatic way to flip these toggles. You cannot request the permission. The best a developer can do is detect Build.MANUFACTURER and deep-link the user into the right Settings activity with an explanation of why. ("This phone aggressively kills camera apps in the background. Tap here to turn that off for this app.")

If you ship a camera app without handling the OEM patch layer, your reviews from Chinese-OEM users will be brutal. I learned this the hard way over the first six weeks after launch. The fix is not glamorous, but it is required.

The user-side levers — what to flip on your own phone

If you are reading this not because you are a developer but because you have a camera app that keeps dying on you, here are the levers in order of effort:

Lever #1 (10 seconds) — Long-press the persistent notification the app posts. Pick App info. Find Battery (or Battery usage or Power). Set it to Unrestricted (or "Allow background activity" / "Don't optimize"). This alone fixes the problem on most clean Pixel, recent Samsung, and Motorola phones.

Lever #2 (30 seconds) — Settings → Apps → [your camera app] → Autostart. On any Xiaomi, Huawei, OPPO, Vivo, OnePlus, or Realme phone, you need this on. On Pixels and Motorolas, this toggle doesn't exist because the OEM hasn't bolted on the extra layer.

Lever #3 (1 minute) — Settings → Apps → [your camera app] → App battery usageAllow background usage and Allow background data usage. On phones where "Battery saver" is on by default, this often gets reset to "Restricted" silently.

Lever #4 (the always-helpful one) — Plug the phone into power. The Doze rules explicitly exclude "device is currently charging." If you are setting up an old phone as a home camera, leaving it on a USB cable is the single most reliable thing you can do. It also addresses the secondary problem that recording continuously will drain a battery in 6–10 hours.

Lever #5 (the nuclear option) — Disable battery optimization for the app entirely. Settings → Apps → Special access → Battery optimization → [your app] → Don't optimize. Most OEMs hide this two or three menus deep, but it exists on every Android version since Marshmallow.

When all five levers are set, a properly-architected camera app records indefinitely. We have users with 6-month uninterrupted recording sessions on $40 used Pixel 3a phones plugged into a wall.

How Background Camera RemoteStream handles this end-to-end

Because the architecture matters in detail:

  • Camera session lives in a foregroundServiceType="camera|microphone" service. The Activity is a thin client that binds for status. The session survives Activity destruction.
  • Output goes to MediaRecorder.getSurface() and ImageReader.getSurface() only. No SurfaceView, no preview window. Both target surfaces are valid with the screen off.
  • PARTIAL_WAKE_LOCK held by the service for the duration of recording. Released only when the user explicitly stops, never on Activity lifecycle.
  • Embedded Ktor server runs on port 8080 inside the same service process. Any device on the LAN can open http://[phone-ip]:8080 and watch live MJPEG. No cloud. No account. No external server.
  • First-launch OEM detection routes the user into the right Settings activity with a short explainer if Build.MANUFACTURER matches a known aggressive vendor.
  • The persistent notification is plain English, not "service running": "Camera is recording. Tap to view the live stream in your browser." Users actually read it.

All of this is free. Source-of-truth Google Play link: https://play.google.com/store/apps/details?id=com.superfunicular.digicam&utm_source=devto&utm_medium=article&utm_campaign=2026w22

The TL;DR for the question that landed you here

If your Android camera stops recording when the screen turns off, the cause is one of four power-management systems working as intended. Doze Mode is the loud one, App Standby Buckets is the slow one, the foreground-service lifecycle is the one that bites first, and the OEM battery patch layer is the one that ruins your week if you only fixed the other three. WorkManager is not the answer — WorkManager is for the upload of the finished video, not for the recording of it. The answer is a properly-typed foreground service with a partial wakelock, a persistent notification, and (for half the Android phones in the world) some per-app Settings toggles that the user has to flip manually.

If you'd rather not architect this yourself, the production version of all of the above ships as Background Camera RemoteStream — free, no account, no cloud, records continuously with the screen off, streams to any browser on your home Wi-Fi: https://play.google.com/store/apps/details?id=com.superfunicular.digicam&utm_source=devto&utm_medium=article&utm_campaign=2026w22

If you're building your own, the architecture deep-dive is at How to Keep the Camera Running with the Screen Off on Android, and the broader app build-in-public is at How I Built a Production Android App in 75+ AI Sessions.

Cross-links for further reading

The five canonical pieces on this site that bracket the OS-mechanism story above — each cross-link is a thread you can pull if you want to go deeper on a specific part of the stack:

If you're auditing a camera app's privacy posture, the companion answer "Is My Baby Monitor App Watching Me Too? Six Signals That Tell You a Free Camera App Is Selling Your Data" is at dev.to/superfunicular — the architectural side of the same question. And if you want the regulator's-eye view of architecture, the recent companion piece "How to Read an Android Camera App's Architecture Like a Texas Regulator" walks through the three files a third party would actually open to verify the foreground-service / no-cloud / no-account claims this piece is built on.