ANDROID注册一个永久的广播接收机 [英] android register a permanent Broadcast Receiver

查看:321
本文介绍了ANDROID注册一个永久的广播接收机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个BroadcastReceiver在紧接每次执行特定任务的设备启动。此外,单击某个按钮时,接收机应该停止在开始启动。有人可以帮助我来管理?

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?

推荐答案

所有你需要解决你的问题的第一部分是让的BroadcastReceiver 它并宣布它在你的表现为:

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>

QUICKBOOT_POWERON 是必要的不发 BOOT_COMPLETED 播出一些设备。 HTC设备喜欢用QuickBoot工具1代替。

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.

对于你的问题的第二部分,有一些不同的方式,你可以做到这一点。你可以简单地设置一个值共享preferences 你的接收器检测每次发射时间,并退出立即如果该值指示等。

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.

您也可以禁用接收器code:

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.

这篇关于ANDROID注册一个永久的广播接收机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆