我无法从 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>
I am trying to start my Service when an alarm gets triggered from my BroadcastReceiver. I am not getting any error and the code runs, but its not starting my service and I am not getting any errors. Could it be a problem that is in my Service or in the manifest?
I have noticed that I am often getting problems when it comes to Intents and Contexts. I have tried to read up on it, but I can't find a site that explains it in a good way though. Any suggestions?
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);
}
}
****************** Manifest*******
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这只需一个动作就可以创建一个新的意图。该操作是BackgroundService 类的名称。当您使用
startService()
时,这将不起作用。而是使用获取类和上下文作为参数的意图构造函数:
This creates a new intent with just an action. The action is the name of the BackgroundService class. This won't work when you are using
startService()
.Rather use the intent constructor that gets a class and a context as arguments instead:
明白了:-D 有点。现在我知道问题所在了。您建议的代码有效。
但问题是我的服务已经在运行。本以为被杀掉了,结果只是定时器停止了,服务还在运行。因此,当执行上面两行时,它基本上什么也不做。
现在我必须找出如何真正杀死它:)
Got it :-D sort of. Now I know the problem. The code you suggested works.
But the problem is that my Service is already running. I thought that it was killed, but only the timer was stopped and the service was still running. So when the two lines above are executed it basically dose nothing.
Now I have to find out how to really kill it :)