我不能让一个startService从我的广播接收器工作 [英] I can't get a startService working from my BroadcastReceiver
问题描述
我想,当警报会从我的广播接收器触发启动我的服务。我没有得到任何错误和code运行,但它不是我的启动服务,我没有得到任何错误。难道说是我的服务,或在清单有问题?
我注意到,我经常得到的问题,当谈到意图和语境。我试图读了它,但我不能找到一个网站,解释它的一个好办法,但。有什么建议?
公共类报警扩展广播接收器{ @覆盖
公共无效的onReceive(上下文的背景下,意图意图){ 振动器振动=(振动器)context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000); 意图为myService =新意图(BackgroundService.class.getName());
context.startService(为myService);
}
}
****************** 清单*******
<服务机器人。BackgroundServiceNAME =机器人:工艺=:远程>
&所述;意图滤光器>
<作用机器人:名字=se.davidsebela.ShutMeUp.BackgroundService/>
&所述; /意图滤光器>
< /服务><接收安卓过程=:遥控机器人:名字=报警>< /接收器>
< /用途>
意图为myService =新意图(BackgroundService.class.getName());
这将创建只是一个动作一个新的意图。的动作是BackgroundService类的名称。当您使用此将无法正常工作 startService()
。
而使用的意图构造,获取类和上下文参数,而不是:
意图为myService =新意图(背景下,BackgroundService.class);
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>
Intent myService = new Intent(BackgroundService.class.getName());
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:
Intent myService = new Intent(context, BackgroundService.class);
这篇关于我不能让一个startService从我的广播接收器工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!