How to check inside service is same service alread

2019-05-22 20:49发布

问题:

I have a service which is used by many application. Developers just start the service and it does its work. If AppA, AppB and AppC start the service I am getting duplicates of my services. Duplicates are not so bad, in fact there should be duplicates of service, but services should do their work if and only if none of duplicates are already doing same job. My problem is, checking inside service wether its runing looks like against logic because if you start service, of course its already runing and it makes no sense to check. Service is by the way STICKY. I want to keep duplicates, if service that does job gets killed, another one (one of duplicates) will start do the job, since none of services doing it. Is there any work around? How could I achieve that? Please if something is unclear, let me know.

回答1:

public class PlayerService extends Service {

    /** The Singleton PlayerService instance. */
    private static PlayerService _instance = null;

    @Override
    public void onCreate() {
        _instance = this;
    }

    public static boolean isPlayerServiceRunning() {
        return _instance != null;
    }