I inherited some android code and i notice there is a class extending Service but its not declared in the manifest. I find this disturbing. i investigated further and i see that the service is not declared in the manifest yet it still works !
what is occuring is in an activities onResume the developer is calling the following:
@Override
protected void onResume() {
super.onResume();
mMyService = new MyService();
}
@Override
protected void onStart() {
super.onStart();
mMyService = new MyService();
}
i have never seen this practice before. would it cause a memory leak ? android components are declared in the manifest and never instantiated right ? The system takes care of it for you.
The service itself is declared like this
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
//... a bunch of other methods that do stuff by calling from the "new" instance would be below.
}
Again, nothing is declared in the manifest. is this another pattern, and is it safe ?
It "works" because the class is used as a regular java class - it has fields and public methods that you can call, but this is no longer an Android Service. An Android Service is a component intended to perform long running operations in background, it has a life-cycle, and also a reference to
Context.For example when creating the service instance with:
MyService service = new MyService()you will notice thatonCreate()method of the class is not called, and if you try to do something that involves the use of theContext, such as showing aToast, you will get an exception.