简体   繁体   中英

android register a permanent Broadcast Receiver

I need to create a BroadcastReceiver which performs certain task immediately each time the device boots up. Also, when a certain button is clicked, the receiver should stop starting on boot. Can someone help me to manage that?

All you need to solve the first part of your question is to make a BroadcastReceiver for it and declare it in your Manifest as:

<receiver android:name=".MyBootReceiver"
        android:enabled="true"
>
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    </intent-filter>
</receiver>

The QUICKBOOT_POWERON is necessary for some devices that don't send the BOOT_COMPLETED broadcast. HTC devices like to use the quickboot one instead.

For the second part of your question, there are a few different ways you could accomplish this. You could simply set a value in SharedPreferences that your receiver checks every time it fires, and exit immediately if the value dictates such.

You could also disable the receiver in code:

getPackageManager().setComponentEnabledSetting( 
    new ComponentName( this, MyBootReceiver.class ),
        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
        PackageManager.DONT_KILL_APP );

You can enable it using the same method:

getPackageManager().setComponentEnabledSetting( 
    new ComponentName( this, MyBootReceiver.class ),
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP );

I am unsure of the persistence of this method. I use it in one of my apps, but it's not for a boot receiver, and it doesn't have to persist across boots. You'll have to experiment with it if you want to go that route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM