How to stop a running service using broadcast rece

2019-09-14 00:21发布

问题:

I think there is a simple problem in my code but I couldn't figure it out. I have a HeaderService which shows a bubble popup over some particular apps. Now what I want is stop that service when user presses Home key or Back key using BroadCastReceiver. Please take a look at my code and suggest me some solution. Thanks in Advance!!

This is my Receiver class

public class PopupClosingReceiver extends BroadcastReceiver {


private boolean isMyServiceRunning(Context con) {
    ActivityManager manager = (ActivityManager) con.getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (HeaderService.class.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

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

    if(isMyServiceRunning(context)){

        Intent serviceIntent = new Intent(context, HeaderService.class);
        context.stopService(serviceIntent);

    }

}

AndroidManifest.xml

<receiver android:name=".PopupClosingReceiver">
        <intent-filter>
            <category android:name="android.intent.category.HOME"/>
        </intent-filter>
    </receiver>