【问题标题】:Starting Service from BroadcastReceiver从 BroadcastReceiver 启动服务
【发布时间】:2011-06-06 05:12:19
【问题描述】:

我的应用程序中有ServiceBroadcastReceiver,但是如何直接从BroadcastReceiver 启动服务?使用

startService(new Intent(this, MyService.class));

BroadcastReceiver 中不起作用,有什么想法吗?

编辑:

context.startService(..);

有效,我忘记了上下文部分

【问题讨论】:

    标签: android broadcastreceiver


    【解决方案1】:

    别忘了

    context.startService(..);

    【讨论】:

    • 完美答案。阅读起来几乎没有什么问题。
    • 也检查这个链接groups.google.com/forum/#!topic/android-developers/WVoO8kQCFF0 context.startService(new Intent(MusicService.ACTION_PAUSE, null, context, MusicService.class));
    • 这很有帮助。
    • 非常感谢您的救援...:)
    • “上下文”应该是什么?
    【解决方案2】:

    应该是这样的:

    Intent i = new Intent(context, YourServiceName.class);
    context.startService(i);
    

    务必将服务添加到 manifest.xml

    【讨论】:

    • 典型清单项目(在 下,与 ' 处于同一“级别”):
    • @ArtSwri 它应该是 而不是接收者。
    【解决方案3】:

    使用BroadcastReceiveronReceive 方法中的context 来启动您的服务组件。

    @Override
    public void onReceive(Context context, Intent intent) {
          Intent serviceIntent = new Intent(context, YourService.class);
          context.startService(serviceIntent);
    }
    

    【讨论】:

    • 终于有人愿意提及“上下文”是什么了。谢谢。
    【解决方案4】:

    最佳实践:

    在创建意图时,尤其是从 BroadcastReceiver 开始时,不要将 this 作为上下文。 以context.getApplicationContext() 如下所示

     Intent intent = new Intent(context.getApplicationContext(), classNAME);
    context.getApplicationContext().startService(intent);
    

    【讨论】:

    • 是的。我们应该传递 context.getApplicationContext() 否则应用程序将崩溃
    • 请说说为什么?
    • 原因:只要注册上下文有效,上下文注册的接收者就会收到广播。例如,如果您在 Activity 上下文中注册,只要该 Activity 未被销毁,您就会收到广播。如果您在应用程序上下文中注册,只要应用程序正在运行,您就会收到广播。
    • 我还是崩溃了。
    【解决方案5】:
     try {
            Intent intentService = new Intent(context, MyNewIntentService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intentService );
            } else {
                context.startService(intentService );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    

    【讨论】:

      【解决方案6】:

      因为接收者的 onReceive(Context, Intent) 方法在主线程上运行,它应该快速执行并返回。如果您需要执行长时间运行的工作,请注意生成线程或启动后台服务,因为系统可以在 onReceive() 返回后终止整个进程。有关详细信息,请参阅对进程状态的影响 要执行长时间运行的工作,我们建议:

      在接收器的 onReceive() 方法中调用 goAsync() 并将 BroadcastReceiver.PendingResult 传递给后台线程。这在从 onReceive() 返回后保持广播活动。但是,即使采用这种方法,系统仍希望您很快完成广播(不到 10 秒)。它确实允许您将工作转移到另一个线程以避免主线程出现故障。 使用 JobScheduler 调度作业 developer.android.com

      【讨论】:

        【解决方案7】:

        最好使用 ContextCompat:

        Intent serviceIntent = new Intent(context, ForegroundService.class);
        ContextCompat.startForegroundService(context, serviceIntent);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-01
          相关资源
          最近更新 更多