I can't get a startService working from my BroadcastReceiver

守給你的承諾、 提交于 2019-12-24 09:32:52

问题


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>

回答1:


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);



回答2:


Got it :-D sort of. Now I know the problem. The code you suggested works.

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

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 :)



来源:https://stackoverflow.com/questions/8456856/i-cant-get-a-startservice-working-from-my-broadcastreceiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!