【问题标题】:How can I start a service of an app when the device boots? (Android) [duplicate]设备启动时如何启动应用程序的服务? (Android)[重复]
【发布时间】:2014-07-19 13:22:58
【问题描述】:

如何写一个service,当device boots时自动启动?例如:当我启动手机时,我收到了新的WhatsApp 消息,而之前没有打开WhatsApp

【问题讨论】:

    标签: java android


    【解决方案1】:

    Himanshu 回答的两个补充:

    • 启动监听应用程序不得安装在 sdcard 上。请记住,设备启动可能已完成 在 sdcard 甚至挂载之前导致您的应用程序的启动侦听器没有被激活

    • 只有在用户激活您的 应用第一次。从 4.2 开始(此处不确定)android 会阻止所有服务 & 新安装的应用声明的监听器从被激活直到被用户显式激活。

    在用户单击主屏幕图标时显式激活。

    【讨论】:

      【解决方案2】:

      您可以使用它来使其工作:

      您的manifest 文件:

      <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jjoe64">
      
          <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
      
          <application>
              <receiver android:name=".BootCompletedIntentReceiver">
                  <intent-filter>
                      <action android:name="android.intent.action.BOOT_COMPLETED" />
                  </intent-filter>
              </receiver>
              <service android:name=".BackgroundService" />
          </application>
      
      </manifest>
      

      添加这个类BootCompletedIntentReceiver.java

      public class BootCompletedIntentReceiver extends BroadcastReceiver {
          @Override
          public void onReceive(Context context, Intent intent) {
              if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
                  Intent pushIntent = new Intent(context, BackgroundService.class);
                  context.startService(pushIntent);
              }
          }
      }
      

      这将使它在设备启动后自动启动您的服务

      【讨论】:

      • 为什么要硬编码BroadcastReceiver 中的Intent?为什么不用对应的常量Intent.ACTION_BOOT_COMPLETED?还要用 4 个空格来缩进你的代码,而不是一个......这次我已经修复了你的格式。
      猜你喜欢
      • 1970-01-01
      • 2020-02-10
      • 2015-10-28
      • 2018-08-14
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2015-08-18
      相关资源
      最近更新 更多