Android的:如何在引导时启动基于用户设置的服务?用户、如何在、Android

2023-09-13 00:37:33 作者:一懒众衫小

嘿大家, 我想编写一个应用程序,它包含了管理后台服务的活动。不过,我想实现一个用户设置为自动启动该服务,在开机的时间。我有一个共享preferences实现用户设置,我用一个BroadcastReceiver和监听BOOT_COMPLETED有启动在启动的服务。

Hey everyone, I'm trying to write an app that consists of an activity that manages a background service. However, I want to implement a user setting for automatically starting the service up at boot time. I have user settings implemented with SharedPreferences and I have the services starting up at boot by using a BroadcastReceiver and listening for BOOT_COMPLETED.

不过,我想不出来实现的设置,使该服务仅在系统启动,如果说设置已启用的好方法。我能想到的一些廉价的方式来做到这一点(如用的onCreate()在服务搞乱,或创建/检查在SD卡上的文件),但我想跟着好习惯。

However, I can't figure out a good way to implement a setting so that the service is only started at boot if said setting is enabled. I can think of a few cheap ways to do this (such as messing with onCreate() in the service, or creating/checking for a file on SD card) but I want to follow good practice.

必须有一个很好的办法做到这一点,因为有吨的应用程序,在那里,这样做,我只是找不到任何在线有关如何做到这一点。

There must be a good way to do this because there's tons of apps out there that do it, I just can't find anything online about how to do it.

感谢

推荐答案

显然,你需要将其设置为一个BOOT_COMPLETED接收器在你的清单,但这个code工作 - 它采取几乎是直接从我的应用程序之一。 ..

Obviously you need to set this up as a BOOT_COMPLETED receiver in your manifest, but this code works - it's taken almost straight from one of my apps...

public class Booter extends BroadcastReceiver {

  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
      SharedPreferences prefs = context.getSharedPreferences("PACKAGENAME_preferences",0);
      if (prefs.getBoolean("startatboot",false)) {
        ... DO STUFF HERE ...
      }
    }
  }
}