android register a permanent Broadcast Receiver

后端 未结 1 2000
野趣味
野趣味 2021-01-24 08:12

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 star

相关标签:
1条回答
  • 2021-01-24 08:34

    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.

    0 讨论(0)
提交回复
热议问题