Android java.lang.IllegalArgumentException: Service not registered

java.lang.IllegalArgumentException: Service not registered

First check whether the Service is registered in the AndroidManifest file. The format is as follows:

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

If the Service has already been registered, this error will still be reported, it may be

  1. If bindService fails, unbindService directly;
  2. It may also be that unbindService has been successful, and unbindService has been performed many times.

Solution:

Every time a service is bound, a boolean value is used to record the state as true.
When the service is unbound, check whether the boolean value is true. If it is true, the service is canceled and the boolean value is set to false.

In this way, even if the service is canceled many times, it will not report "service not registered".

The sample code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

private boolean mIsBound=false ;

public void doBindService() {

  Intent bindIntent = new Intent(this, MyService.class);

   bindService(bindIntent,connection,BIND_AUTO_CREATE);

    mIsBound = true;

}

  

public void doUnbindService() {

    if (mIsBound) {

        unbindService(mConnection);

        mIsBound = false;

    }

}

Reprinted in: https://www.cnblogs.com/expiator/p/5719774.html 

Guess you like

Origin blog.csdn.net/weixin_42602900/article/details/131441141