简体   繁体   English

android注册永久广播接收器

[英]android register a permanent Broadcast Receiver

I need to create a BroadcastReceiver which performs certain task immediately each time the device boots up. 我需要创建一个BroadcastReceiver,每次设备启动时立即执行某些任务。 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: 解决问题的第一部分所需要做的就是为其创建一个BroadcastReceiver并将其在清单中声明为:

<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. QUICKBOOT_POWERON是必要的不发送的一些设备BOOT_COMPLETED广播。 HTC devices like to use the quickboot one instead. HTC设备喜欢使用quickboot之一。

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. 您可以简单地在接收者每次触发时在SharedPreferences中设置一个值,并在该值指示时立即退出。

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. 如果要走那条路,就必须尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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