Sometimes we need our program to run automatically after the system starts up. At this time, we can use the Broadcast Mechanism in Android to compile a class that inherits BroadcastReceiver and accept the system to start and stop broadcasting. The Code is as follows:
[Java]View plaincopy
- /**
- * @ Author coolszy
- * @ Date 2011-6-14
- * @ Blog http://blog.csdn.net/coolszy
- */
- Public class BootCompletedReceiver extends BroadcastReceiver
- {
- @ Override
- Public void onReceive (Context context, Intent intent)
- {
- Log. I ("MainActivity", "system started ");
- }
- }
Then, register in the AndroidManifest. xml file:
[Xhtml]View plaincopy
- <Cycler android: name = ". BootCompletedReceiver">
- <Intent-filter>
- <Action android: name = "android. intent. action. BOOT_COMPLETED"/>
- </Intent-filter>
- </Cycler>
Add the required permissions:
[Xhtml]View plaincopy
- <Uses-permission android: name = "android. permission. RECEIVE_BOOT_COMPLETED"/>
Since the Android system sends a broadcast after it is started, is there a broadcast when the system is disabled? Query the help document and find the system-disabled broadcast:
[Java]View plaincopy
- /**
- * @ Author coolszy
- * @ Date 2011-6-14
- * @ Blog http://blog.csdn.net/coolszy
- */
- Public class ShutdownReceiver extends BroadcastReceiver
- {
- @ Override
- Public void onReceive (Context context, Intent intent)
- {
- Log. I ("MainActivity", "starting to close ...");
- }
- }
Register in the AndroidManifest. xml file:
[Xhtml]View plaincopy
- <Cycler android: name = ". shutdowncycler">
- <Intent-filter>
- <Action android: name = "android. intent. action. ACTION_SHUTDOWN"/>
- </Intent-filter>
- </Cycler>
Do you still need the corresponding permissions? After querying the help document, you cannot find the relevant permissions. Test the help document in the simulator. After the system is disabled, the information can be output normally.