@santoshyadavviolet/capacitor-background-service
v1.0.2
Published
Capacitor plugin to keep Android app running in background with auto-restart
Downloads
255
Maintainers
Readme
capacitor-background-service
Capacitor plugin to keep your Android app running in the background using a foreground service with automatic restart capability.
Features
- Foreground Service: Keeps app running in background with persistent notification
- Auto-restart: Automatically restarts service if killed by Android
- Boot Start: Optionally start service on device boot
- Wake Lock: Prevents CPU from sleeping while service is active
- Task Removal Handling: Restarts service when app is swiped away from recents
Installation
npm install capacitor-background-service
npx cap syncAndroid Configuration
1. Update AndroidManifest.xml
The plugin's manifest will be merged automatically, but you may need to request notification permission in your app's main AndroidManifest.xml for Android 13+:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>2. Request Runtime Permissions (Android 13+)
For Android 13 and above, you need to request notification permission at runtime:
import { BackgroundService } from 'capacitor-background-service';
// Request notification permission first (Android 13+)
async function requestPermissions() {
if (Capacitor.getPlatform() === 'android') {
// Use Capacitor's PermissionsPlugin or request manually
// This is required for the notification to show
}
}Usage
Basic Example
import { BackgroundService } from 'capacitor-background-service';
// Start the background service
await BackgroundService.start({
title: 'App is running',
text: 'Background service is active',
autoRestart: true,
startOnBoot: false
});
// Check if service is running
const { running } = await BackgroundService.isRunning();
console.log('Service running:', running);
// Stop the service
await BackgroundService.stop();Advanced Example
import { BackgroundService } from 'capacitor-background-service';
await BackgroundService.start({
title: 'My App',
text: 'Syncing data in background',
channelId: 'my_channel_id',
channelName: 'My Background Service',
autoRestart: true, // Auto-restart if killed
startOnBoot: true // Start on device boot
});Integration with Angular
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { Platform } from '@ionic/angular';
import { BackgroundService } from 'capacitor-background-service';
import { Capacitor } from '@capacitor/core';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
})
export class AppComponent implements OnInit {
constructor(private platform: Platform) {}
async ngOnInit() {
await this.platform.ready();
if (Capacitor.getPlatform() === 'android') {
await this.startBackgroundService();
}
}
async startBackgroundService() {
try {
await BackgroundService.start({
title: 'My App',
text: 'Running in background',
autoRestart: true,
startOnBoot: true
});
console.log('Background service started');
} catch (error) {
console.error('Failed to start background service:', error);
}
}
}API
start(options: StartOptions)
Starts the foreground service.
Parameters:
title(string): Notification titletext(string): Notification text/descriptionicon(string, optional): Small icon resource namechannelId(string, optional): Notification channel ID (default: 'background_service_channel')channelName(string, optional): Notification channel name (default: 'Background Service')autoRestart(boolean, optional): Enable auto-restart on kill (default: true)startOnBoot(boolean, optional): Start on device boot (default: false)
Returns: Promise<void>
stop()
Stops the foreground service.
Returns: Promise<void>
isRunning()
Checks if the service is currently running.
Returns: Promise<{ running: boolean }>
Important Notes
Android Battery Optimization
Some Android manufacturers (Xiaomi, Huawei, OnePlus, etc.) have aggressive battery optimization that may still kill your app. Users may need to:
- Disable battery optimization for your app
- Add app to "Auto-start" whitelist
- Lock app in recent apps
You should guide users to do this in your app's settings or onboarding.
Android 12+ Restrictions
Starting from Android 12, there are stricter limitations on starting foreground services from the background. Make sure to:
- Start the service when your app is in the foreground
- Request necessary permissions (POST_NOTIFICATIONS for Android 13+)
- Use appropriate foreground service types in the manifest
Battery Usage
Using a foreground service with wake lock will increase battery consumption. Use this plugin only when necessary and inform users about battery impact.
Troubleshooting
Service not starting
- Ensure you have the required permissions in AndroidManifest.xml
- Check that notification permission is granted (Android 13+)
- Start the service while app is in foreground
Service gets killed
- Some manufacturers have aggressive battery optimization
- Guide users to whitelist your app
- Check device-specific battery settings
Notification not showing
- Request POST_NOTIFICATIONS permission on Android 13+
- Check that notification channels are properly created
- Verify app has notification permissions enabled
Platform Support
- ✅ Android
- ❌ iOS (not supported - iOS has strict background limitations)
- ❌ Web (not supported)
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
