Android has a concept of Service, or a process that can sit in the background and run a task without needing to interact with the user. There’s plenty of reasons why a Service might not need to be running all the time (say an alarm clock app with no alarms scheduled), but for the most part, Services need to be started at boot. Here’s how, tested from Android 1.5 to 2.2, since no other example I could find on the Internet was complete for this ever-changing SDK.
This example Service, StartAtBootService, is a member of the package com.example.ssab (StartServiceAtBoot): Be careful with your Service implementation, as the onStart() method is depreciated in newer versions of the SDK!
This example Service, StartAtBootService, is a member of the package com.example.ssab (StartServiceAtBoot): Be careful with your Service implementation, as the onStart() method is depreciated in newer versions of the SDK!
Use any Service you already have instead of the above. Within application in your AndroidManifest.xml define your Service with an intent-filter:
Now the new part. The OS broadcasts ACTION_BOOT_COMPLETED when it has finished booting. Your app can ask to receive this notification by requesting permission in your manifest:
Your app now gets the broadcast, but still needs to do something with it. This is done by subclassing the BroadcastReceiver class. As far as I know, ACTION_BOOT_COMPLETED is the only Intent broadcast to apps, but because this could change at any point (and I can all but guarantee it will), do yourself a favor and check the Intent in your onReceive() method:
The last thing you need to do is register your BroadcastReceiver in your manifest, within application:
That should do it. If you’re using Eclipse, run your app once and then exit the emulator. Then issue emulator -avd your_avd_name to launch your emulator without uninstalling your app. An adb logcat | grep StartAtBootService should show your app starting at boot.
No comments:
Post a Comment