Sriniketh
Sriniketh

Reputation: 55

Unable to start/stop service from BroadcastReceiver

I have an activity which starts a service. Now, i want to start/stop the service in a BroadcastReceiver which listens to screen off/on. I used:

public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        Log.d("Screen:", "In Method:  ACTION_SCREEN_OFF");
        context.stopService(new Intent(context, ScreenReceiver.class));
    } 
    else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
        Log.d("Screen:", "In Method:  ACTION_USER_PRESENT");
        context.startService(new Intent(context, ScreenReceiver.class));
    }
}
}

I have added the required permissions and have registered/unregistered the BroadcastReceiver in the service. I am able to see the Log messages in Logcat when i run the code, but the service doesn't seem to stop. How should i fix it? Thanks in advance.

Upvotes: 3

Views: 5640

Answers (1)

Lazy Ninja
Lazy Ninja

Reputation: 22537

You are trying to restart your BroadcastReceiver.
Use you service class instead.

context.startService(new Intent(context, ScreenReceiver.class));

should be

context.startService(new Intent(context, YourService.class));

and in your manifest file:

<service android:name=".YourService"></service>

Upvotes: 5

Related Questions