I had a similar issue and this is what I did.
MyService
and MyActivity
have a common part, MyEngine
, but the behaviour must be a bit different in these two cases.
One thing that is different is setup, but this setup is done in the classes MyService
and MyActivity
.
Another thing that is different for the activity and the service is done via a listener: MyEngine
defines the interface MyEngine.Listener
while MyService
and MyActivity
provide the engine with different implementations of that interface.
So, if you want to pass a boolean value, two methods are possible:
// Method 1: different initialization
class MyEngine {
MyEngine(boolean isService) { ... }
}
class MyActivity extends Activity {
private MyEngine = new MyEngine(false);
...
}
class MyService extends Service {
private MyEngine = new MyEngine(true);
...
}
// Method 2: callbacks
class MyEngine {
interface Listener {
boolean isService();
}
private Listener mListener;
MyEngine(Listener listener) { mListener = listener; }
}
class MyActivity extends Activity {
private mListener = new MyEngine.Listener() {
boolean isService() { return false; }
}
private MyEngine = new MyEngine(mListener);
...
}
class MyService extends Service {
private mListener = new MyEngine.Listener() {
boolean isService() { return true; }
}
private MyEngine = new MyEngine(mListener);
...
}
Notes.
The boolean value used in the above example is useless in the real world: if you want to use, say, different log file names, it is better to pass the file name rather than the boolean. If you want to perform two different actions, it's better to have one listener function with two implementations.
Of course, one could pass a Context
and check if it is a child of Activity
or a Service
, or get the name of the current process, but these things are Android-specific implementation details, and it's better not to depend on them unless absolutely necessary.