【问题标题】:I can't get a startService working from my BroadcastReceiver我无法从我的 BroadcastReceiver 获得 startService
【发布时间】:2011-12-10 13:34:19
【问题描述】:

当我的 BroadcastReceiver 触发警报时,我正在尝试启动我的服务。我没有收到任何错误并且代码运行,但它没有启动我的服务并且我没有收到任何错误。这可能是我的服务或清单中的问题吗?

我注意到,当涉及到意图和上下文时,我经常遇到问题。我试图阅读它,但我找不到一个可以很好地解释它的网站。有什么建议吗?

public class Alarm extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(1000);

        Intent myService = new Intent(BackgroundService.class.getName());
        context.startService(myService); 
    }
}

******************清单************

<service android:name=".BackgroundService" android:process=":remote">
    <intent-filter>
    <action android:name="se.davidsebela.ShutMeUp.BackgroundService" />
    </intent-filter>
</service>

<receiver  android:process=":remote" android:name="Alarm"></receiver>
</application>

【问题讨论】:

    标签: java android service android-intent broadcastreceiver


    【解决方案1】:
    Intent myService = new Intent(BackgroundService.class.getName());
    

    这只需一个动作就可以创建一个新的意图。该操作是 BackgroundService 类的名称。这在您使用 startService() 时不起作用。

    而是使用获取类和上下文作为参数的意图构造函数:

    Intent myService = new Intent(context, BackgroundService.class);
    

    【讨论】:

    • 我得到相同的结果。在 Eclipse 中看起来不错,但是当我在 Android 模拟器中运行代码时,服务永远不会启动并且没有给出错误:(
    • @DavidSebela 您确定您的广播接收器已正确注册并接收到适当的广播吗?尝试在onReceive() 中添加断点或日志语句,看看你是否结束了,或者它是否没有被调用。在你的服务 onStart/onStartCommand 中也做同样的事情。
    • 我知道警报被触发,并且 onReceive 运行。我有 Log.d();在里面,但我在发布时已将它们删除。我的服务也做了很多,我知道它没有开始。但是我的服务中有很多东西,比如 timertasks 和其他东西。所以我会做一个新的服务来测试更多的东西。感谢负载:)
    • 嗯好的。我猜该服务也已在 AndroidManifest 中正确注册?
    【解决方案2】:

    知道了 :-D 有点。现在我知道问题所在了。您建议的代码有效。

    Intent myService = new Intent(context, TestService.class);
    context.startService(myService);
    

    但问题是我的服务已经在运行。我以为它被杀死了,但只有计时器停止了,服务仍在运行。因此,当执行上述两行时,它基本上没有任何作用。

    现在我必须找出如何真正杀死它:)

    【讨论】:

    • 并使用 stopSelf();让一切都像我想要的那样工作。谢谢加载alextsc
    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2021-03-09
    相关资源
    最近更新 更多