【问题标题】:android: use Intent.ACTION_BOOT_COMPLETED or ...?android:使用 Intent.ACTION_BOOT_COMPLETED 或 ...?
【发布时间】:2018-12-20 01:25:32
【问题描述】:

在 AndroidManifest 文件中,我想在用户重新启动设备时捕获 BOOT_COMPLETED 事件。我正在添加此权限:

"使用权限 android:name="android.permission.RECEIVE_BOOT_COMPLETED"

我在 Stackoverflow 上看到过其他人使用的两个“意图过滤器”:

“Intent.ACTION_BOOT_COMPLETED”和

“android.intent.action.BOOT_COMPLETED”

这里首选的操作字符串是什么?请指教和解释。

【问题讨论】:

    标签: android android-manifest bootcompleted


    【解决方案1】:

    Intent.ACTION_BOOT_COMPLETED == android.intent.action.BOOT_COMPLETED

    它们是相同的,因为如果您查看Intent.ACTION_BOOT_COMPLETED 的值,您会发现它是android.intent.action.BOOT_COMPLETED

    通常在 Manifest 中,您将使用 android.intent.action.BOOT_COMPLETED,因为 Intent.ACTION_BOOT_COMPLETED 是 Java 代码而不是 xml。

    但是在您的代码中,您可以使用Intent.ACTION_BOOT_COMPLETED 作为替代,因为它更容易记住。

    【讨论】:

      【解决方案2】:

      这是一个完整的解决方案:

      在清单中设置权限:

      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
      

      当你的系统重新启动时,你需要一个接收器来运行,如下所示:

      public class StartMyActivityAtBootReceiver extends BroadcastReceiver {
      
          @Override
          public void onReceive(Context context, Intent intent) {
              if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
                 // everything here executes after system restart
              }
          }
      }
      

      在您的清单中包含此接收器,如下所示:

      <receiver
          android:name=".service.StartMyActivityAtBootReceiver"
          android:label="StartMyServiceAtBootReceiver">
          <intent-filter>
              <action android:name="android.intent.action.BOOT_COMPLETED" />
          </intent-filter>
      </receiver>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-08
        • 1970-01-01
        • 2014-03-02
        • 2013-10-06
        • 1970-01-01
        • 2017-11-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多